From dc3fd3302e926c05062bdf84f5f6143989e10f2c Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 1 Dec 2026 16:28:03 -0800 Subject: [PATCH 1/3] MiniMax-H3 VAE: pad the last video frame into one allocation instead of one full-clip concat per padded frame (from upstream #2476) --- src/model/vae/minimax_h3_vae.hpp | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/src/model/vae/minimax_h3_vae.hpp b/src/model/vae/minimax_h3_vae.hpp index e8dc0fa593..983b25c94c 100644 --- a/src/model/vae/minimax_h3_vae.hpp +++ b/src/model/vae/minimax_h3_vae.hpp @@ -991,12 +991,29 @@ namespace MiniMaxH3VAE { return params; } + // Appends `count` copies of the last frame. The output is allocated once and each plane is copied + // directly, instead of one full-clip concat per padded frame. 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); + GGML_ASSERT(input.dim() == 5 && input.shape()[2] > 0 && count >= 0); + if (count == 0) { + return input; + } + auto shape = input.shape(); + const int64_t frames = shape[2]; + const int64_t padded_frames = frames + count; + shape[2] = padded_frames; + sd::Tensor result(std::move(shape)); + const int64_t frame_size = input.shape()[0] * input.shape()[1]; + const int64_t planes = input.shape()[3] * input.shape()[4]; + for (int64_t p = 0; p < planes; ++p) { + const float* src = input.data() + p * frames * frame_size; + float* dst = result.data() + p * padded_frames * frame_size; + memcpy(dst, src, sizeof(float) * frames * frame_size); + const float* last = src + (frames - 1) * frame_size; + for (int64_t i = 0; i < count; ++i) { + memcpy(dst + (frames + i) * frame_size, last, sizeof(float) * frame_size); + } } return result; } From cff16da3669c96f72a2365341f36836dac5a1626 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Tue, 1 Dec 2026 16:33:45 -0800 Subject: [PATCH 2/3] MiniMax-H3 VAE encoder: one padding kernel and fused frame GroupNorm + affine + SiLU on CUDA / HIP, one batched GroupNorm elsewhere (from upstream #2476) --- src/core/cuda/CMakeLists.txt | 4 +- src/core/cuda/registration.cu | 4 ++ src/core/cuda/vae_frame_norm.cu | 94 +++++++++++++++++++++++++ src/core/cuda/vae_pad.cu | 62 ++++++++++++++++ src/core/ggml_extensions.cpp | 78 +++++++++++++++++++++ src/core/ggml_extensions.h | 19 +++++ src/model/vae/minimax_h3_vae.hpp | 117 ++++++++++++++++++++----------- 7 files changed, 335 insertions(+), 43 deletions(-) create mode 100644 src/core/cuda/vae_frame_norm.cu create mode 100644 src/core/cuda/vae_pad.cu diff --git a/src/core/cuda/CMakeLists.txt b/src/core/cuda/CMakeLists.txt index e2dd3f92c3..21402cca22 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 w4 convrot affine modulate bf16 rms_affine vae_pad vae_frame_norm 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") @@ -55,6 +55,8 @@ if(SD_HIPBLAS) set_target_properties(${SD_CUDA_TARGET} PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON) endif() 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") # 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) diff --git a/src/core/cuda/registration.cu b/src/core/cuda/registration.cu index d92be448ce..4b81833014 100644 --- a/src/core/cuda/registration.cu +++ b/src/core/cuda/registration.cu @@ -16,6 +16,8 @@ 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_HIP) && !defined(SD_CUDA_VENDOR_MUSA) void register_sage_attention(ggml_backend_dev_t device); void register_sol_attention(ggml_backend_dev_t device); @@ -32,6 +34,8 @@ 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_HIP) && !defined(SD_CUDA_VENDOR_MUSA) register_sage_attention(device); register_sol_attention(device); 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 1e20250634..5958ba17aa 100644 --- a/src/core/ggml_extensions.cpp +++ b/src/core/ggml_extensions.cpp @@ -131,6 +131,84 @@ 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; +} + 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 3145c6fbb4..acbe8cdd08 100644 --- a/src/core/ggml_extensions.h +++ b/src/core/ggml_extensions.h @@ -18,6 +18,25 @@ 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); + struct SDI8Attributes { int64_t shape[3]; int32_t group_size; diff --git a/src/model/vae/minimax_h3_vae.hpp b/src/model/vae/minimax_h3_vae.hpp index 983b25c94c..a89eff8ce4 100644 --- a/src/model/vae/minimax_h3_vae.hpp +++ b/src/model/vae/minimax_h3_vae.hpp @@ -77,20 +77,40 @@ namespace MiniMaxH3VAE { struct CausalConv3d : public Conv3d { std::tuple temporal_padding; + // Downsampling convolutions repeat the second-to-last column and row once at the right / bottom edge. + 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 + // One kernel for the spatial reflection, the end padding and the causal zero frames, where the backend + // has it (a pure copy, so the convolution input is unchanged). + 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); @@ -106,9 +126,15 @@ namespace MiniMaxH3VAE { return value; }; - x = reflect_pad(x, 0, std::get<2>(temporal_padding)); - x = reflect_pad(x, 1, std::get<1>(temporal_padding)); - int temporal_pad = std::get<0>(temporal_padding) * 2; + 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); + } if (temporal_pad > 0) { x = ggml_ext_pad_ext(ctx, x, @@ -129,55 +155,62 @@ namespace MiniMaxH3VAE { explicit TemporalGroupNorm(int64_t channels) : GroupNorm(32, channels, 1e-6f, true) {} - 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); + // GroupNorm per frame, affine and SiLU in one kernel on the encoder's [W, H, T, C * B] layout where the + // backend has it; otherwise the separate ops. + 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; + } } - return result; +#endif + return ggml_silu(ctx->ggml_ctx, forward(ctx, x)); + } + + ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) { + 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); + } + // Each frame of each video is an independent GroupNorm batch item: one normalisation over all + // frames instead of a slice, norm and concat per frame. + 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); - 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); - } return std::dynamic_pointer_cast(blocks["conv"])->forward(ctx, x); } }; @@ -213,8 +246,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); } @@ -275,7 +308,7 @@ 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)); } }; From 239d1425c32a549b286d6cdd90326354ec02bce9 Mon Sep 17 00:00:00 2001 From: Daniel Han <23090290+danielhanchen@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:11:03 -0800 Subject: [PATCH 3/3] MiniMax-H3 VAE: shorten the padding and frame norm comments --- src/model/vae/minimax_h3_vae.hpp | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/model/vae/minimax_h3_vae.hpp b/src/model/vae/minimax_h3_vae.hpp index a89eff8ce4..1adefbfad3 100644 --- a/src/model/vae/minimax_h3_vae.hpp +++ b/src/model/vae/minimax_h3_vae.hpp @@ -98,8 +98,7 @@ namespace MiniMaxH3VAE { const auto [padding_t, padding_h, padding_w] = temporal_padding; const int temporal_pad = padding_t * 2; #ifndef SD_USE_UPSTREAM_GGML - // One kernel for the spatial reflection, the end padding and the causal zero frames, where the backend - // has it (a pure copy, so the convolution input is unchanged). + // Reflection, end padding and causal zero frames as one copy kernel where the backend has it. 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}; @@ -155,8 +154,7 @@ namespace MiniMaxH3VAE { explicit TemporalGroupNorm(int64_t channels) : GroupNorm(32, channels, 1e-6f, true) {} - // GroupNorm per frame, affine and SiLU in one kernel on the encoder's [W, H, T, C * B] layout where the - // backend has it; otherwise the separate ops. + // Per-frame GroupNorm + affine + SiLU as one kernel where the backend has it. ggml_tensor* forward_silu(GGMLRunnerContext* ctx, ggml_tensor* x) { #ifndef SD_USE_UPSTREAM_GGML if (ctx->backend && !ctx->weight_adapter) { @@ -185,8 +183,7 @@ namespace MiniMaxH3VAE { x = GroupNorm::forward(ctx, x); return ggml_reshape_4d(c, x, width, height, frames, planes); } - // Each frame of each video is an independent GroupNorm batch item: one normalisation over all - // frames instead of a slice, norm and concat per frame. + // Every frame is its own 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); @@ -1024,8 +1021,7 @@ namespace MiniMaxH3VAE { return params; } - // Appends `count` copies of the last frame. The output is allocated once and each plane is copied - // directly, instead of one full-clip concat per padded frame. + // Appends `count` copies of the last frame in one allocation. static sd::Tensor repeat_last_frame(const sd::Tensor& input, int64_t count) { GGML_ASSERT(input.dim() == 5 && input.shape()[2] > 0 && count >= 0);