Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/core/cuda/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cmake_policy(SET CMP0079 NEW)

function(sd_cuda_sources VENDOR LANGUAGE)
set(SOURCES)
foreach(OP rope int8 w4 convrot affine modulate bf16 rms_affine registration)
foreach(OP rope int8 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")
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions src/core/cuda/registration.cu
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand Down
94 changes: 94 additions & 0 deletions src/core/cuda/vae_frame_norm.cu
Original file line number Diff line number Diff line change
@@ -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, &params) && 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, &params))
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<<<grid, norm_threads, 0, static_cast<CUDAStream>(context.stream)>>>(
static_cast<const float*>(dst->src[0]->data), static_cast<const float*>(dst->src[1]->data),
static_cast<const float*>(dst->src[2]->data), static_cast<float*>(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));
}
}
62 changes: 62 additions & 0 deletions src/core/cuda/vae_pad.cu
Original file line number Diff line number Diff line change
@@ -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<<<grid, block, 0, static_cast<CUDAStream>(context.stream)>>>(
static_cast<const float*>(src->data), static_cast<float*>(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));
}
}
78 changes: 78 additions & 0 deletions src/core/ggml_extensions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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(&params, 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;
}
Expand Down
19 changes: 19 additions & 0 deletions src/core/ggml_extensions.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading