From f6e2d831cae0b8b867ac846f7126802bc18ab3fe Mon Sep 17 00:00:00 2001 From: leejet Date: Tue, 1 Dec 2026 22:03:14 +0800 Subject: [PATCH 1/2] perf: optimize MiniMax H3 video VAE encoding and decoding --- CMakeLists.txt | 2 +- cmake/backend_extensions.h.in | 1 + src/core/cuda/CMakeLists.txt | 8 +- src/core/cuda/registration.cu | 10 + src/core/cuda/rope.cu | 67 +++-- src/core/cuda/swiglu_f16.cu | 230 ++++++++++++++++++ src/core/cuda/vae_frame_norm.cu | 94 +++++++ src/core/cuda/vae_pad.cu | 62 +++++ src/core/ggml_extensions.cpp | 106 ++++++++ src/core/ggml_extensions.h | 22 ++ src/core/vulkan/CMakeLists.txt | 6 + src/core/vulkan/rope.cpp | 85 +++++-- src/core/vulkan/shaders/rms_rope_head64.comp | 76 ++++++ src/core/vulkan/shaders/swiglu_bias.comp | 31 +++ src/core/vulkan/shaders/vae_frame_norm.comp | 74 ++++++ src/core/vulkan/shaders/vae_pad_3d.comp | 39 +++ src/core/vulkan/vae.cpp | 166 +++++++++++++ src/model/vae/minimax_h3_vae.hpp | 243 +++++++++---------- src/runtime/tiling.cpp | 75 +++--- 19 files changed, 1202 insertions(+), 195 deletions(-) create mode 100644 src/core/cuda/swiglu_f16.cu create mode 100644 src/core/cuda/vae_frame_norm.cu create mode 100644 src/core/cuda/vae_pad.cu create mode 100644 src/core/vulkan/shaders/rms_rope_head64.comp create mode 100644 src/core/vulkan/shaders/swiglu_bias.comp create mode 100644 src/core/vulkan/shaders/vae_frame_norm.comp create mode 100644 src/core/vulkan/shaders/vae_pad_3d.comp create mode 100644 src/core/vulkan/vae.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index c50ae80067..1a70a6289a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -451,7 +451,7 @@ if (NOT SD_USE_UPSTREAM_GGML AND (SD_CUDA OR SD_HIPBLAS OR SD_MUSA)) endif() if (SD_VULKAN AND NOT SD_USE_UPSTREAM_GGML) add_subdirectory(src/core/vulkan) - list(APPEND SD_BACKEND_REGISTRATIONS sd_ggml_register_vulkan_rope sd_ggml_register_vulkan_i8 sd_ggml_register_vulkan_modulate sd_ggml_register_vulkan_rms_affine) + list(APPEND SD_BACKEND_REGISTRATIONS sd_ggml_register_vulkan_rope sd_ggml_register_vulkan_i8 sd_ggml_register_vulkan_modulate sd_ggml_register_vulkan_rms_affine sd_ggml_register_vulkan_vae) endif() if(SD_BACKEND_REGISTRATIONS) string(REPLACE ";" ",\n " SD_BACKEND_REGISTRATIONS "${SD_BACKEND_REGISTRATIONS}") diff --git a/cmake/backend_extensions.h.in b/cmake/backend_extensions.h.in index 602c3b4ae5..9fcaed802d 100644 --- a/cmake/backend_extensions.h.in +++ b/cmake/backend_extensions.h.in @@ -9,6 +9,7 @@ void sd_ggml_register_vulkan_rope(ggml_backend_dev_t device); void sd_ggml_register_vulkan_i8(ggml_backend_dev_t device); void sd_ggml_register_vulkan_rms_affine(ggml_backend_dev_t device); void sd_ggml_register_vulkan_modulate(ggml_backend_dev_t device); +void sd_ggml_register_vulkan_vae(ggml_backend_dev_t device); static void (*const sd_backend_extensions[])(ggml_backend_dev_t) = { @SD_BACKEND_REGISTRATIONS@ diff --git a/src/core/cuda/CMakeLists.txt b/src/core/cuda/CMakeLists.txt index c6dab2cfeb..dd205f72cc 100644 --- a/src/core/cuda/CMakeLists.txt +++ b/src/core/cuda/CMakeLists.txt @@ -2,7 +2,11 @@ cmake_policy(SET CMP0079 NEW) function(sd_cuda_sources VENDOR LANGUAGE) set(SOURCES) - foreach(OP rope int8 requantize i8_lora_merge w4 convrot affine modulate bf16 rms_affine registration) + set(OPERATORS rope int8 requantize i8_lora_merge w4 convrot affine modulate bf16 rms_affine vae_pad vae_frame_norm registration) + if(NOT VENDOR STREQUAL "musa") + list(APPEND OPERATORS swiglu_f16) + endif() + foreach(OP IN LISTS OPERATORS) 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 +62,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") + # Keep the GroupNorm reductions and SiLU division consistent with ggml-hip. + set_source_files_properties("${CMAKE_CURRENT_BINARY_DIR}/vae_frame_norm_hip.cu" PROPERTIES COMPILE_OPTIONS "-fno-fast-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") target_link_libraries(${SD_CUDA_TARGET} PRIVATE hip::host roc::hipblas) diff --git a/src/core/cuda/registration.cu b/src/core/cuda/registration.cu index 339474e025..e6708d89e5 100644 --- a/src/core/cuda/registration.cu +++ b/src/core/cuda/registration.cu @@ -18,6 +18,11 @@ namespace SD_CUDA_NAMESPACE { void register_modulate(ggml_backend_dev_t device); void register_bf16(ggml_backend_dev_t device); void register_rms_affine(ggml_backend_dev_t device); + void register_vae_pad(ggml_backend_dev_t device); + void register_vae_frame_norm(ggml_backend_dev_t device); +#if !defined(SD_CUDA_VENDOR_MUSA) + void register_swiglu_f16(ggml_backend_dev_t device); +#endif #if defined(SD_CUDA_VENDOR_HIP) void register_wmma_attention(ggml_backend_dev_t device); #endif @@ -39,6 +44,11 @@ namespace SD_CUDA_NAMESPACE { register_rope(device); register_bf16(device); register_rms_affine(device); + register_vae_pad(device); + register_vae_frame_norm(device); +#if !defined(SD_CUDA_VENDOR_MUSA) + register_swiglu_f16(device); +#endif #if defined(SD_CUDA_VENDOR_HIP) register_wmma_attention(device); #endif diff --git a/src/core/cuda/rope.cu b/src/core/cuda/rope.cu index 981b52dbae..dd51ebc3ae 100644 --- a/src/core/cuda/rope.cu +++ b/src/core/cuda/rope.cu @@ -13,7 +13,7 @@ namespace SD_CUDA_NAMESPACE { return v; } - template + template static __global__ __launch_bounds__(HiddenDim > 4096 ? 256 : HiddenDim ? HiddenDim / 4 : 128) void rms_norm_mul_rope_apply_fused(const float* x, const float* weight, @@ -75,14 +75,23 @@ namespace SD_CUDA_NAMESPACE { : (batch * heads + head) * tokens + token; T* out = dst + out_row * D; float v[D / 32], sums[8] = {}; + if constexpr (vector_norm) { + // Keep the same four-channel partial sums and warp reduction as native RMSNorm. + float sum = 0.f; + if (lane < D / 4) { + const auto values = reinterpret_cast(x_row)[lane]; + sum = values.x * values.x + values.y * values.y + values.z * values.z + values.w * values.w; + } + scale = rsqrtf(sd_warp_sum(sum) / float(D) + eps); + } #pragma unroll for (int j = 0; j < D / 32; ++j) { v[j] = x_row[j * 32 + lane]; - if constexpr (HiddenDim == 0) { + if constexpr (HiddenDim == 0 && !vector_norm) { sums[j] = sd_warp_sum(__fmul_rn(v[j], v[j])); } } - if constexpr (HiddenDim == 0) { + if constexpr (HiddenDim == 0 && !vector_norm) { // Preserve the 256-thread RMSNorm kernel's reduction tree, including inactive warps. const float sum = __fadd_rn( __fadd_rn(__fadd_rn(sums[0], sums[4]), __fadd_rn(sums[2], sums[6])), @@ -391,8 +400,16 @@ namespace SD_CUDA_NAMESPACE { return hidden_rope_cast_count(g, first); } if (first + 1 < ggml_graph_n_nodes(g) && - rope_non_affine_fusion_supports(ggml_graph_node(g, first), ggml_graph_node(g, first + 1))) + rope_non_affine_fusion_supports(ggml_graph_node(g, first), ggml_graph_node(g, first + 1))) { + if (first + 2 < ggml_graph_n_nodes(g)) { + const auto* rope = ggml_graph_node(g, first + 1); + const auto* cast = ggml_graph_node(g, first + 2); + if (cast->op == GGML_OP_CPY && cast->src[0] == rope && cast->src[1] == cast && !cast->view_src && + cast->type == GGML_TYPE_F16 && ggml_is_contiguous(cast) && ggml_are_same_shape(rope, cast)) + return 3; + } return 2; + } if (first + 2 >= ggml_graph_n_nodes(g) || !rope_fusion_supports( ggml_graph_node(g, first), ggml_graph_node(g, first + 1), ggml_graph_node(g, first + 2))) return 0; @@ -487,28 +504,40 @@ namespace SD_CUDA_NAMESPACE { return x <= y ? y - x < ggml_nbytes(a) : x - y < ggml_nbytes(b); } + template + static CUDAError non_affine_rope_launch(CUDAStream stream, const ggml_tensor* norm, const ggml_tensor* rope, T* output) { + const auto* x = norm->src[0]; + const auto* pe = rope->src[1]; + const int64_t rows = ggml_nrows(x); + const bool aligned = (reinterpret_cast(x->data) | x->nb[1] | x->nb[2] | x->nb[3]) % 16 == 0; + auto kernel = aligned ? rms_norm_mul_rope_apply_fused<64, false, T, false, 0, true> + : rms_norm_mul_rope_apply_fused<64, false, T, false>; + kernel<<((rows + 3) / 4), dim3(32, 4), 0, stream>>>( + static_cast(x->data), nullptr, static_cast(pe->data), output, + x->ne[1], x->ne[2], rows, x->nb[1] / 4, x->nb[2] / 4, x->nb[3] / 4, int(pe->ne[2]), param_f32(norm, 0), 1.f); + return cuda_last_error(); + } + static ggml_status rope_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int count, void*, void*) { ggml_ext_gpu_context context; if (!cuda_context(execution->backend, &context)) return GGML_STATUS_FAILED; - auto stream = static_cast(context.stream); - const bool hidden = count >= 4 && rope_is_node(nodes[3]); - const auto* rope = nodes[hidden ? 3 : count <= 2 ? count - 1 - : 2]; - const auto* x = count == 1 ? rope->src[0] : nodes[0]->src[0]; - auto* dst = nodes[count - 1]; - const bool alias = overlaps(dst, x) || overlaps(dst, rope->src[1]) || (count > 2 && overlaps(dst, nodes[1]->src[1])); - void* output = alias ? ggml_backend_buffer_get_base(execution->workspace) : dst->data; + auto stream = static_cast(context.stream); + const bool hidden = count >= 4 && rope_is_node(nodes[3]); + const bool non_affine = count >= 2 && rope_is_node(nodes[1]); + const auto* rope = nodes[hidden ? 3 : non_affine ? 1 + : count > 1 ? 2 + : 0]; + const auto* x = count == 1 ? rope->src[0] : nodes[0]->src[0]; + auto* dst = nodes[count - 1]; + const bool alias = overlaps(dst, x) || overlaps(dst, rope->src[1]) || (count > 2 && !non_affine && overlaps(dst, nodes[1]->src[1])); + void* output = alias ? ggml_backend_buffer_get_base(execution->workspace) : dst->data; CUDAError error; if (hidden) { error = hidden_rope_launch(stream, nodes, output, dst->type == GGML_TYPE_F16, 1.f); - } else if (count == 2) { - const auto* pe = rope->src[1]; - const int64_t rows = ggml_nrows(x); - rms_norm_mul_rope_apply_fused<64, false, float, false><<((rows + 3) / 4), dim3(32, 4), 0, stream>>>( - static_cast(x->data), nullptr, static_cast(pe->data), static_cast(output), - x->ne[1], x->ne[2], rows, x->nb[1] / 4, x->nb[2] / 4, x->nb[3] / 4, int(pe->ne[2]), param_f32(nodes[0], 0), 1.f); - error = cuda_last_error(); + } else if (non_affine) { + error = dst->type == GGML_TYPE_F16 ? non_affine_rope_launch(stream, nodes[0], rope, static_cast(output)) + : non_affine_rope_launch(stream, nodes[0], rope, static_cast(output)); } else if (count > 2) { error = rms_rope_launch(stream, nodes, output, count > 3, count == 5 ? param_f32(nodes[3], 0) : 1.f); } else { diff --git a/src/core/cuda/swiglu_f16.cu b/src/core/cuda/swiglu_f16.cu new file mode 100644 index 0000000000..c3bc4b06b8 --- /dev/null +++ b/src/core/cuda/swiglu_f16.cu @@ -0,0 +1,230 @@ +#include "core/cuda/runtime.h" + +#if defined(SD_CUDA_VENDOR_HIP) +#include +#else +#include +#endif + +#include +#include +#include +#include + +namespace SD_CUDA_NAMESPACE { + +#if defined(SD_CUDA_VENDOR_HIP) + using BlasHandle = hipblasHandle_t; +#else + using BlasHandle = cublasHandle_t; +#endif + + static bool matrix(const ggml_tensor* tensor, ggml_type type) { + return tensor && tensor->type == type && ggml_is_contiguous(tensor) && tensor->ne[2] == 1 && + tensor->ne[3] == 1 && ggml_nelements(tensor) > 0 && ggml_nelements(tensor) <= INT_MAX; + } + + static bool projection(const ggml_tensor* mat) { + return mat->op == GGML_OP_MUL_MAT && ggml_prec_get_acc(mat) == GGML_PREC_UNDEFINED && + matrix(mat, GGML_TYPE_F32) && !mat->view_src && matrix(mat->src[0], GGML_TYPE_F16) && + matrix(mat->src[1], GGML_TYPE_F32) && mat->ne[0] % 8 == 0 && mat->src[0]->ne[0] % 8 == 0; + } + + static bool aligned(const ggml_tensor* tensor, size_t alignment) { + size_t offset = 0; + while (!tensor->data && tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + return (reinterpret_cast(tensor->data) + offset) % alignment == 0; + } + + static int swiglu_match(ggml_backend_dev_t, const ggml_cgraph* graph, int first, void*) { + static const bool disabled = [] { + const char* fusion = std::getenv("GGML_CUDA_DISABLE_FUSION"); + return (fusion && std::atoi(fusion)) || std::getenv("GGML_CUDA_CUBLAS_COMPUTE_TYPE"); + }(); + auto* g = const_cast(graph); + if (disabled || first + 3 >= ggml_graph_n_nodes(g)) + return 0; + const auto* w1 = ggml_graph_node(g, first); + const auto* add = ggml_graph_node(g, first + 1); + const auto* glu = ggml_graph_node(g, first + 2); + const auto* w2 = ggml_graph_node(g, first + 3); + if (!projection(w1) || !projection(w2) || w1->ne[1] < 128 || w1->ne[1] > 65535 || + add->op != GGML_OP_ADD || add->src[0] != w1 || !ggml_are_same_shape(w1, add) || + glu->op != GGML_OP_GLU || ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU || glu->op_params[1] != 0 || + glu->src[0] != add || glu->src[1] || w2->src[1] != glu) + return 0; + const auto* bias = add->src[1]; + return matrix(bias, GGML_TYPE_F32) && bias->ne[0] == w1->ne[0] && bias->ne[1] == 1 && + aligned(bias, alignof(float2)) && aligned(w1->src[1], alignof(float4)) + ? 4 + : 0; + } + + static size_t activation_half_count(ggml_tensor* const* nodes) { + return GGML_PAD(size_t(std::max(ggml_nelements(nodes[0]->src[1]), ggml_nelements(nodes[2]))), 128); + } + + static ggml_status swiglu_prepare(ggml_backend_t, ggml_tensor* const* nodes, int, void**, size_t* workspace, void* user_data) { + const bool fp32_result = *static_cast(user_data); + const size_t projection_bytes = fp32_result ? sizeof(float) * ggml_nelements(nodes[0]) + : sizeof(half) * std::max(ggml_nelements(nodes[0]), ggml_nelements(nodes[3])); + *workspace = sizeof(half) * activation_half_count(nodes) + projection_bytes; + return GGML_STATUS_SUCCESS; + } + + static void swiglu_destroy(void*, void*) {} + + static __global__ void f32_to_f16(const float4* src, half2* dst, int vectors) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < vectors) { + const float4 value = src[i]; + dst[2 * i] = __floats2half2_rn(value.x, value.y); + dst[2 * i + 1] = __floats2half2_rn(value.z, value.w); + } + } + + static __global__ void f16_to_f32(const half2* src, float2* dst, int pairs) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < pairs) + dst[i] = __half22float2(src[i]); + } + + static __device__ __forceinline__ float swiglu_bias(float gate, float up, float gate_bias, float up_bias) { + gate = __fadd_rn(gate, gate_bias); + up = __fadd_rn(up, up_bias); + return __fmul_rn(gate / (1.f + expf(-gate)), up); + } + + static __device__ __forceinline__ float2 to_float2(half2 value) { + return __half22float2(value); + } + static __device__ __forceinline__ float2 to_float2(float2 value) { + return value; + } + + template + static __global__ void swiglu_bias_f16(const Pair* src, const float2* bias, half2* dst, int pairs) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= pairs) + return; + const size_t row = size_t(blockIdx.y) * pairs; + const float2 gate = to_float2(src[2 * row + i]); + const float2 up = to_float2(src[2 * row + pairs + i]); + const float2 gate_bias = bias[i]; + const float2 up_bias = bias[pairs + i]; + dst[row + i] = __floats2half2_rn(swiglu_bias(gate.x, up.x, gate_bias.x, up_bias.x), + swiglu_bias(gate.y, up.y, gate_bias.y, up_bias.y)); + } + + static bool gemm_f16(BlasHandle handle, const ggml_tensor* mat, const half* input, void* output, bool fp32_result) { + const auto* weight = mat->src[0]; + const int n = int(mat->ne[0]), rows = int(mat->ne[1]), k = int(weight->ne[0]); + const half alpha = __float2half(1.f), beta = __float2half(0.f); +#if defined(SD_CUDA_VENDOR_HIP) +#if HIP_VERSION >= 60500000 || defined(HIPBLAS_V2) + constexpr auto f32_compute = HIPBLAS_COMPUTE_32F, f16_compute = HIPBLAS_COMPUTE_16F; +#else + constexpr auto f32_compute = HIPBLAS_R_32F, f16_compute = HIPBLAS_R_16F; +#endif +#if HIP_VERSION >= 70000000 || defined(HIPBLAS_V2) + constexpr auto f32_type = HIP_R_32F, f16_type = HIP_R_16F; +#else + constexpr auto f32_type = HIPBLAS_R_32F, f16_type = HIPBLAS_R_16F; +#endif + const float alpha_f32 = 1.f, beta_f32 = 0.f; + const void* a = fp32_result ? static_cast(&alpha_f32) : static_cast(&alpha); + const void* b = fp32_result ? static_cast(&beta_f32) : static_cast(&beta); + return hipblasGemmEx(handle, HIPBLAS_OP_T, HIPBLAS_OP_N, n, rows, k, a, weight->data, f16_type, k, + input, f16_type, k, b, output, fp32_result ? f32_type : f16_type, n, + fp32_result ? f32_compute : f16_compute, HIPBLAS_GEMM_DEFAULT) == HIPBLAS_STATUS_SUCCESS; +#else + GGML_ASSERT(!fp32_result); + return cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, n, rows, k, &alpha, weight->data, CUDA_R_16F, k, + input, CUDA_R_16F, k, &beta, output, CUDA_R_16F, n, CUBLAS_COMPUTE_16F, + CUBLAS_GEMM_DEFAULT_TENSOR_OP) == CUBLAS_STATUS_SUCCESS; +#endif + } + + static ggml_status swiglu_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int, void*, void* user_data) { + ggml_ext_gpu_context context; + if (!cuda_context(execution->backend, &context)) + return GGML_STATUS_FAILED; + const auto reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(execution->backend)); + const auto query = reinterpret_cast(ggml_backend_reg_get_proc_address(reg, "ggml_ext_gpu_blas_v1")); + const auto handle = query ? static_cast(query(execution->backend)) : nullptr; + if (!handle) + return GGML_STATUS_FAILED; + + const bool fp32_result = *static_cast(user_data); + const auto stream = static_cast(context.stream); + auto* activation = static_cast(ggml_backend_buffer_get_base(execution->workspace)); + auto* projection = activation + activation_half_count(nodes); + const auto* input = nodes[0]->src[1]; + auto* dst = nodes[3]; + constexpr int block = 256; + const int vectors = int(ggml_nelements(input) / 4); + f32_to_f16<<<(vectors + block - 1) / block, block, 0, stream>>>( + static_cast(input->data), reinterpret_cast(activation), vectors); + if (cuda_last_error() != cuda_success || !gemm_f16(handle, nodes[0], activation, projection, fp32_result)) + return GGML_STATUS_FAILED; + + // Apply bias and SwiGLU in FP32 to the native GEMM's rounded output. + const int gate_pairs = int(nodes[2]->ne[0] / 2); + const dim3 grid((gate_pairs + block - 1) / block, unsigned(dst->ne[1])); + const auto* bias = static_cast(nodes[1]->src[1]->data); + auto* packed = reinterpret_cast(activation); + if (fp32_result) { + swiglu_bias_f16<<>>(reinterpret_cast(projection), bias, packed, gate_pairs); + } else { + swiglu_bias_f16<<>>(reinterpret_cast(projection), bias, packed, gate_pairs); + } + void* output = fp32_result ? dst->data : projection; + if (cuda_last_error() != cuda_success || !gemm_f16(handle, dst, activation, output, fp32_result)) + return GGML_STATUS_FAILED; + if (fp32_result) + return GGML_STATUS_SUCCESS; + + const int out_pairs = int(ggml_nelements(dst) / 2); + f16_to_f32<<<(out_pairs + block - 1) / block, block, 0, stream>>>( + reinterpret_cast(projection), static_cast(dst->data), out_pairs); + return cuda_last_error() == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED; + } + + void register_swiglu_f16(ggml_backend_dev_t device) { + const auto info = cuda_device_info(device); + if (info.device < 0 || !ggml_backend_reg_get_proc_address(ggml_backend_dev_backend_reg(device), "ggml_ext_gpu_blas_v1")) + return; + bool fp32_result = false; +#if defined(SD_CUDA_VENDOR_HIP) + hipDeviceProp_t props; + if (hipGetDeviceProperties(&props, info.device) != hipSuccess || std::strncmp(props.gcnArchName, "gfx", 3)) + return; + char* suffix; + const auto arch = std::strtoul(props.gcnArchName + 3, &suffix, 16); + if (arch < 0x803 || (*suffix && *suffix != ':')) + return; + // Match ggml's FP32 result path on CDNA and gfx1200+ (gfx909/gfx90c are GCN APUs). + fp32_result = arch >= 0x1200 || (arch >= 0x908 && arch < 0x1010 && arch != 0x909 && arch != 0x90c); +#else + cudaDeviceProp props; + if (cudaGetDeviceProperties(&props, info.device) != cudaSuccess || props.major < 8) + return; +#endif + static bool fp32_modes[] = {false, true}; + ggml_ext_kernel_desc desc = {}; + desc.user_data = &fp32_modes[fp32_result]; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.swiglu_f16_matmul." SD_CUDA_NAME ".v1"; + desc.op = GGML_OP_MUL_MAT; + desc.priority = 200; + desc.match = swiglu_match; + desc.prepare = swiglu_prepare; + desc.destroy = swiglu_destroy; + desc.execute = swiglu_execute; + 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/vae_frame_norm.cu b/src/core/cuda/vae_frame_norm.cu new file mode 100644 index 0000000000..117422135b --- /dev/null +++ b/src/core/cuda/vae_frame_norm.cu @@ -0,0 +1,94 @@ +#include "core/cuda/runtime.h" +#include "core/ggml_extensions.h" + +namespace SD_CUDA_NAMESPACE { + + constexpr int norm_threads = 1024; + constexpr int norm_warp = 32; + + static __device__ __forceinline__ float block_sum(float value, float* partials) { + const int lane = threadIdx.x % norm_warp; +#pragma unroll + for (int offset = norm_warp / 2; offset > 0; offset >>= 1) + value += cuda_shuffle_xor(value, offset, norm_warp); + if (lane == 0) + partials[threadIdx.x / norm_warp] = value; + __syncthreads(); + value = partials[lane]; +#pragma unroll + for (int offset = norm_warp / 2; offset > 0; offset >>= 1) + value += cuda_shuffle_xor(value, offset, norm_warp); + return value; + } + + static __global__ void vae_frame_norm(const float* src, const float* weight, const float* bias, float* dst, int spatial, int frames, int groups, int group_channels, float eps) { + const int group = blockIdx.x % groups; + const int frame = blockIdx.y; + const int first_channel = group * group_channels; + const int plane_stride = frames * spatial; + const int base = (blockIdx.x / groups * groups * group_channels + first_channel) * plane_stride + frame * spatial; + src += base; + dst += base; + + // Keep the native GroupNorm reduction order over the logical [spatial, channels] group. + __shared__ float sums[2][norm_threads / norm_warp]; + float sum = 0.f; + for (int channel = 0; channel < group_channels; ++channel) + for (int pixel = threadIdx.x; pixel < spatial; pixel += norm_threads) + sum += src[channel * plane_stride + pixel]; + const int group_size = spatial * group_channels; + const float mean = block_sum(sum, sums[0]) / group_size; + float squares = 0.f; + for (int channel = 0; channel < group_channels; ++channel) { + for (int pixel = threadIdx.x; pixel < spatial; pixel += norm_threads) { + const float centered = src[channel * plane_stride + pixel] - mean; + squares += centered * centered; + } + } + const float scale = rsqrtf(block_sum(squares, sums[1]) / group_size + eps); + for (int channel = 0; channel < group_channels; ++channel) { + const float gain = weight[first_channel + channel]; + const float offset = bias[first_channel + channel]; + for (int pixel = threadIdx.x; pixel < spatial; pixel += norm_threads) { + const int index = channel * plane_stride + pixel; + const float normalized = (src[index] - mean) * scale; + const float value = __fadd_rn(__fmul_rn(normalized, gain), offset); + dst[index] = value / (1.f + expf(-value)); + } + } + } + + static bool frame_norm_supports(ggml_backend_dev_t, const ggml_tensor* dst, void*) { + SDVAEFrameNormParams params; + return sd_ggml_vae_frame_norm_describe(dst, ¶ms) && ggml_nelements(dst) <= INT32_MAX && + dst->ne[0] * dst->ne[1] % norm_threads == 0 && dst->ne[2] <= 65535; + } + + static ggml_status frame_norm_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int, void*, void*) { + ggml_ext_gpu_context context; + auto* dst = nodes[0]; + SDVAEFrameNormParams params; + if (!cuda_context(execution->backend, &context) || !sd_ggml_vae_frame_norm_describe(dst, ¶ms)) + return GGML_STATUS_FAILED; + + const int channels = int(dst->src[1]->ne[0]); + const dim3 grid(unsigned(dst->ne[3] / channels * params.groups), unsigned(dst->ne[2])); + vae_frame_norm<<(context.stream)>>>( + static_cast(dst->src[0]->data), static_cast(dst->src[1]->data), + static_cast(dst->src[2]->data), static_cast(dst->data), + int(dst->ne[0] * dst->ne[1]), int(dst->ne[2]), params.groups, channels / params.groups, params.eps); + return cuda_last_error() == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED; + } + + void register_vae_frame_norm(ggml_backend_dev_t device) { + ggml_ext_kernel_desc desc = {}; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.vae_frame_norm." SD_CUDA_NAME ".v1"; + desc.op = GGML_OP_CUSTOM; + desc.custom_op = sd_ggml_vae_frame_norm_op(); + desc.priority = 100; + desc.supports = frame_norm_supports; + desc.execute = frame_norm_execute; + 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/vae_pad.cu b/src/core/cuda/vae_pad.cu new file mode 100644 index 0000000000..3a6a1d54fc --- /dev/null +++ b/src/core/cuda/vae_pad.cu @@ -0,0 +1,62 @@ +#include "core/cuda/runtime.h" +#include "core/ggml_extensions.h" + +namespace SD_CUDA_NAMESPACE { + + static __global__ void vae_pad_3d(const float* src, float* dst, int width, int height, int frames, int out_width, int out_height, int out_frames, SDVAEPad3DParams pad) { + const int x = blockIdx.x * blockDim.x + threadIdx.x; + const int y = blockIdx.y * blockDim.y + threadIdx.y; + if (x >= out_width || y >= out_height) + return; + const int plane = blockIdx.z; + const int frame = plane % out_frames - pad.front; + const size_t out = (size_t(plane) * out_height + y) * out_width + x; + if (frame < 0) { + dst[out] = 0.f; + return; + } + + int src_x = x - pad.left; + int src_y = y - pad.top; + src_x = src_x < 0 ? 1 : src_x == width ? width - 2 + : src_x; + src_y = src_y < 0 ? 1 : src_y == height ? height - 2 + : src_y; + const int channel = plane / out_frames; + dst[out] = src[((size_t(channel) * frames + frame) * height + src_y) * width + src_x]; + } + + static bool vae_pad_supports(ggml_backend_dev_t, const ggml_tensor* dst, void*) { + SDVAEPad3DParams pad; + return sd_ggml_vae_pad_3d_describe(dst, &pad) && + dst->ne[0] < INT32_MAX - 32 && dst->ne[1] <= 65535 && dst->ne[2] <= 65535 / dst->ne[3]; + } + + static ggml_status vae_pad_execute(const ggml_ext_execution_context* execution, ggml_tensor* const* nodes, int, void*, void*) { + ggml_ext_gpu_context context; + auto* dst = nodes[0]; + SDVAEPad3DParams pad; + if (!cuda_context(execution->backend, &context) || !sd_ggml_vae_pad_3d_describe(dst, &pad)) + return GGML_STATUS_FAILED; + + const auto* src = dst->src[0]; + const dim3 block(32, 8); + const dim3 grid((dst->ne[0] + block.x - 1) / block.x, (dst->ne[1] + block.y - 1) / block.y, dst->ne[2] * dst->ne[3]); + vae_pad_3d<<(context.stream)>>>( + static_cast(src->data), static_cast(dst->data), int(src->ne[0]), int(src->ne[1]), int(src->ne[2]), + int(dst->ne[0]), int(dst->ne[1]), int(dst->ne[2]), pad); + return cuda_last_error() == cuda_success ? GGML_STATUS_SUCCESS : GGML_STATUS_FAILED; + } + + void register_vae_pad(ggml_backend_dev_t device) { + ggml_ext_kernel_desc desc = {}; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.vae_pad_3d." SD_CUDA_NAME ".v1"; + desc.op = GGML_OP_CUSTOM; + desc.custom_op = sd_ggml_vae_pad_3d_op(); + desc.priority = 100; + desc.supports = vae_pad_supports; + desc.execute = vae_pad_execute; + GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE)); + } +} diff --git a/src/core/ggml_extensions.cpp b/src/core/ggml_extensions.cpp index 5d52748600..0aa0f8adb7 100644 --- a/src/core/ggml_extensions.cpp +++ b/src/core/ggml_extensions.cpp @@ -152,6 +152,112 @@ bool sd_ggml_rope_describe(const ggml_tensor* node) { std::memcmp(output.ne, node->ne, sizeof(output.ne)) == 0; } +static bool vae_pad_3d_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* out) { + if (count != 1 || !attributes || !inputs[0] || inputs[0]->type != GGML_TYPE_F32 || !ggml_is_contiguous(inputs[0])) + return false; + SDVAEPad3DParams pad; + std::memcpy(&pad, attributes, sizeof(pad)); + const auto* x = inputs[0]; + for (auto p : {pad.left, pad.right, pad.top, pad.bottom}) { + if (p < 0 || p > 1) + return false; + } + if (pad.front < 0 || x->ne[0] <= std::max(pad.left, pad.right) || x->ne[1] <= std::max(pad.top, pad.bottom) || + x->ne[2] <= 0 || x->ne[3] <= 0) + return false; + *out = {GGML_TYPE_F32, {x->ne[0] + pad.left + pad.right, x->ne[1] + pad.top + pad.bottom, x->ne[2] + pad.front, x->ne[3]}}; + return true; +} + +ggml_ext_op_t sd_ggml_vae_pad_3d_op() { + static const auto op = [] { + const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.vae_pad_3d.v1", sizeof(SDVAEPad3DParams), vae_pad_3d_infer}; + auto result = ggml_ext_register_op(&desc); + GGML_ASSERT(result); + return result; + }(); + return op; +} + +bool sd_ggml_vae_pad_3d_describe(const ggml_tensor* node, SDVAEPad3DParams* params) { + if (ggml_ext_op_get(node) != sd_ggml_vae_pad_3d_op() || !ggml_is_contiguous(node) || node->src[1]) + return false; + const auto* attributes = ggml_ext_op_attributes(node); + ggml_ext_tensor_desc out; + if (!vae_pad_3d_infer(node->src, 1, attributes, &out) || node->type != out.type || std::memcmp(out.ne, node->ne, sizeof(out.ne)) != 0) + return false; + std::memcpy(params, attributes, sizeof(*params)); + return true; +} + +static bool vae_frame_norm_infer(ggml_tensor* const* inputs, int count, const void* attributes, ggml_ext_tensor_desc* out) { + if (count != 3 || !attributes) + return false; + for (int i = 0; i < count; ++i) { + if (!inputs[i] || inputs[i]->type != GGML_TYPE_F32 || !ggml_is_contiguous(inputs[i])) + return false; + } + SDVAEFrameNormParams params; + std::memcpy(¶ms, attributes, sizeof(params)); + const auto* x = inputs[0]; + const int64_t channels = inputs[1]->ne[0]; + if (params.groups <= 0 || !(params.eps > 0.f) || channels <= 0 || channels % params.groups != 0 || + ggml_nelements(inputs[1]) != channels || inputs[2]->ne[0] != channels || ggml_nelements(inputs[2]) != channels || + ggml_nelements(x) == 0 || x->ne[3] % channels != 0) + return false; + *out = {x->type, {x->ne[0], x->ne[1], x->ne[2], x->ne[3]}}; + return true; +} + +ggml_ext_op_t sd_ggml_vae_frame_norm_op() { + static const auto op = [] { + const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.vae_frame_norm.v1", sizeof(SDVAEFrameNormParams), vae_frame_norm_infer}; + auto result = ggml_ext_register_op(&desc); + GGML_ASSERT(result); + return result; + }(); + return op; +} + +bool sd_ggml_vae_frame_norm_describe(const ggml_tensor* node, SDVAEFrameNormParams* params) { + if (ggml_ext_op_get(node) != sd_ggml_vae_frame_norm_op() || !ggml_is_contiguous(node) || node->src[3]) + return false; + const auto* attributes = ggml_ext_op_attributes(node); + ggml_ext_tensor_desc out; + if (!vae_frame_norm_infer(node->src, 3, attributes, &out) || node->type != out.type || !ggml_are_same_shape(node, node->src[0])) + return false; + std::memcpy(params, attributes, sizeof(*params)); + return true; +} + +static bool swiglu_bias_infer(ggml_tensor* const* inputs, int count, const void*, ggml_ext_tensor_desc* out) { + if (count != 2) + return false; + const auto* x = inputs[0]; + const auto* bias = inputs[1]; + if (!x || !bias || x->type != GGML_TYPE_F32 || bias->type != GGML_TYPE_F32 || !ggml_is_contiguous(x) || + !ggml_is_contiguous(bias) || x->ne[0] % 2 != 0 || bias->ne[0] != x->ne[0] || ggml_nelements(bias) != x->ne[0]) + return false; + *out = {GGML_TYPE_F32, {x->ne[0] / 2, x->ne[1], x->ne[2], x->ne[3]}}; + return true; +} + +ggml_ext_op_t sd_ggml_swiglu_bias_op() { + static const auto op = [] { + const ggml_ext_op_desc desc = {GGML_EXT_ABI_VERSION, "sd.swiglu_bias.v1", 0, swiglu_bias_infer}; + auto result = ggml_ext_register_op(&desc); + GGML_ASSERT(result); + return result; + }(); + return op; +} + +bool sd_ggml_swiglu_bias_describe(const ggml_tensor* node) { + ggml_ext_tensor_desc out; + return ggml_ext_op_get(node) == sd_ggml_swiglu_bias_op() && !node->src[2] && ggml_is_contiguous(node) && + swiglu_bias_infer(node->src, 2, nullptr, &out) && node->type == out.type && std::memcmp(out.ne, node->ne, sizeof(out.ne)) == 0; +} + bool sd_ggml_valid_convrot_group(int group) { return group == 1 || group == 4 || group == 16 || group == 64 || group == 256; } diff --git a/src/core/ggml_extensions.h b/src/core/ggml_extensions.h index 4d1ebbb954..1da179e608 100644 --- a/src/core/ggml_extensions.h +++ b/src/core/ggml_extensions.h @@ -19,6 +19,28 @@ ggml_ext_op_t sd_ggml_rope_op(); bool sd_ggml_rope_describe(const ggml_tensor* node); +struct SDVAEPad3DParams { + int32_t left; + int32_t right; + int32_t top; + int32_t bottom; + int32_t front; +}; + +ggml_ext_op_t sd_ggml_vae_pad_3d_op(); +bool sd_ggml_vae_pad_3d_describe(const ggml_tensor* node, SDVAEPad3DParams* params); + +struct SDVAEFrameNormParams { + int32_t groups; + float eps; +}; + +ggml_ext_op_t sd_ggml_vae_frame_norm_op(); +bool sd_ggml_vae_frame_norm_describe(const ggml_tensor* node, SDVAEFrameNormParams* params); + +ggml_ext_op_t sd_ggml_swiglu_bias_op(); +bool sd_ggml_swiglu_bias_describe(const ggml_tensor* node); + struct SDI8Attributes { int64_t shape[3]; int32_t group_size; diff --git a/src/core/vulkan/CMakeLists.txt b/src/core/vulkan/CMakeLists.txt index 8a26fec8bd..e677466962 100644 --- a/src/core/vulkan/CMakeLists.txt +++ b/src/core/vulkan/CMakeLists.txt @@ -52,6 +52,11 @@ sd_vulkan_shader(modulate modulate ON -O) sd_vulkan_shader(rms_modulate rms_modulate ON -O) 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(rms_rope_head64 rms_rope_head64 ON) +sd_vulkan_shader(rms_rope_head64_cast rms_rope_head64 ON -DCAST_F16) +sd_vulkan_shader(vae_pad_3d vae_pad_3d ON -O) +sd_vulkan_shader(vae_frame_norm vae_frame_norm ON -O) +sd_vulkan_shader(swiglu_bias swiglu_bias ON -O) 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(quantize_i8_rowwise pack_i8_rows ${SD_VK_DOT} -O) @@ -91,4 +96,5 @@ sd_vulkan_shader(mul_mat_i8_residual_cm2 mul_mat_i8_tensorwise_cm2 ${SD_VK_CM2} add_custom_target(sd-vulkan-shaders DEPENDS ${SD_VULKAN_HEADERS}) add_dependencies(${SD_LIB} sd-vulkan-shaders) target_sources(${SD_LIB} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/rope.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/int8.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/modulate.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/rms_affine.cpp") +target_sources(${SD_LIB} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/vae.cpp") target_include_directories(${SD_LIB} PRIVATE "${SD_VULKAN_GENERATED}") diff --git a/src/core/vulkan/rope.cpp b/src/core/vulkan/rope.cpp index 194603e13d..fb88114c8b 100644 --- a/src/core/vulkan/rope.cpp +++ b/src/core/vulkan/rope.cpp @@ -2,6 +2,8 @@ #include "ggml-ext-vulkan.h" #include "rms_rope_apply.h" #include "rms_rope_cast.h" +#include "rms_rope_head64.h" +#include "rms_rope_head64_cast.h" #include "rope_apply.h" #include @@ -77,6 +79,27 @@ namespace sd_vulkan_rope { weight->type == GGML_TYPE_F32 && weight->ne[0] == 128 && ggml_nelements(weight) == 128 && ggml_is_contiguous(weight) && bounded(weight, info) && bounded(x, info) && (x->ne[1] + 3) / 4 <= info.max_group_count[0]; } + static bool head64_supports(ggml_backend_dev_t device, const ggml_tensor* norm, const ggml_tensor* rope) { + if (norm->op != GGML_OP_RMS_NORM || !is_rope(rope) || rope->src[0] != norm || !supports(device, rope, nullptr)) + return false; + const auto* x = norm->src[0]; + if (!x || x->type != GGML_TYPE_F32 || x->ne[0] != 64 || x->nb[0] != 4 || !ggml_are_same_shape(x, norm)) + return false; + uint32_t interleaved; + std::memcpy(&interleaved, ggml_ext_op_attributes(rope), sizeof(interleaved)); + if (interleaved != 0) + return false; + ggml_ext_vulkan_device_info info; + if (!api(device)->device_info(device, &info) || info.fusion_disabled || !info.full_subgroups || + (info.subgroup_size != 32 && info.subgroup_size != 64) || !bounded(x, info) || + (x->ne[1] + 1) / 2 > info.max_group_count[0] || info.max_push_constants < sizeof(FusedParameters)) + return false; + const auto reg = ggml_backend_dev_backend_reg(device); + auto query = reinterpret_cast(ggml_backend_reg_get_proc_address(reg, "ggml_ext_vulkan_compute_v1")); + const auto* compute = query ? query() : nullptr; + ggml_ext_vulkan_compute_info compute_info; + return compute && compute->properties(device, &compute_info) && compute_info.subgroup_arithmetic; + } static bool cast_supports(ggml_backend_dev_t device, const ggml_tensor* rope, const ggml_tensor* scale, const ggml_tensor* copy) { ggml_ext_vulkan_device_info info; api(device)->device_info(device, &info); @@ -85,8 +108,17 @@ namespace sd_vulkan_rope { copy->op == GGML_OP_CPY && copy->src[0] == (scale ? scale : rope) && copy->type == GGML_TYPE_F16 && ggml_is_contiguous(copy) && aligned(copy, 4) && ggml_are_same_shape(rope, copy); } + static bool head64_cast_supports(ggml_backend_dev_t device, const ggml_tensor* rope, const ggml_tensor* copy) { + return copy->src[1] == copy && !copy->view_src && cast_supports(device, rope, nullptr, copy); + } static int match(ggml_backend_dev_t device, const ggml_cgraph* graph, int first, void*) { auto* g = const_cast(graph); + if (first + 1 < ggml_graph_n_nodes(g)) { + const auto* rope = ggml_graph_node(g, first + 1); + if (head64_supports(device, ggml_graph_node(g, first), rope)) { + return first + 2 < ggml_graph_n_nodes(g) && head64_cast_supports(device, rope, ggml_graph_node(g, first + 2)) ? 3 : 2; + } + } if (first + 2 >= ggml_graph_n_nodes(g) || !fused_supports(device, ggml_graph_node(g, first), ggml_graph_node(g, first + 1), ggml_graph_node(g, first + 2))) return 0; if (first + 4 < ggml_graph_n_nodes(g) && cast_supports(device, ggml_graph_node(g, first + 2), ggml_graph_node(g, first + 3), ggml_graph_node(g, first + 4))) @@ -94,22 +126,33 @@ namespace sd_vulkan_rope { return first + 3 < ggml_graph_n_nodes(g) && cast_supports(device, ggml_graph_node(g, first + 2), nullptr, ggml_graph_node(g, first + 3)) ? 4 : 3; } static void optimize(ggml_backend_dev_t device, ggml_cgraph* graph, void*) { - for (int last = 2; last < ggml_graph_n_nodes(graph); ++last) { + for (int last = 1; last < ggml_graph_n_nodes(graph); ++last) { const auto* output = ggml_graph_node(graph, last); const auto* source = output->op == GGML_OP_CPY ? output->src[0] : nullptr; const auto* scale = source && source->op == GGML_OP_SCALE ? source : nullptr; const auto* rope = source ? (scale ? scale->src[0] : source) : output; if (!is_rope(rope)) continue; - const auto* mul = rope->src[0]; - const auto* norm = mul->src[0]; - if (!norm || !fused_supports(device, norm, mul, rope)) - continue; - const int count = output == rope ? 3 : cast_supports(device, rope, scale, output) ? (scale ? 5 : 4) - : 0; - if (!count) - continue; - const ggml_tensor* nodes[] = {norm, mul, rope, scale ? scale : output, output}; + const auto* precursor = rope->src[0]; + const ggml_tensor* nodes[5]; + int count = 0; + if (precursor->op == GGML_OP_RMS_NORM) { + if (!head64_supports(device, precursor, rope) || (output != rope && !head64_cast_supports(device, rope, output))) + continue; + nodes[count++] = precursor; + } else { + const auto* norm = precursor->src[0]; + if (!norm || !fused_supports(device, norm, precursor, rope) || + (output != rope && !cast_supports(device, rope, scale, output))) + continue; + nodes[count++] = norm; + nodes[count++] = precursor; + } + nodes[count++] = rope; + if (scale) + nodes[count++] = scale; + if (output != rope) + nodes[count++] = output; int indices[5], next = count - 1; for (int i = last; i >= std::max(0, last - 64) && next >= 0; --i) if (ggml_graph_node(graph, i) == nodes[next]) @@ -140,17 +183,19 @@ namespace sd_vulkan_rope { ggml_ext_vulkan_device_info info; if (!service || !service->device_info(device, &info)) return GGML_STATUS_FAILED; - const auto* rope = nodes[count == 1 ? 0 : 2]; + const bool head64 = count > 1 && is_rope(nodes[1]); + const auto* rope = nodes[count == 1 ? 0 : head64 ? 1 + : 2]; const auto* x = count == 1 ? rope->src[0] : nodes[0]->src[0]; const auto* pe = rope->src[1]; const auto* output = nodes[count - 1]; - ggml_ext_vulkan_binding bindings[] = {{x}, {pe}, {output}, {count == 1 ? nullptr : nodes[1]->src[1]}}; + ggml_ext_vulkan_binding bindings[] = {{x}, {pe}, {output}, {count == 1 || head64 ? nullptr : nodes[1]->src[1]}}; ggml_ext_vulkan_buffer_info buffers[4]; - const int n_buffers = count == 1 ? 3 : 4; + const int n_buffers = count == 1 || head64 ? 3 : 4; for (int i = 0; i < n_buffers; ++i) if (!service->buffer_info(execution->backend, bindings + i, buffers + i)) return GGML_STATUS_FAILED; - bool alias = overlaps(buffers[2], buffers[0]) || overlaps(buffers[2], buffers[1]) || (count != 1 && overlaps(buffers[2], buffers[3])); + bool alias = overlaps(buffers[2], buffers[0]) || overlaps(buffers[2], buffers[1]) || (n_buffers == 4 && overlaps(buffers[2], buffers[3])); const auto destination = bindings[2]; if (alias) { bindings[2] = {nullptr, execution->workspace, 0, ggml_nbytes(output)}; @@ -184,6 +229,18 @@ namespace sd_vulkan_rope { const uint32_t n_groups = uint32_t((uint64_t(pc.pairs) + 255) / 256); groups[0] = std::min(n_groups, info.max_group_count[0]); groups[1] = (n_groups + groups[0] - 1) / groups[0]; + } else if (head64) { + const bool cast = output->type == GGML_TYPE_F16; + pipeline.name = cast ? "sd.rms_rope_head64_cast.vulkan" : "sd.rms_rope_head64.vulkan"; + pipeline.spirv = cast ? sd_vulkan_shaders::rms_rope_head64_cast : sd_vulkan_shaders::rms_rope_head64; + pipeline.spirv_size = cast ? sizeof(sd_vulkan_shaders::rms_rope_head64_cast) : sizeof(sd_vulkan_shaders::rms_rope_head64); + pipeline.push_constant_size = sizeof(FusedParameters); + pipeline.full_subgroups = true; + pipeline.required_subgroup_size = info.subgroup_size_control ? info.subgroup_size : 0; + params.eps = param(nodes[0], 0); + groups[0] = (pc.heads + 1) / 2; + groups[1] = std::min(pc.tokens, info.max_group_count[1]); + groups[2] = std::min(uint32_t(x->ne[3]), info.max_group_count[2]); } else { pipeline.name = count > 3 ? "sd.rms_rope_cast.vulkan" : "sd.rms_rope_apply.vulkan"; pipeline.spirv = count > 3 ? sd_vulkan_shaders::rms_rope_cast : sd_vulkan_shaders::rms_rope_apply; diff --git a/src/core/vulkan/shaders/rms_rope_head64.comp b/src/core/vulkan/shaders/rms_rope_head64.comp new file mode 100644 index 0000000000..60025c144d --- /dev/null +++ b/src/core/vulkan/shaders/rms_rope_head64.comp @@ -0,0 +1,76 @@ +#version 450 + +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_EXT_control_flow_attributes : require +#ifdef CAST_F16 +#extension GL_EXT_shader_16bit_storage : require +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#define OUTPUT_TYPE float16_t +#else +#define OUTPUT_TYPE float +#endif + +layout(local_size_x = 128, local_size_y = 1, local_size_z = 1) in; +layout(binding = 0) readonly buffer X { + float data_x[]; +}; +layout(binding = 1) readonly buffer PE { + float data_pe[]; +}; +layout(binding = 2) writeonly buffer D { + OUTPUT_TYPE data_d[]; +}; + +layout(push_constant) uniform Parameters { + uint half_dim, rot_half, heads, tokens, pairs; + uint x_stride[4], pe_stride[4]; + uint x_offset, pe_offset, dst_offset, interleaved; + float eps; + uint w_offset; + float output_scale; +} +pc; + +shared float subgroup_sums[4]; + +void main() { + const uint lane = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID; + const uint head = gl_WorkGroupID.x * 2 + lane / 64; + const uint col = lane % 64; + const bool valid = head < pc.heads; + const uint batches = pc.pairs / (32 * pc.heads * pc.tokens); + for (uint batch = gl_WorkGroupID.z; batch < batches; batch += gl_NumWorkGroups.z) { + for (uint token = gl_WorkGroupID.y; token < pc.tokens; token += gl_NumWorkGroups.y) { + barrier(); + const uint row = pc.x_offset + head * pc.x_stride[1] + token * pc.x_stride[2] + batch * pc.x_stride[3]; + const float x = valid ? data_x[row + col] : 0.0; + // Use the native Vulkan RMSNorm reduction for a 64-channel row. + const float subtotal = subgroupAdd(x * x); + if (subgroupElect()) { + subgroup_sums[gl_SubgroupID] = subtotal; + } + barrier(); + const uint first = (lane / 64) * (64 / gl_SubgroupSize); + float sum = 0.0; + [[unroll]] for (uint i = 0; i < 64 / gl_SubgroupSize; ++i) { + sum += subgroup_sums[first + i]; + } + const float scale = inversesqrt(sum / 64.0 + pc.eps); + if (valid) { + precise float value = scale * x; + if (col < 2 * pc.rot_half) { + const uint pair = col % pc.rot_half; + const uint matrix = pc.pe_offset + pair * pc.pe_stride[2] + token * pc.pe_stride[3]; + const float c = data_pe[matrix]; + const float s = data_pe[matrix + pc.pe_stride[1]]; + const uint partner = col < pc.rot_half ? col + pc.rot_half : pair; + precise float other = scale * data_x[row + partner]; + value = col < pc.rot_half ? value * c - other * s : other * s + value * c; + } + const uint out_row = ((batch * pc.heads + head) * pc.tokens + token) * 64; + data_d[pc.dst_offset + out_row + col] = OUTPUT_TYPE(value); + } + } + } +} diff --git a/src/core/vulkan/shaders/swiglu_bias.comp b/src/core/vulkan/shaders/swiglu_bias.comp new file mode 100644 index 0000000000..30ab08731e --- /dev/null +++ b/src/core/vulkan/shaders/swiglu_bias.comp @@ -0,0 +1,31 @@ +#version 450 + +layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in; +layout(binding = 0) readonly buffer Projection { + float projection[]; +}; +layout(binding = 1) readonly buffer Bias { + float bias[]; +}; +layout(binding = 2) writeonly buffer Output { + float output_data[]; +}; + +layout(push_constant) uniform Parameters { + uint columns; + uint projection_offset, bias_offset, output_offset; +} +pc; + +void main() { + const uint col = gl_GlobalInvocationID.x; + if (col >= pc.columns) { + return; + } + const uint row = gl_WorkGroupID.y * pc.columns; + const uint i = pc.projection_offset + 2 * row + col; + const uint b = pc.bias_offset + col; + precise float gate = projection[i] + bias[b]; + precise float up = projection[i + pc.columns] + bias[b + pc.columns]; + output_data[pc.output_offset + row + col] = gate / (1.0 + exp(-gate)) * up; +} diff --git a/src/core/vulkan/shaders/vae_frame_norm.comp b/src/core/vulkan/shaders/vae_frame_norm.comp new file mode 100644 index 0000000000..1ebb0d5bbc --- /dev/null +++ b/src/core/vulkan/shaders/vae_frame_norm.comp @@ -0,0 +1,74 @@ +#version 450 +#extension GL_EXT_control_flow_attributes : enable + +#define BLOCK_SIZE 512 +layout(local_size_x = BLOCK_SIZE) in; +layout(binding = 0) readonly buffer Input { + float src[]; +}; +layout(binding = 1) readonly buffer Weight { + float weight[]; +}; +layout(binding = 2) readonly buffer Bias { + float bias[]; +}; +layout(binding = 3) writeonly buffer Output { + float dst[]; +}; +layout(push_constant) uniform Parameters { + uint spatial, frames, groups, group_channels; + float eps; + uint input_offset, weight_offset, bias_offset, output_offset; +} +p; + +shared float partials[BLOCK_SIZE]; + +float block_sum(float value) { + const uint tid = gl_LocalInvocationID.x; + partials[tid] = value; + barrier(); + [[unroll]] for (uint step = BLOCK_SIZE / 2; step > 0; step >>= 1) { + if (tid < step) + partials[tid] += partials[tid + step]; + barrier(); + } + const float total = partials[0]; + barrier(); + return total; +} + +void main() { + const uint tid = gl_LocalInvocationID.x; + const uint first_channel = (gl_WorkGroupID.x % p.groups) * p.group_channels; + const uint plane_stride = p.frames * p.spatial; + const uint base = ((gl_WorkGroupID.x / p.groups) * p.groups * p.group_channels + first_channel) * plane_stride + gl_WorkGroupID.y * p.spatial; + const uint group_size = p.spatial * p.group_channels; + + // Traverse each frame's group in the native GroupNorm reduction order. + float sum = 0.0; + for (uint channel = 0; channel < p.group_channels; ++channel) + for (uint pixel = tid; pixel < p.spatial; pixel += BLOCK_SIZE) + sum += src[p.input_offset + base + channel * plane_stride + pixel]; + const float mean = block_sum(sum) / group_size; + + float squares = 0.0; + for (uint channel = 0; channel < p.group_channels; ++channel) { + for (uint pixel = tid; pixel < p.spatial; pixel += BLOCK_SIZE) { + const float centered = src[p.input_offset + base + channel * plane_stride + pixel] - mean; + // Match the native GroupNorm's contracted variance accumulation. + squares = fma(centered, centered, squares); + } + } + const float scale = inversesqrt(block_sum(squares) / group_size + p.eps); + for (uint channel = 0; channel < p.group_channels; ++channel) { + const float gain = weight[p.weight_offset + first_channel + channel]; + const float offset = bias[p.bias_offset + first_channel + channel]; + for (uint pixel = tid; pixel < p.spatial; pixel += BLOCK_SIZE) { + const uint index = base + channel * plane_stride + pixel; + const float normalized = (src[p.input_offset + index] - mean) * scale; + precise float value = normalized * gain + offset; + dst[p.output_offset + index] = value / (1.0 + exp(-value)); + } + } +} diff --git a/src/core/vulkan/shaders/vae_pad_3d.comp b/src/core/vulkan/shaders/vae_pad_3d.comp new file mode 100644 index 0000000000..6ffee5b894 --- /dev/null +++ b/src/core/vulkan/shaders/vae_pad_3d.comp @@ -0,0 +1,39 @@ +#version 450 + +layout(local_size_x = 32, local_size_y = 8, local_size_z = 1) in; +layout(binding = 0) readonly buffer Input { + float input_data[]; +}; +layout(binding = 1) writeonly buffer Output { + float output_data[]; +}; + +layout(push_constant) uniform Parameters { + uint width, height, frames; + uint out_width, out_height, out_frames; + uint left, top, front; + uint input_offset, output_offset; +} +pc; + +void main() { + const uint x = gl_GlobalInvocationID.x; + const uint y = gl_GlobalInvocationID.y; + if (x >= pc.out_width || y >= pc.out_height) { + return; + } + const uint plane = gl_WorkGroupID.z; + const uint frame = plane % pc.out_frames; + const uint out_index = pc.output_offset + (plane * pc.out_height + y) * pc.out_width + x; + if (frame < pc.front) { + output_data[out_index] = 0.0; + return; + } + uint src_x = x < pc.left ? 1u : x - pc.left; + uint src_y = y < pc.top ? 1u : y - pc.top; + src_x = src_x == pc.width ? pc.width - 2 : src_x; + src_y = src_y == pc.height ? pc.height - 2 : src_y; + const uint channel = plane / pc.out_frames; + const uint in_index = pc.input_offset + ((channel * pc.frames + frame - pc.front) * pc.height + src_y) * pc.width + src_x; + output_data[out_index] = input_data[in_index]; +} diff --git a/src/core/vulkan/vae.cpp b/src/core/vulkan/vae.cpp new file mode 100644 index 0000000000..7ad777be16 --- /dev/null +++ b/src/core/vulkan/vae.cpp @@ -0,0 +1,166 @@ +#include "core/ggml_extensions.h" +#include "ggml-ext-vulkan.h" +#include "swiglu_bias.h" +#include "vae_frame_norm.h" +#include "vae_pad_3d.h" + +namespace sd_vulkan_vae { + + struct PadParameters { + uint32_t width, height, frames; + uint32_t out_width, out_height, out_frames; + uint32_t left, top, front; + uint32_t input_offset, output_offset; + }; + struct SwiGLUParameters { + uint32_t columns; + uint32_t projection_offset, bias_offset, output_offset; + }; + struct FrameNormParameters { + uint32_t spatial, frames, groups, group_channels; + float eps; + uint32_t input_offset, weight_offset, bias_offset, output_offset; + }; + static_assert(sizeof(PadParameters) == 44 && sizeof(SwiGLUParameters) == 16, "VAE push constant layouts"); + static_assert(sizeof(FrameNormParameters) == 36, "VAE frame norm push constant layout"); + + static const ggml_ext_vulkan_api* api(ggml_backend_dev_t device) { + const auto reg = ggml_backend_dev_backend_reg(device); + auto query = reinterpret_cast(ggml_backend_reg_get_proc_address(reg, "ggml_ext_vulkan_v1")); + return query ? query() : nullptr; + } + + static bool bounded(const ggml_tensor* node, const ggml_ext_vulkan_device_info& info) { + return node && node->type == GGML_TYPE_F32 && ggml_is_contiguous(node) && ggml_nelements(node) > 0 && + ggml_nbytes(node) <= UINT32_MAX && ggml_nbytes(node) <= info.max_buffer_range - (info.buffer_alignment - 1); + } + + static bool pad_supports(ggml_backend_dev_t device, const ggml_tensor* dst, void*) { + const auto* service = api(device); + ggml_ext_vulkan_device_info info; + SDVAEPad3DParams pad; + return service && service->device_info(device, &info) && sd_ggml_vae_pad_3d_describe(dst, &pad) && + bounded(dst, info) && bounded(dst->src[0], info) && info.max_group_size[0] >= 32 && info.max_group_size[1] >= 8 && + info.max_group_invocations >= 256 && info.max_push_constants >= sizeof(PadParameters) && + (dst->ne[0] + 31) / 32 <= info.max_group_count[0] && (dst->ne[1] + 7) / 8 <= info.max_group_count[1] && + dst->ne[2] * dst->ne[3] <= info.max_group_count[2]; + } + + static ggml_status pad_execute(const ggml_ext_execution_context* e, ggml_tensor* const* nodes, int, void*, void*) { + const auto* service = api(ggml_backend_get_device(e->backend)); + const auto* dst = nodes[0]; + const auto* src = dst->src[0]; + const ggml_ext_vulkan_binding bindings[] = {{src}, {dst}}; + ggml_ext_vulkan_buffer_info input, output; + SDVAEPad3DParams pad; + if (!service || !sd_ggml_vae_pad_3d_describe(dst, &pad) || + !service->buffer_info(e->backend, &bindings[0], &input) || !service->buffer_info(e->backend, &bindings[1], &output)) + return GGML_STATUS_FAILED; + const PadParameters p{uint32_t(src->ne[0]), uint32_t(src->ne[1]), uint32_t(src->ne[2]), + uint32_t(dst->ne[0]), uint32_t(dst->ne[1]), uint32_t(dst->ne[2]), + uint32_t(pad.left), uint32_t(pad.top), uint32_t(pad.front), + input.shader_offset / 4, output.shader_offset / 4}; + const uint32_t groups[] = {(p.out_width + 31) / 32, (p.out_height + 7) / 8, uint32_t(dst->ne[2] * dst->ne[3])}; + const ggml_ext_vulkan_pipeline pipeline{"sd.vae_pad_3d.vulkan", sd_vulkan_shaders::vae_pad_3d, + sizeof(sd_vulkan_shaders::vae_pad_3d), 2, sizeof(p)}; + return service->dispatch(e->backend, &pipeline, bindings, &p, groups); + } + + static bool has_workgroup_f16_coopmat(ggml_backend_dev_t device) { + const auto reg = ggml_backend_dev_backend_reg(device); + const auto query = reinterpret_cast(ggml_backend_reg_get_proc_address(reg, "ggml_ext_vulkan_compute_v1")); + const auto* service = query ? query() : nullptr; + ggml_ext_vulkan_matrix_properties prop; + for (uint32_t i = 0; service && service->matrix_properties(device, i, &prop); ++i) { + if (prop.flexible && prop.workgroup_scope && !prop.saturating && prop.a == GGML_TYPE_F16 && prop.b == GGML_TYPE_F16 && + prop.accumulator == GGML_TYPE_F32 && prop.result == GGML_TYPE_F32) + return true; + } + return false; + } + + static bool frame_norm_supports(ggml_backend_dev_t device, const ggml_tensor* dst, void*) { + const auto* service = api(device); + ggml_ext_vulkan_device_info info; + SDVAEFrameNormParams norm; + // Workgroup limits alone do not prevent device loss in full encoder graphs on older drivers. + return service && service->device_info(device, &info) && !info.fusion_disabled && sd_ggml_vae_frame_norm_describe(dst, &norm) && + bounded(dst, info) && bounded(dst->src[0], info) && bounded(dst->src[1], info) && bounded(dst->src[2], info) && + info.max_group_size[0] >= 512 && info.max_group_invocations >= 512 && info.max_push_constants >= sizeof(FrameNormParameters) && + dst->ne[0] * dst->ne[1] % 512 == 0 && dst->ne[3] / dst->src[1]->ne[0] * norm.groups <= info.max_group_count[0] && + dst->ne[2] <= info.max_group_count[1] && has_workgroup_f16_coopmat(device); + } + + static ggml_status frame_norm_execute(const ggml_ext_execution_context* e, ggml_tensor* const* nodes, int, void*, void*) { + const auto* service = api(ggml_backend_get_device(e->backend)); + const auto* dst = nodes[0]; + const ggml_ext_vulkan_binding bindings[] = {{dst->src[0]}, {dst->src[1]}, {dst->src[2]}, {dst}}; + ggml_ext_vulkan_buffer_info buffers[4]; + SDVAEFrameNormParams norm; + if (!service || !sd_ggml_vae_frame_norm_describe(dst, &norm)) + return GGML_STATUS_FAILED; + for (int i = 0; i < 4; ++i) + if (!service->buffer_info(e->backend, &bindings[i], &buffers[i])) + return GGML_STATUS_FAILED; + const auto channels = dst->src[1]->ne[0]; + const FrameNormParameters p{uint32_t(dst->ne[0] * dst->ne[1]), uint32_t(dst->ne[2]), uint32_t(norm.groups), + uint32_t(channels / norm.groups), norm.eps, buffers[0].shader_offset / 4, + buffers[1].shader_offset / 4, buffers[2].shader_offset / 4, buffers[3].shader_offset / 4}; + const uint32_t groups[] = {uint32_t(dst->ne[3] / channels * norm.groups), p.frames, 1}; + const ggml_ext_vulkan_pipeline pipeline{"sd.vae_frame_norm.vulkan", sd_vulkan_shaders::vae_frame_norm, + sizeof(sd_vulkan_shaders::vae_frame_norm), 4, sizeof(p)}; + return service->dispatch(e->backend, &pipeline, bindings, &p, groups); + } + + static bool swiglu_supports(ggml_backend_dev_t device, const ggml_tensor* dst, void*) { + const auto* service = api(device); + ggml_ext_vulkan_device_info info; + return service && service->device_info(device, &info) && !info.fusion_disabled && + info.max_group_size[0] >= 256 && info.max_group_invocations >= 256 && info.max_push_constants >= sizeof(SwiGLUParameters) && + sd_ggml_swiglu_bias_describe(dst) && bounded(dst, info) && bounded(dst->src[0], info) && bounded(dst->src[1], info) && + (dst->ne[0] + 255) / 256 <= info.max_group_count[0] && ggml_nrows(dst) <= info.max_group_count[1]; + } + + static ggml_status swiglu_execute(const ggml_ext_execution_context* e, ggml_tensor* const* nodes, int, void*, void*) { + const auto* service = api(ggml_backend_get_device(e->backend)); + const auto* dst = nodes[0]; + const ggml_ext_vulkan_binding bindings[] = {{dst->src[0]}, {dst->src[1]}, {dst}}; + ggml_ext_vulkan_buffer_info buffers[3]; + if (!service) + return GGML_STATUS_FAILED; + for (int i = 0; i < 3; ++i) + if (!service->buffer_info(e->backend, &bindings[i], &buffers[i])) + return GGML_STATUS_FAILED; + const SwiGLUParameters p{uint32_t(dst->ne[0]), buffers[0].shader_offset / 4, + buffers[1].shader_offset / 4, buffers[2].shader_offset / 4}; + const uint32_t groups[] = {(p.columns + 255) / 256, uint32_t(ggml_nrows(dst)), 1}; + const ggml_ext_vulkan_pipeline pipeline{"sd.swiglu_bias.vulkan", sd_vulkan_shaders::swiglu_bias, + sizeof(sd_vulkan_shaders::swiglu_bias), 3, sizeof(p)}; + return service->dispatch(e->backend, &pipeline, bindings, &p, groups); + } + +} + +void sd_ggml_register_vulkan_vae(ggml_backend_dev_t device) { + if (!sd_vulkan_vae::api(device)) + return; + ggml_ext_kernel_desc desc = {}; + desc.abi_version = GGML_EXT_ABI_VERSION; + desc.name = "sd.vae_pad_3d.vulkan.v1"; + desc.op = GGML_OP_CUSTOM; + desc.custom_op = sd_ggml_vae_pad_3d_op(); + desc.priority = 100; + desc.supports = sd_vulkan_vae::pad_supports; + desc.execute = sd_vulkan_vae::pad_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); + desc.name = "sd.swiglu_bias.vulkan.v1"; + desc.custom_op = sd_ggml_swiglu_bias_op(); + desc.supports = sd_vulkan_vae::swiglu_supports; + desc.execute = sd_vulkan_vae::swiglu_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); + desc.name = "sd.vae_frame_norm.vulkan.v1"; + desc.custom_op = sd_ggml_vae_frame_norm_op(); + desc.supports = sd_vulkan_vae::frame_norm_supports; + desc.execute = sd_vulkan_vae::frame_norm_execute; + GGML_ASSERT(ggml_ext_register_kernel(device, &desc)); +} diff --git a/src/model/vae/minimax_h3_vae.hpp b/src/model/vae/minimax_h3_vae.hpp index 25cd5e3f17..1d69e24368 100644 --- a/src/model/vae/minimax_h3_vae.hpp +++ b/src/model/vae/minimax_h3_vae.hpp @@ -12,6 +12,7 @@ #include #include +#include "core/image_geometry.h" #include "core/rng_mt19937.hpp" #include "model/common/rope.hpp" #include "model/diffusion/dit.hpp" @@ -71,20 +72,36 @@ namespace MiniMaxH3VAE { struct CausalConv3d : public Conv3d { std::tuple temporal_padding; + bool pad_spatial_end; CausalConv3d(int64_t in_channels, int64_t out_channels, std::tuple kernel_size, std::tuple stride = {1, 1, 1}, - std::tuple padding = {0, 0, 0}) + std::tuple padding = {0, 0, 0}, + bool pad_spatial_end = false) : Conv3d(in_channels, out_channels, kernel_size, stride, {0, 0, 0}), - temporal_padding(padding) {} + temporal_padding(padding), + pad_spatial_end(pad_spatial_end) {} ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) override { + const auto [padding_t, padding_h, padding_w] = temporal_padding; + const int temporal_pad = padding_t * 2; +#ifndef SD_USE_UPSTREAM_GGML + if (ctx->backend && (temporal_pad || padding_h || padding_w || pad_spatial_end)) { + const SDVAEPad3DParams pad{padding_w, padding_w + int(pad_spatial_end), + padding_h, padding_h + int(pad_spatial_end), temporal_pad}; + sd_ggml_register_extensions(ctx->backend); + ggml_tensor* inputs[] = {x}; + auto padded = ggml_ext_op_create(ctx->ggml_ctx, sd_ggml_vae_pad_3d_op(), inputs, 1, &pad); + if (padded && ggml_backend_supports_op(ctx->backend, padded)) + return Conv3d::forward(ctx, padded); + } +#endif auto reflect_pad = [&](ggml_tensor* value, int dim, int amount) { for (int i = 0; i < amount; ++i) { GGML_ASSERT(value->ne[dim] > 1); @@ -100,16 +117,22 @@ namespace MiniMaxH3VAE { return value; }; - if (std::get<1>(temporal_padding) != 0 || std::get<2>(temporal_padding) != 0) { + if (padding_h || padding_w || pad_spatial_end) { const int64_t frames = x->ne[2]; const int64_t channels = x->ne[3]; // Keep spatial padding in one outer slice to avoid per-channel CUDA launches. x = ggml_reshape_3d(ctx->ggml_ctx, ggml_ext_cont(ctx, x), x->ne[0], x->ne[1], frames * channels); - x = reflect_pad(x, 0, std::get<2>(temporal_padding)); - x = reflect_pad(x, 1, std::get<1>(temporal_padding)); + x = reflect_pad(x, 0, padding_w); + x = reflect_pad(x, 1, padding_h); + if (pad_spatial_end) { + GGML_ASSERT(x->ne[0] > 1 && x->ne[1] > 1); + auto right = ggml_ext_slice(ctx, x, 0, x->ne[0] - 2, x->ne[0] - 1); + x = ggml_concat(ctx->ggml_ctx, x, right, 0); + auto bottom = ggml_ext_slice(ctx, x, 1, x->ne[1] - 2, x->ne[1] - 1); + x = ggml_concat(ctx->ggml_ctx, x, bottom, 1); + } x = ggml_reshape_4d(ctx->ggml_ctx, x, x->ne[0], x->ne[1], frames, channels); } - int temporal_pad = std::get<0>(temporal_padding) * 2; if (temporal_pad > 0) { x = ggml_ext_pad_ext(ctx, x, @@ -130,59 +153,58 @@ namespace MiniMaxH3VAE { explicit TemporalGroupNorm(int64_t channels) : GroupNorm(32, channels, 1e-6f, true) {} + ggml_tensor* forward_silu(GGMLRunnerContext* ctx, ggml_tensor* x) { +#ifndef SD_USE_UPSTREAM_GGML + if (ctx->backend && !ctx->weight_adapter) { + const SDVAEFrameNormParams norm{num_groups, eps}; + ggml_tensor* inputs[] = {x, params.at("weight"), params.at("bias")}; + sd_ggml_register_extensions(ctx->backend); + auto fused = ggml_ext_op_create(ctx->ggml_ctx, sd_ggml_vae_frame_norm_op(), inputs, 3, &norm); + if (fused && ggml_backend_supports_op(ctx->backend, fused)) + return fused; + } +#endif + return ggml_silu(ctx->ggml_ctx, forward(ctx, x)); + } + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { - ggml_tensor* result = nullptr; - for (int64_t t = 0; t < x->ne[2]; ++t) { - auto frame = ggml_ext_slice(ctx, x, 2, t, t + 1); - GGML_ASSERT(frame->ne[3] % num_channels == 0); - int64_t batch_size = frame->ne[3] / num_channels; - frame = ggml_cont(ctx->ggml_ctx, frame); - frame = ggml_reshape_4d(ctx->ggml_ctx, - frame, - frame->ne[0], - frame->ne[1], - num_channels, - batch_size); - frame = GroupNorm::forward(ctx, frame); - frame = ggml_reshape_4d(ctx->ggml_ctx, - frame, - frame->ne[0], - frame->ne[1], - 1, - num_channels * batch_size); - result = result == nullptr ? frame : ggml_concat(ctx->ggml_ctx, result, frame, 2); + auto c = ctx->ggml_ctx; + const int64_t width = x->ne[0]; + const int64_t height = x->ne[1]; + const int64_t frames = x->ne[2]; + const int64_t planes = x->ne[3]; + GGML_ASSERT(planes % num_channels == 0); + const int64_t batch = planes / num_channels; + if (frames == 1) { + x = ggml_reshape_4d(c, ggml_ext_cont(ctx, x), width, height, num_channels, batch); + x = GroupNorm::forward(ctx, x); + return ggml_reshape_4d(c, x, width, height, frames, planes); } - return result; + // Treat each frame of each video as an independent GroupNorm batch item. + x = ggml_reshape_4d(c, ggml_ext_cont(ctx, x), width * height, frames, num_channels, batch); + x = ggml_cont(c, ggml_permute(c, x, 0, 2, 1, 3)); + x = ggml_reshape_4d(c, x, width, height, num_channels, frames * batch); + x = GroupNorm::forward(ctx, x); + x = ggml_reshape_4d(c, x, width * height, num_channels, frames, batch); + x = ggml_cont(c, ggml_permute(c, x, 0, 2, 1, 3)); + return ggml_reshape_4d(c, x, width, height, frames, planes); } }; struct Downsample3D : public GGMLBlock { - int spatial_stride; - Downsample3D(int64_t in_channels, int64_t out_channels, int temporal_stride, - int spatial_stride) - : spatial_stride(spatial_stride) { + int spatial_stride) { blocks["conv"] = std::make_shared(in_channels, out_channels, std::tuple{3, 3, 3}, std::tuple{temporal_stride, spatial_stride, spatial_stride}, - std::tuple{1, 0, 0}); + std::tuple{1, 0, 0}, + spatial_stride == 2); } ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { - if (spatial_stride == 2) { - GGML_ASSERT(x->ne[0] > 1 && x->ne[1] > 1); - const int64_t frames = x->ne[2]; - const int64_t channels = x->ne[3]; - x = ggml_reshape_3d(ctx->ggml_ctx, ggml_ext_cont(ctx, x), x->ne[0], x->ne[1], frames * channels); - auto right = ggml_ext_slice(ctx, x, 0, x->ne[0] - 2, x->ne[0] - 1); - x = ggml_concat(ctx->ggml_ctx, x, right, 0); - auto bottom = ggml_ext_slice(ctx, x, 1, x->ne[1] - 2, x->ne[1] - 1); - x = ggml_concat(ctx->ggml_ctx, x, bottom, 1); - x = ggml_reshape_4d(ctx->ggml_ctx, x, x->ne[0], x->ne[1], frames, channels); - } return std::dynamic_pointer_cast(blocks["conv"])->forward(ctx, x); } }; @@ -218,8 +240,8 @@ namespace MiniMaxH3VAE { auto norm2 = std::dynamic_pointer_cast(blocks["norm2"]); auto conv1 = std::dynamic_pointer_cast(blocks["conv1"]); auto conv2 = std::dynamic_pointer_cast(blocks["conv2"]); - auto h = conv1->forward(ctx, ggml_silu(ctx->ggml_ctx, norm1->forward(ctx, x))); - h = conv2->forward(ctx, ggml_silu(ctx->ggml_ctx, norm2->forward(ctx, h))); + auto h = conv1->forward(ctx, norm1->forward_silu(ctx, x)); + h = conv2->forward(ctx, norm2->forward_silu(ctx, h)); if (in_channels != out_channels) { x = std::dynamic_pointer_cast(blocks["nin_shortcut"])->forward(ctx, x); } @@ -280,32 +302,10 @@ namespace MiniMaxH3VAE { } auto norm = std::dynamic_pointer_cast(blocks["norm_out"]); auto conv = std::dynamic_pointer_cast(blocks["conv_out"]); - return conv->forward(ctx, ggml_silu(ctx->ggml_ctx, norm->forward(ctx, x))); + return conv->forward(ctx, norm->forward_silu(ctx, x)); } }; - static ggml_tensor* attention_layout(ggml_context* ctx, ggml_tensor* x) { - x = ggml_cont(ctx, ggml_permute(ctx, x, 0, 2, 1, 3)); - return ggml_reshape_3d(ctx, x, x->ne[0], x->ne[1], x->ne[2] * x->ne[3]); - } - - static ggml_tensor* apply_partial_rope(GGMLRunnerContext* runner_ctx, - ggml_tensor* x, - ggml_tensor* pe) { - auto ctx = runner_ctx->ggml_ctx; - int64_t rot_dim = pe->ne[2] * 2; - auto rotated = Rope::apply_rope(runner_ctx, - ggml_ext_slice(runner_ctx, x, 0, 0, rot_dim), - pe, - false); - if (rot_dim == x->ne[0]) { - return rotated; - } - auto tail = attention_layout(ctx, - ggml_ext_slice(runner_ctx, x, 0, rot_dim, x->ne[0])); - return ggml_concat(ctx, rotated, tail, 0); - } - struct DecoderAttention : public GGMLBlock { static constexpr int head_dim = 64; int dim; @@ -330,30 +330,12 @@ namespace MiniMaxH3VAE { num_head, sequence, batch_size); - auto qkv = ggml_ext_chunk(ctx, qkv_projection, 3, 0); - auto q = ggml_reshape_4d(ctx->ggml_ctx, - qkv[0], - head_dim, - num_head, - sequence, - batch_size); - auto k = ggml_reshape_4d(ctx->ggml_ctx, - qkv[1], - head_dim, - num_head, - sequence, - batch_size); - auto v = ggml_reshape_4d(ctx->ggml_ctx, - qkv[2], - head_dim, - num_head, - sequence, - batch_size); - q = ggml_rms_norm(ctx->ggml_ctx, q, 1e-5f); - k = ggml_rms_norm(ctx->ggml_ctx, k, 1e-5f); - q = apply_partial_rope(ctx, q, pe); - k = apply_partial_rope(ctx, k, pe); - return {q, k, v}; + auto qkv = ggml_ext_chunk(ctx, qkv_projection, 3, 0, false); + auto q = ggml_rms_norm(ctx->ggml_ctx, qkv[0], 1e-5f); + auto k = ggml_rms_norm(ctx->ggml_ctx, qkv[1], 1e-5f); + return {Rope::apply_rope(ctx, q, pe, false), + Rope::apply_rope(ctx, k, pe, false), + qkv[2]}; } std::array project_sol(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* pe) { @@ -409,8 +391,19 @@ namespace MiniMaxH3VAE { ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { auto w1 = std::dynamic_pointer_cast(blocks["w1"]); auto w2 = std::dynamic_pointer_cast(blocks["w2"]); - auto gate = ggml_swiglu(ctx->ggml_ctx, w1->forward(ctx, x)); - return w2->forward(ctx, gate); + auto proj = w1->forward(ctx, x); +#ifndef SD_USE_UPSTREAM_GGML + if (sd_backend_is(ctx->backend, "Vulkan") && proj->op == GGML_OP_ADD && proj->view_src == proj->src[0] && + proj->src[0]->op == GGML_OP_MUL_MAT && proj->src[0]->src[0]->type == GGML_TYPE_F16) { + // Keep the projection and bias separate so the backend can write the compact gate directly. + sd_ggml_register_extensions(ctx->backend); + ggml_tensor* inputs[] = {proj->src[0], proj->src[1]}; + auto* gate = ggml_ext_op_create(ctx->ggml_ctx, sd_ggml_swiglu_bias_op(), inputs, 2, nullptr); + if (gate && ggml_backend_supports_op(ctx->backend, gate)) + return w2->forward(ctx, gate); + } +#endif + return w2->forward(ctx, ggml_swiglu(ctx->ggml_ctx, proj)); } }; @@ -650,6 +643,7 @@ namespace MiniMaxH3VAE { sd::Tensor latents_mean; sd::Tensor latents_std; sd::Tensor rope_cache; + std::array rope_shape{}; MiniMaxH3VideoVAERunner(ggml_backend_t backend, const String2TensorStorage& tensor_storage_map, @@ -755,38 +749,27 @@ namespace MiniMaxH3VAE { return params; } - static sd::Tensor repeat_last_frame(const sd::Tensor& input, - int64_t count) { - auto result = input; - auto last = sd::ops::slice(input, 2, input.shape()[2] - 1, input.shape()[2]); - for (int64_t i = 0; i < count; ++i) { - result = sd::ops::concat(result, last, 2); - } - return result; - } - - static sd::Tensor blend_temporal(const sd::Tensor& previous, - const sd::Tensor& current, - int64_t extent) { - auto output = current; - extent = std::min({extent, previous.shape()[2], current.shape()[2]}); - int64_t previous_start = previous.shape()[2] - extent; - for (int64_t b = 0; b < current.shape()[4]; ++b) { - for (int64_t c = 0; c < current.shape()[3]; ++c) { - for (int64_t t = 0; t < extent; ++t) { - float wb = static_cast(t) / extent; - float wa = 1.f - wb; - for (int64_t h = 0; h < current.shape()[1]; ++h) { - for (int64_t w = 0; w < current.shape()[0]; ++w) { - output.index(w, h, t, c, b) = - previous.index(w, h, previous_start + t, c, b) * wa + - current.index(w, h, t, c, b) * wb; - } - } + static void blend_temporal(const sd::Tensor& previous, + sd::Tensor& current, + int64_t extent) { + const int64_t current_frames = current.shape()[2]; + const int64_t previous_frames = previous.shape()[2]; + extent = std::min({extent, previous_frames, current_frames}); + const int64_t frame_size = current.shape()[0] * current.shape()[1]; + const int64_t planes = current.shape()[3] * current.shape()[4]; + for (int64_t plane = 0; plane < planes; ++plane) { + const auto* src = previous.data() + ((plane + 1) * previous_frames - extent) * frame_size; + auto* dst = current.data() + plane * current_frames * frame_size; + for (int64_t t = 0; t < extent; ++t) { + const float wb = static_cast(t) / extent; + const float wa = 1.f - wb; + for (int64_t i = 0; i < frame_size; ++i) { + dst[i] = src[i] * wa + dst[i] * wb; } + src += frame_size; + dst += frame_size; } } - return output; } sd::Tensor encode(int n_threads, @@ -816,7 +799,7 @@ namespace MiniMaxH3VAE { pad += 17; } if (pad > 0) { - input = repeat_last_frame(input, pad); + input = sd::pad_video_tensor(input, input.shape()[2] + pad); } auto plan = make_vae_temporal_tile_plan(input.shape()[2], {17, 0}); auto result = process_vae_temporal_tiles(input, plan, [&](const sd::Tensor& chunk, const VAETemporalTile& tile) { @@ -939,7 +922,7 @@ namespace MiniMaxH3VAE { num_chunks += 1; } if (pad_tokens > 0) { - input = repeat_last_frame(input, pad_tokens); + input = sd::pad_video_tensor(input, input.shape()[2] + pad_tokens); } sd::Tensor overlap; @@ -968,7 +951,7 @@ namespace MiniMaxH3VAE { std::min(frame_pre_padding, first_end), first_end); if (!overlap.empty()) { - first = blend_temporal(overlap, first, frame_overlap); + blend_temporal(overlap, first, frame_overlap); overlap = {}; } @@ -1044,9 +1027,11 @@ namespace MiniMaxH3VAE { sd::Tensor shifted_rope; sd::Tensor sol_row_ids; if (decode_graph) { - rope_cache = build_rope(input.shape()[0], - input.shape()[1], - input.shape()[2]); + const std::array shape{input.shape()[0], input.shape()[1], input.shape()[2]}; + if (rope_shape != shape) { + rope_cache = build_rope(shape[0], shape[1], shape[2]); + rope_shape = shape; + } if (config.sol) { const auto& shape = input.shape(); sol_plan = std::make_unique(shape[0], shape[1], shape[2], false); diff --git a/src/runtime/tiling.cpp b/src/runtime/tiling.cpp index 95bcc228b6..efdacdd87f 100644 --- a/src/runtime/tiling.cpp +++ b/src/runtime/tiling.cpp @@ -66,17 +66,22 @@ static sd::Tensor sd_tensor_split_2d(const sd::Tensor& input, int output_shape[0] = width; output_shape[1] = height; sd::Tensor output(std::move(output_shape)); - int64_t input_width = input.shape()[0]; - int64_t input_height = input.shape()[1]; - int64_t input_plane = sd_tensor_plane_size(input); - int64_t output_plane = sd_tensor_plane_size(output); - int64_t plane_count = input.numel() / input_plane; - for (int iy = 0; iy < height; iy++) { - for (int ix = 0; ix < width; ix++) { - int64_t src_xy = (ix + x) % input_width + input_width * ((iy + y) % input_height); - int64_t dst_xy = ix + width * iy; - for (int64_t plane = 0; plane < plane_count; ++plane) { - output[plane * output_plane + dst_xy] = input[plane * input_plane + src_xy]; + int64_t input_width = input.shape()[0]; + int64_t input_height = input.shape()[1]; + int64_t input_plane = sd_tensor_plane_size(input); + int64_t output_plane = sd_tensor_plane_size(output); + int64_t plane_count = input.numel() / input_plane; + const int64_t first_width = std::min(width, input_width - x); + const int64_t wrap_width = width - first_width; + for (int64_t plane = 0; plane < plane_count; ++plane) { + const auto* src_plane = input.data() + plane * input_plane; + auto* dst_plane = output.data() + plane * output_plane; + for (int iy = 0; iy < height; ++iy) { + const auto* src_row = src_plane + ((iy + y) % input_height) * input_width; + auto* dst_row = dst_plane + static_cast(iy) * width; + std::copy_n(src_row + x, first_width, dst_row); + if (wrap_width > 0) { + std::copy_n(src_row, wrap_width, dst_row + first_width); } } } @@ -108,29 +113,37 @@ static void sd_tensor_merge_2d(const sd::Tensor& input, GGML_ASSERT(overlap_left >= 0 && overlap_right >= 0); GGML_ASSERT(overlap_top >= 0 && overlap_bottom >= 0); - auto smootherstep_f32 = [](const float x) -> float { - return x * x * x * (x * (6.0f * x - 15.0f) + 10.0f); + auto axis_weights = [](int64_t size, int before, int after) { + std::vector weights(size, 1.0f); + for (int64_t i = 0; i < size; ++i) { + float t = 1.0f; + if (i < before) { + t = static_cast(i) / before; + } + if (i >= size - after) { + t = static_cast(size - i) / after; + } + t = std::clamp(t, 0.0f, 1.0f); + weights[i] = t * t * t * (t * (6.0f * t - 15.0f) + 10.0f); + } + return weights; }; + const auto x_weights = axis_weights(in_width, overlap_left, overlap_right); + const auto y_weights = axis_weights(in_height, overlap_top, overlap_bottom); + const int64_t first_width = std::min(in_width, out_width - x); + const int64_t wrap_width = in_width - first_width; for (int64_t plane = 0; plane < plane_count; ++plane) { - for (int iy = 0; iy < in_height; ++iy) { - float y_f = 1.0f; - if (iy < overlap_top) { - y_f = static_cast(iy) / overlap_top; - } - if (iy >= in_height - overlap_bottom) { - y_f = static_cast(in_height - iy) / overlap_bottom; + const auto* src_plane = input.data() + plane * in_size; + auto* dst_plane = output->data() + plane * out_size; + for (int64_t iy = 0; iy < in_height; ++iy) { + const auto* src_row = src_plane + iy * in_width; + auto* dst_row = dst_plane + (y + iy) % out_height * out_width; + const float yw = y_weights[iy]; + for (int64_t ix = 0; ix < first_width; ++ix) { + dst_row[x + ix] += x_weights[ix] * yw * src_row[ix]; } - const float y_weight = smootherstep_f32(std::clamp(y_f, 0.0f, 1.0f)); - for (int ix = 0; ix < in_width; ++ix) { - float x_f = 1.0f; - if (ix < overlap_left) { - x_f = static_cast(ix) / overlap_left; - } - if (ix >= in_width - overlap_right) { - x_f = static_cast(in_width - ix) / overlap_right; - } - float x_weight = smootherstep_f32(std::clamp(x_f, 0.0f, 1.0f)); - (*output)[plane * out_size + out_width * ((y + iy) % out_height) + ((x + ix) % out_width)] += x_weight * y_weight * input[plane * in_size + in_width * iy + ix]; + for (int64_t ix = 0; ix < wrap_width; ++ix) { + dst_row[ix] += x_weights[first_width + ix] * yw * src_row[first_width + ix]; } } } From 2758c8fab5fe4265088ef6248b7e5191fafae860 Mon Sep 17 00:00:00 2001 From: leejet Date: Tue, 1 Dec 2026 22:26:53 +0800 Subject: [PATCH 2/2] fix --- src/core/cuda/rope.cu | 5 ++--- src/core/vulkan/rope.cpp | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/core/cuda/rope.cu b/src/core/cuda/rope.cu index dd51ebc3ae..c7a3ecb7e8 100644 --- a/src/core/cuda/rope.cu +++ b/src/core/cuda/rope.cu @@ -491,9 +491,8 @@ namespace SD_CUDA_NAMESPACE { static ggml_status rope_prepare(ggml_backend_t, ggml_tensor* const* nodes, int count, void**, size_t* workspace, void*) { const auto* dst = nodes[count - 1]; - // Owning casts are fresh outputs; copies into existing storage retain view_src. - const bool fresh_output = !dst->data && !dst->buffer && !dst->view_src; - *workspace = fresh_output ? 0 : ggml_nbytes(dst); + // The allocator can reuse input storage for a terminal copy, including an owning cast. + *workspace = dst->op == GGML_OP_CPY || dst->data || dst->buffer || dst->view_src ? ggml_nbytes(dst) : 0; return GGML_STATUS_SUCCESS; } diff --git a/src/core/vulkan/rope.cpp b/src/core/vulkan/rope.cpp index fb88114c8b..df0d9091db 100644 --- a/src/core/vulkan/rope.cpp +++ b/src/core/vulkan/rope.cpp @@ -169,8 +169,8 @@ namespace sd_vulkan_rope { } static ggml_status prepare(ggml_backend_t, ggml_tensor* const* nodes, int count, void**, size_t* bytes, void*) { const auto* output = nodes[count - 1]; - // RoPE outputs and owning casts cannot reuse allocator input storage. - *bytes = output->data || output->view_src ? ggml_nbytes(output) : 0; + // The allocator can reuse input storage for a terminal copy, including an owning cast. + *bytes = output->op == GGML_OP_CPY || output->data || output->view_src ? ggml_nbytes(output) : 0; return GGML_STATUS_SUCCESS; } static void destroy(void*, void*) {}