Commit 3d0df00 for stable-diffusion.cpp
commit 3d0df004429e5fe2f3bd0005873721ece7c0a3ea
Author: leejet <leejet714@gmail.com>
Date: Sun Nov 29 01:34:50 2026 +0800
perf: extend CUDA fusions for Wan (#2458)
diff --git a/docs/guides/performance.md b/docs/guides/performance.md
index fade7a0..243b5f9 100644
--- a/docs/guides/performance.md
+++ b/docs/guides/performance.md
@@ -152,11 +152,11 @@ On Vulkan, CPU-offloaded weights use pageable system RAM, leaving the driver's h
When a graph has cut markers and its missing weights plus incremental compute workspace exceed the available device headroom, it runs its fixed segment list in order. An existing monolithic workspace can be reused without a new allocation. An explicit `--max-vram` budget includes resident managed weights, compute and cache buffers registered by runners sharing the device, and ggml's idle buffer pool. The current segment's weights are pinned during compute, and the next parameter-bearing segment is prefetched when the device supports asynchronous transfer. No opt-in streaming flag is required.
-When choosing between monolithic and segmented execution, the runner requires
-an additional 128 MiB of headroom in both available device memory and any explicit
-managed budget. This planning headroom absorbs small allocation estimate changes;
-subsequent capacity checks can consume it while still preserving the 512 MiB device
-scratch reserve and respecting the managed budget.
+When planning a new monolithic workspace allocation, the runner requires an
+additional 128 MiB in both available device memory and any explicit managed
+budget. New device allocations also reserve 512 MiB for backend scratch
+buffers, or 1 GiB on Windows CUDA. A graph that reuses its resident weights and
+workspace still checks the managed budget.
- `--max-vram <GiB>` optionally lowers the live-memory limit. A positive value is a managed per-device budget, `0` uses the device's current free memory without an explicit budget, and a negative value snapshots free memory at startup while reserving that many GiB (`--max-vram -1` reserves about 1 GiB). Driver contexts and unrelated external allocations remain outside the managed budget.
- `--disable-prefetch` disables asynchronous next-segment prefetch while retaining synchronous loading, eviction, and segmented execution.
diff --git a/src/core/cuda/convrot.cu b/src/core/cuda/convrot.cu
index e3a1724..d77ab3b 100644
--- a/src/core/cuda/convrot.cu
+++ b/src/core/cuda/convrot.cu
@@ -27,6 +27,7 @@ namespace SD_CUDA_NAMESPACE {
}
enum Kind { SCALE,
NORM,
+ NORM_MOD,
MOD,
RMS_MOD,
RMS_MOD_VEC,
@@ -85,6 +86,14 @@ namespace SD_CUDA_NAMESPACE {
op.eps = param_f32(first, 0);
if (op.k < 1024 || !vector(op.modulation, op.k))
return false;
+ } else if (count == 3 && first->op == GGML_OP_NORM && value == nodes[1] &&
+ sd_ggml_modulate_describe(value) && value->src[0] == first) {
+ op.kind = NORM_MOD;
+ op.modulation = value->src[1];
+ op.shift = value->src[2];
+ op.eps = param_f32(first, 0);
+ if (op.k < 1024 || !vector(op.modulation, op.k) || (op.shift && !vector(op.shift, op.k)))
+ return false;
} else if (count == 2 && sd_ggml_modulate_describe(first) && value == first) {
op.kind = MOD;
op.modulation = first->src[1];
@@ -134,7 +143,7 @@ namespace SD_CUDA_NAMESPACE {
return false;
} else
return false;
- if (op.group == 1 && (op.kind == SCALE || op.kind == NORM))
+ if (op.group == 1 && (op.kind == SCALE || op.kind == NORM || op.kind == NORM_MOD))
return false;
for (int i = 0; i < count - 1; ++i) {
if (!f32(nodes[i]) || !ggml_are_same_shape(nodes[i], value))
@@ -146,8 +155,8 @@ namespace SD_CUDA_NAMESPACE {
return true;
}
static bool supported(const Operation& op, const ggml_ext_gpu_device_info& device) {
- const size_t extra = op.kind == NORM ? 384 : op.kind == RMS_MOD || op.kind == RMS_MOD_VEC ? 256
- : 128;
+ const size_t extra = op.kind == NORM || op.kind == NORM_MOD ? 384 : op.kind == RMS_MOD || op.kind == RMS_MOD_VEC ? 256
+ : 128;
return device.device >= 0 && size_t(op.k) * sizeof(float) + extra <= device.shared_memory;
}
static int match(ggml_backend_dev_t device, const ggml_cgraph* graph, int first, void*) {
@@ -188,7 +197,8 @@ namespace SD_CUDA_NAMESPACE {
chain[2] = value;
chain[3] = quant;
count = 4;
- } else if (weight->op == GGML_OP_RMS_NORM && vector_rms_input(weight->src[0], value->ne[0])) {
+ } else if (weight->op == GGML_OP_NORM ||
+ (weight->op == GGML_OP_RMS_NORM && vector_rms_input(weight->src[0], value->ne[0]))) {
chain[0] = weight;
chain[1] = value;
chain[2] = quant;
@@ -259,7 +269,7 @@ namespace SD_CUDA_NAMESPACE {
}
template <bool Rotate, bool Swiglu, bool Normalize, bool Scaled, bool Sigmoid, bool RMS, bool Modulate, bool Situ, bool Gelu, bool RMSVec>
static CUDAError launch_quantize(Plan& p, const Operation& op, int8_t* output, CUDAStream stream) {
- constexpr bool warp = Scaled || RMS || Modulate || Gelu;
+ constexpr bool warp = Scaled || RMS || (Modulate && !Normalize) || Gelu;
constexpr int extra = Normalize ? 384 : RMS ? 256
: 128;
if (!p.configured) {
@@ -283,7 +293,7 @@ namespace SD_CUDA_NAMESPACE {
}
template <bool Swiglu = false, bool Normalize = false, bool Scaled = false, bool Sigmoid = false, bool RMS = false, bool Modulate = false, bool Situ = false, bool Gelu = false, bool RMSVec = false>
static CUDAError launch(Plan& p, const Operation& op, int8_t* output, CUDAStream stream) {
- if constexpr (Swiglu || RMS || Modulate || Gelu) {
+ if constexpr (Swiglu || RMS || (Modulate && !Normalize) || Gelu) {
if (op.group == 1)
return launch_quantize<false, Swiglu, Normalize, Scaled, Sigmoid, RMS, Modulate, Situ, Gelu, RMSVec>(p, op, output, stream);
}
@@ -312,6 +322,9 @@ namespace SD_CUDA_NAMESPACE {
case NORM:
error = launch<false, true>(plan, op, output, stream);
break;
+ case NORM_MOD:
+ error = launch<false, true, false, false, false, true>(plan, op, output, stream);
+ break;
case RMS_MOD:
error = launch<false, false, false, false, true>(plan, op, output, stream);
break;
diff --git a/src/core/cuda/convrot_kernel.h b/src/core/cuda/convrot_kernel.h
index c34330b..a14e5f1 100644
--- a/src/core/cuda/convrot_kernel.h
+++ b/src/core/cuda/convrot_kernel.h
@@ -218,7 +218,13 @@ namespace SD_CUDA_NAMESPACE {
const float inv_std = rsqrtf(variance + eps);
for (int64_t i = tid; i < k; i += 1024) {
const float normalized = __fmul_rn(__fsub_rn(src_row[i], mean), inv_std);
- values[i] = __fmul_rn(__fmul_rn(normalized, modulation[i]), 1.0f / 16.0f);
+ float value = __fmul_rn(normalized, modulation[i]);
+ if constexpr (modulate) {
+ value = __fadd_rn(normalized, value);
+ if (rms_shift)
+ value = __fadd_rn(value, rms_shift[i]);
+ }
+ values[i] = __fmul_rn(value, rotation_scale);
}
} else {
for (int64_t i = tid; i < k; i += blockDim.x) {
diff --git a/src/core/cuda/requantize.cu b/src/core/cuda/requantize.cu
index 82a0d40..0899956 100644
--- a/src/core/cuda/requantize.cu
+++ b/src/core/cuda/requantize.cu
@@ -168,7 +168,7 @@ namespace SD_CUDA_NAMESPACE {
values[j] = h256_signed(blocks[0].decode(source) * (1.0f / 16.0f), i);
} else {
const int i = j * lanes + lane;
- values[j] = blocks[i / block_size].decode(i % block_size) * (1.0f / 16.0f);
+ values[j] = blocks[i / block_size].decode(i % block_size) * (1.0f / 16.0f);
}
}
if constexpr (cuda_kind == GGML_EXT_GPU_CUDA && block_size == group_size) {
diff --git a/src/core/cuda/rope.cu b/src/core/cuda/rope.cu
index 5ae7c0d..981b52d 100644
--- a/src/core/cuda/rope.cu
+++ b/src/core/cuda/rope.cu
@@ -14,35 +14,47 @@ namespace SD_CUDA_NAMESPACE {
}
template <int D, bool interleaved, typename T, bool affine = true, int HiddenDim = 0>
- static __global__ __launch_bounds__(HiddenDim ? HiddenDim / 4 : 128) void rms_norm_mul_rope_apply_fused(
- const float* x,
- const float* weight,
- const float* pe,
- T* dst,
- int64_t heads,
- int64_t tokens,
- int64_t rows,
- int64_t nb1,
- int64_t nb2,
- int64_t nb3,
- int rot_half,
- float eps,
- float output_scale) {
- const int lane = threadIdx.x;
- const int64_t head_count = HiddenDim > 0 ? HiddenDim / D : heads;
- int64_t first = int64_t(blockIdx.x) * blockDim.y + threadIdx.y;
- int64_t end = first + 1;
- float scale = 1.0f;
+ static __global__ __launch_bounds__(HiddenDim > 4096 ? 256 : HiddenDim ? HiddenDim / 4
+ : 128) void rms_norm_mul_rope_apply_fused(const float* x,
+ const float* weight,
+ const float* pe,
+ T* dst,
+ int64_t heads,
+ int64_t tokens,
+ int64_t rows,
+ int64_t nb1,
+ int64_t nb2,
+ int64_t nb3,
+ int rot_half,
+ float eps,
+ float output_scale) {
+ const int lane = threadIdx.x;
+ const int64_t head_count = HiddenDim > 0 ? HiddenDim / D : heads;
+ constexpr bool shared_positions = HiddenDim == 5120;
+ constexpr int physical_warps = shared_positions ? 8 : HiddenDim / 128;
+ int64_t first = int64_t(blockIdx.x) * blockDim.y + threadIdx.y;
+ int64_t end = first + 1;
+ float scale = 1.0f;
if constexpr (HiddenDim > 0) {
- constexpr int threads = HiddenDim / 4;
+ constexpr int threads = HiddenDim > 4096 ? 1024 : HiddenDim / 4;
constexpr int warps = threads / 32;
__shared__ float warp_sums[warps];
- const int tid = threadIdx.y * 32 + lane;
- const float4 v = reinterpret_cast<const float4*>(x)[int64_t(blockIdx.x) * threads + tid];
- // Match the vectorized whole-row RMSNorm reduction before splitting the heads.
- const float sum = sd_warp_sum(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
- if (lane == 0) {
- warp_sums[threadIdx.y] = sum;
+ const auto* row = reinterpret_cast<const float4*>(x) + int64_t(blockIdx.x) * (HiddenDim / 4);
+ // Match the native vectorized RMSNorm reduction, even when several virtual warps share one physical warp.
+ for (int warp = threadIdx.y; warp < warps; warp += physical_warps) {
+ const int tid = warp * 32 + lane;
+ const float4 v = row[tid];
+ float sum = v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w;
+ if constexpr (HiddenDim > 4096) {
+ if (tid + threads < HiddenDim / 4) {
+ const float4 tail = row[tid + threads];
+ sum += tail.x * tail.x + tail.y * tail.y + tail.z * tail.z + tail.w * tail.w;
+ }
+ }
+ sum = sd_warp_sum(sum);
+ if (lane == 0) {
+ warp_sums[warp] = sum;
+ }
}
__syncthreads();
scale = rsqrtf(sd_warp_sum(lane < warps ? warp_sums[lane] : 0.f) / HiddenDim + eps);
@@ -51,14 +63,16 @@ namespace SD_CUDA_NAMESPACE {
} else if (first >= rows) {
return;
}
- for (int64_t row = first; row < end; row += HiddenDim > 0 ? HiddenDim / 128 : 1) {
+ for (int64_t row = first; row < end; row += HiddenDim > 0 ? physical_warps : 1) {
const int64_t head = row % head_count;
const int64_t token = HiddenDim > 0 ? int64_t(blockIdx.x) : (row / heads) % tokens;
const int64_t batch = HiddenDim > 0 ? 0 : row / (heads * tokens);
const float* x_row = x + head * nb1 + token * nb2 + batch * nb3;
const float* weight_row = HiddenDim > 0 ? weight + head * D : weight;
- const int64_t position = HiddenDim > 0 ? row : token;
- const int64_t out_row = HiddenDim > 0 && std::is_same<T, float>::value ? row : (batch * heads + head) * tokens + token;
+ const int64_t position = HiddenDim > 0 && !shared_positions ? row : token;
+ const int64_t out_row = HiddenDim > 0 && !shared_positions && std::is_same<T, float>::value
+ ? row
+ : (batch * heads + head) * tokens + token;
T* out = dst + out_row * D;
float v[D / 32], sums[8] = {};
#pragma unroll
@@ -233,14 +247,17 @@ namespace SD_CUDA_NAMESPACE {
reshape->src[0] != mul || rope->src[0] != reshape || !rope_supports(nullptr, rope, nullptr)) {
return false;
}
- const auto* x = norm->src[0];
- const auto* weight = mul->src[1];
- const auto* pe = rope->src[1];
+ const auto* x = norm->src[0];
+ const auto* weight = mul->src[1];
+ const auto* pe = rope->src[1];
+ const bool shared_positions = x && x->ne[0] == 5120 && reshape->ne[0] == 128 &&
+ reshape->ne[1] == 40 && reshape->ne[2] == ggml_nrows(x);
return x && weight && weight != norm && x->type == GGML_TYPE_F32 && norm->type == GGML_TYPE_F32 &&
weight->type == GGML_TYPE_F32 && ggml_nelements(weight) == x->ne[0] && weight->ne[0] == x->ne[0] &&
- (x->ne[0] == 2048 || x->ne[0] == 4096) && ggml_nrows(x) <= INT_MAX &&
+ (x->ne[0] == 2048 || x->ne[0] == 4096 || shared_positions) &&
+ ggml_nrows(x) <= INT_MAX &&
ggml_are_same_shape(x, norm) && ggml_are_same_shape(x, mul) &&
- reshape->ne[1] == 1 && reshape->ne[3] == 1 &&
+ (reshape->ne[1] == 1 || shared_positions) && reshape->ne[3] == 1 &&
(reshape->ne[0] == 64 || reshape->ne[0] == 128) &&
pe->ne[2] == reshape->ne[0] / 2 && ggml_is_contiguous(pe) &&
ggml_is_contiguous(reshape) && ggml_is_contiguous(x) && ggml_is_contiguous(weight) &&
@@ -258,7 +275,8 @@ namespace SD_CUDA_NAMESPACE {
auto kernel = rope_interleaved(nodes[3])
? rms_norm_mul_rope_apply_fused<HeadDim, true, T, true, HiddenDim>
: rms_norm_mul_rope_apply_fused<HeadDim, false, T, true, HiddenDim>;
- kernel<<<static_cast<unsigned>(tokens), dim3(32, HiddenDim / 128), 0, stream>>>(
+ constexpr int warps = HiddenDim > 4096 ? 8 : HiddenDim / 128;
+ kernel<<<static_cast<unsigned>(tokens), dim3(32, warps), 0, stream>>>(
static_cast<const float*>(x->data), static_cast<const float*>(weight->data), static_cast<const float*>(pe->data), output,
heads, tokens, tokens * heads, HeadDim, HiddenDim, 0, HeadDim / 2, param_f32(nodes[0], 0), scale);
}
@@ -267,7 +285,9 @@ namespace SD_CUDA_NAMESPACE {
static CUDAError hidden_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, T* output, float scale) {
const auto dim = nodes[0]->ne[0];
const auto head_dim = nodes[3]->ne[0];
- if (dim == 4096 && head_dim == 128) {
+ if (dim == 5120) {
+ hidden_rope_launch<5120, 128>(stream, nodes, output, scale);
+ } else if (dim == 4096 && head_dim == 128) {
hidden_rope_launch<4096, 128>(stream, nodes, output, scale);
} else if (dim == 4096) {
hidden_rope_launch<4096, 64>(stream, nodes, output, scale);
@@ -293,10 +313,13 @@ namespace SD_CUDA_NAMESPACE {
bool hidden_rope_head_major(const ggml_tensor* view, const ggml_tensor* norm, const ggml_tensor* rope) {
const auto head_dim = rope->ne[0];
const auto width = norm->ne[0];
- return view->ne[0] == head_dim && view->ne[1] == ggml_nrows(norm) &&
- view->ne[2] == width / head_dim && view->ne[3] == 1 &&
- view->nb[0] == sizeof(float) && view->nb[1] == width * sizeof(float) &&
- view->nb[2] == head_dim * sizeof(float);
+ if (view->ne[0] != head_dim || view->ne[1] != ggml_nrows(norm) ||
+ view->ne[2] != width / head_dim || view->ne[3] != 1) {
+ return false;
+ }
+ return rope->src[0]->ne[1] > 1 ? ggml_is_contiguous(view)
+ : view->nb[0] == sizeof(float) && view->nb[1] == width * sizeof(float) &&
+ view->nb[2] == head_dim * sizeof(float);
}
static int hidden_rope_cast_count(ggml_cgraph* graph, int first) {
diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp
index 1311e97..0e7ce24 100644
--- a/src/core/execution_engine.cpp
+++ b/src/core/execution_engine.cpp
@@ -555,7 +555,9 @@ namespace sd {
constexpr size_t planning_headroom = 128ULL * 1024ULL * 1024ULL;
auto requests = memory_requests(full_measurement.buffers, session_.cache_.pending_bytes(graph));
for (auto& request : requests) {
- request.pending_allocation_bytes = add_bytes(request.pending_allocation_bytes, planning_headroom);
+ if (request.pending_allocation_bytes != 0) {
+ request.pending_allocation_bytes = add_bytes(request.pending_allocation_bytes, planning_headroom);
+ }
}
segmented = !fits(requests, params, DeviceMemoryCheck::Reclaimable);
}
diff --git a/src/model/diffusion/wan.hpp b/src/model/diffusion/wan.hpp
index 124020e..b0878e3 100644
--- a/src/model/diffusion/wan.hpp
+++ b/src/model/diffusion/wan.hpp
@@ -283,18 +283,16 @@ namespace WAN {
namespace WAN {
- static ggml_tensor* modulate_add(ggml_context* ctx, ggml_tensor* x, ggml_tensor* e) {
+ static ggml_tensor* modulate_time(GGMLRunnerContext* ctx, ggml_tensor* x, ggml_tensor* shift, ggml_tensor* scale) {
// x: [N, n_token, dim]
- // e: [N, 1, dim] or [N, T, 1, dim]
- if (ggml_n_dims(e) == 3) {
- int64_t T = e->ne[2];
- x = ggml_reshape_4d(ctx, x, x->ne[0], x->ne[1] / T, T, x->ne[2]); // [N, T, n_token/T, dim]
- x = ggml_add(ctx, x, e);
- x = ggml_reshape_3d(ctx, x, x->ne[0], x->ne[1] * x->ne[2], x->ne[3]); // [N, n_token, dim]
- } else {
- x = ggml_add(ctx, x, e);
+ // shift and scale: [N, 1, dim] or [N, T, 1, dim]
+ if (ggml_n_dims(scale) == 3) {
+ int64_t T = scale->ne[2];
+ x = ggml_reshape_4d(ctx->ggml_ctx, x, x->ne[0], x->ne[1] / T, T, x->ne[2]);
+ x = ggml_ext_modulate(ctx, x, shift, scale);
+ return ggml_reshape_3d(ctx->ggml_ctx, x, x->ne[0], x->ne[1] * x->ne[2], x->ne[3]);
}
- return x;
+ return ggml_ext_modulate(ctx, x, shift, scale);
}
static ggml_tensor* modulate_mul(ggml_context* ctx, ggml_tensor* x, ggml_tensor* e) {
@@ -373,9 +371,7 @@ namespace WAN {
auto ffn_2 = std::dynamic_pointer_cast<Linear>(blocks["ffn.2"]);
// self-attention
- auto y = norm1->forward(ctx, x);
- y = ggml_add(ctx->ggml_ctx, y, modulate_mul(ctx->ggml_ctx, y, es[1]));
- y = modulate_add(ctx->ggml_ctx, y, es[0]);
+ auto y = modulate_time(ctx, norm1->forward(ctx, x), es[0], es[1]);
y = self_attn->forward(ctx, y, pe);
x = ggml_add(ctx->ggml_ctx, x, modulate_mul(ctx->ggml_ctx, y, es[2]));
@@ -386,12 +382,11 @@ namespace WAN {
cross_attn->forward(ctx, norm3->forward(ctx, x), context, context_img_len));
// ffn
- y = norm2->forward(ctx, x);
- y = ggml_add(ctx->ggml_ctx, y, modulate_mul(ctx->ggml_ctx, y, es[4]));
- y = modulate_add(ctx->ggml_ctx, y, es[3]);
+ y = modulate_time(ctx, norm2->forward(ctx, x), es[3], es[4]);
y = ffn_0->forward(ctx, y);
- y = ggml_ext_gelu(ctx, y, true);
+ // Keep GELU out-of-place so it can fuse with ConvRot quantization.
+ y = ggml_ext_gelu(ctx, y);
y = ffn_2->forward(ctx, y);
x = ggml_add(ctx->ggml_ctx, x, modulate_mul(ctx->ggml_ctx, y, es[5]));
@@ -489,9 +484,7 @@ namespace WAN {
auto norm = std::dynamic_pointer_cast<LayerNorm>(blocks["norm"]);
auto head = std::dynamic_pointer_cast<Linear>(blocks["head"]);
- x = norm->forward(ctx, x);
- x = ggml_add(ctx->ggml_ctx, x, modulate_mul(ctx->ggml_ctx, x, es[1]));
- x = modulate_add(ctx->ggml_ctx, x, es[0]);
+ x = modulate_time(ctx, norm->forward(ctx, x), es[0], es[1]);
x = head->forward(ctx, x);
return x;
}
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index 11dd990..8815846 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -2453,8 +2453,10 @@ ModelManager::CapacityCheck ModelManager::check_capacity(
const size_t prefetch_reused_bytes = request.prefetch_buffer && request.prefetch_buffer->buffer ? request.prefetch_buffer->bytes : 0;
const size_t reused_bytes = add(request.reused_buffer_bytes, prefetch_reused_bytes);
const size_t pending_bytes = add(request.pending_allocation_bytes, missing);
- result.required_device_bytes = add(pending_bytes - std::min(pending_bytes, reused_bytes), safety_margin);
- result.required_budget_bytes = add(request.runtime_peak_bytes(), missing);
+ const size_t allocation_bytes = pending_bytes - std::min(pending_bytes, reused_bytes);
+ // WDDM can report zero free memory even after all buffers for the graph have been allocated.
+ result.required_device_bytes = allocation_bytes == 0 ? 0 : add(allocation_bytes, safety_margin);
+ result.required_budget_bytes = add(request.runtime_peak_bytes(), missing);
const bool allow_reclamation = check == DeviceMemoryCheck::Reclaimable;
std::vector<ggml_tensor*> protected_params;