diff --git a/docs/development/pe_cache.md b/docs/development/pe_cache.md index e18195999..bc4a72d03 100644 --- a/docs/development/pe_cache.md +++ b/docs/development/pe_cache.md @@ -1,9 +1,9 @@ # Position embedding cache `sd::PECache` stores CPU-side `sd::Tensor` data. Each model runner owns -its cache and calls the existing `make_input()` on every graph build. Cache -hits skip PE generation; allocation and upload remain ordinary graph-input -operations. `GGMLRunner` has no PE-specific code or resource hooks. +its cache. A cache hit skips PE generation, and `make_input()` submits the CPU +data through ordinary graph-input allocation and upload. `GGMLRunner` has no +PE-specific code or resource hooks. The cache keeps the most recent key and tensor for each named PE input. A matching key returns the existing tensor by reference. Changing its parameters @@ -13,6 +13,12 @@ there is no LRU, device-buffer cache, memory budget, or graph lifecycle callback CPU data lives with the model runner, including across `runner_end()` calls, and is released when its named entry is replaced or the cache is destroyed. +On CUDA, HIP, and MUSA, LTXAV retains large video RoPE tensors in the existing +device runner cache during sampling. It stores each rotation as an FP32 2×2 matrix. +The tensors count against the runner's device memory budget. +The runner clears them when the position key changes or sampling ends. If +allocation fails, it clears the device cache and retries with the CPU inputs. + ## Adding a model Include `core/pe_cache.h` and declare a member: diff --git a/src/core/cuda/convrot.cu b/src/core/cuda/convrot.cu index c069d46b9..912080410 100644 --- a/src/core/cuda/convrot.cu +++ b/src/core/cuda/convrot.cu @@ -29,8 +29,10 @@ namespace SD_CUDA_NAMESPACE { NORM, MOD, RMS_MOD, + RMS_MOD_VEC, SWIGLU, SITU, + GELU, SILU, SIGMOID }; struct Operation { @@ -43,6 +45,17 @@ namespace SD_CUDA_NAMESPACE { int64_t k, rows, stride, up_stride, gate_offset = 0, up_offset = 0; float eps = 0.f, scale = 1.f, bias = 0.f; }; + static bool vector_rms_input(const ggml_tensor* input, int64_t width) { + if (width != 1024 && width != 2048 && width != 4096) { + return false; + } + size_t offset = 0; + while (!input->data && input->view_src) { + offset += input->view_offs; + input = input->view_src; + } + return (reinterpret_cast(input->data) + offset) % 16 == 0; + } static bool describe(ggml_tensor* const* nodes, int count, Operation& op) { int group; const auto* first = nodes[0]; @@ -73,14 +86,20 @@ namespace SD_CUDA_NAMESPACE { op.shift = first->src[2]; if (!vector(op.modulation, op.k) || (op.shift && !vector(op.shift, op.k))) return false; - } else if (count == 4 && first->op == GGML_OP_RMS_NORM && nodes[1]->op == GGML_OP_MUL && nodes[1]->src[0] == first && - sd_ggml_modulate_describe(nodes[2]) && nodes[2]->src[0] == nodes[1] && value == nodes[2]) { - op.kind = RMS_MOD; - op.weight = nodes[1]->src[1]; - op.modulation = nodes[2]->src[1]; - op.shift = nodes[2]->src[2]; + } else if (first->op == GGML_OP_RMS_NORM && value == nodes[count - 2] && sd_ggml_modulate_describe(value)) { + if (count == 3 && value->src[0] == first && vector_rms_input(op.input, op.k)) { + op.kind = RMS_MOD_VEC; + } else if (count == 4 && nodes[1]->op == GGML_OP_MUL && nodes[1]->src[0] == first && + value->src[0] == nodes[1] && op.k >= 1024 && vector(nodes[1]->src[1], op.k)) { + op.kind = RMS_MOD; + op.weight = nodes[1]->src[1]; + } else { + return false; + } + op.modulation = value->src[1]; + op.shift = value->src[2]; op.eps = param_f32(first, 0); - if (op.k < 1024 || !vector(op.weight, op.k) || !vector(op.modulation, op.k) || (op.shift && !vector(op.shift, op.k))) + if (!vector(op.modulation, op.k) || (op.shift && !vector(op.shift, op.k))) return false; } else if (count == 2 && first->op == GGML_OP_GLU && value == first) { const auto glu = ggml_get_glu_op(first); @@ -97,6 +116,8 @@ namespace SD_CUDA_NAMESPACE { else op.up_offset = op.k; } + } else if (count == 2 && first->op == GGML_OP_UNARY && ggml_get_unary_op(first) == GGML_UNARY_OP_GELU && value == first) { + op.kind = GELU; } else if (count == 3 && first->op == GGML_OP_UNARY && nodes[1]->op == GGML_OP_MUL && value == nodes[1] && (nodes[1]->src[0] == first || nodes[1]->src[1] == first)) { auto unary = ggml_get_unary_op(first); @@ -118,17 +139,20 @@ 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 ? 256 - : 128; + const size_t extra = op.kind == NORM ? 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*) { if (fusion_disabled()) return 0; - auto* g = const_cast(graph); - const int available = ggml_graph_n_nodes(g) - first; - const auto* node = ggml_graph_node(g, first); - const int count = node->op == GGML_OP_RMS_NORM ? 4 : node->op == GGML_OP_NORM || node->op == GGML_OP_UNARY ? 3 + auto* g = const_cast(graph); + const int available = ggml_graph_n_nodes(g) - first; + const auto* node = ggml_graph_node(g, first); + const bool unary_mul = node->op == GGML_OP_UNARY && ggml_get_unary_op(node) != GGML_UNARY_OP_GELU; + const bool affine_rms = node->op == GGML_OP_RMS_NORM && available >= 2 && + ggml_graph_node(g, first + 1)->op == GGML_OP_MUL; + const int count = affine_rms ? 4 : node->op == GGML_OP_RMS_NORM || node->op == GGML_OP_NORM || unary_mul ? 3 : 2; if (available < count) return 0; @@ -157,6 +181,11 @@ 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])) { + chain[0] = weight; + chain[1] = value; + chain[2] = quant; + count = 3; } else { chain[0] = value; chain[1] = quant; @@ -221,26 +250,26 @@ namespace SD_CUDA_NAMESPACE { const auto x = reinterpret_cast(a->data), y = reinterpret_cast(b->data); return x <= y ? y - x < ggml_nbytes(a) : x - y < ggml_nbytes(b); } - template + template static CUDAError launch(Plan& p, const Operation& op, int8_t* output, CUDAStream stream) { - constexpr bool warp = Scaled || RMS || Modulate; + constexpr bool warp = Scaled || RMS || Modulate || Gelu; constexpr int extra = Normalize ? 384 : RMS ? 256 : 128; if (!p.configured) { - auto status = cuda_set_shared_memory(quantize, + auto status = cuda_set_shared_memory(quantize, int(p.device.shared_memory - extra)); if (status != cuda_success) return status; p.configured = true; } - const int threads = Normalize ? 1024 : RMS ? (op.k <= 1024 ? 128 : op.k <= 6144 ? 256 - : op.k <= 8192 ? 512 - : 1024) - : (Situ ? op.k >= 8192 : Swiglu && !Sigmoid && op.k >= 16384) ? 512 - : 256; + const int threads = Normalize ? 1024 : RMS ? (op.k <= 1024 ? 128 : op.k <= 6144 ? 256 + : op.k <= 8192 ? 512 + : 1024) + : (Situ ? op.k >= 8192 : (Gelu || (Swiglu && !Sigmoid)) && op.k >= 16384) ? 512 + : 256; const int64_t padded = (op.rows + 3) / 4 * 4; auto data = [](const ggml_tensor* t) { return t ? static_cast(t->data) : nullptr; }; - quantize<<>>( + quantize<<>>( data(op.input) + op.gate_offset, output, reinterpret_cast(output + op.k * padded), op.k, op.rows, op.k, op.up ? data(op.up) + op.up_offset : nullptr, op.stride, op.up_stride, nullptr, nullptr, data(op.modulation), op.eps, op.scale, op.bias, data(op.weight), data(op.shift)); return cuda_last_error(); @@ -271,6 +300,9 @@ namespace SD_CUDA_NAMESPACE { case RMS_MOD: error = launch(plan, op, output, stream); break; + case RMS_MOD_VEC: + error = launch(plan, op, output, stream); + break; case MOD: error = launch(plan, op, output, stream); break; @@ -281,6 +313,9 @@ namespace SD_CUDA_NAMESPACE { case SITU: error = launch(plan, op, output, stream); break; + case GELU: + error = launch(plan, op, output, stream); + break; case SIGMOID: error = launch(plan, op, output, stream); break; diff --git a/src/core/cuda/convrot_kernel.h b/src/core/cuda/convrot_kernel.h index fa9e4daf0..6611e9b77 100644 --- a/src/core/cuda/convrot_kernel.h +++ b/src/core/cuda/convrot_kernel.h @@ -46,7 +46,7 @@ namespace SD_CUDA_NAMESPACE { return __fmul_rn(__fmul_rn(a, 1.0f / (1.0f + expf(-gate))), b); } - template + template __global__ void quantize( const T* src, int8_t* dst, @@ -81,12 +81,18 @@ namespace SD_CUDA_NAMESPACE { [[maybe_unused]] float rms_scale = 1.0f; if constexpr (rms_modulation) { __shared__ float sums[32]; - // Preserve the unfused RMSNorm's 1024-thread reduction order with fewer physical warps. - for (int virtual_tid = tid; virtual_tid < 1024; virtual_tid += blockDim.x) { + // Match the unfused RMSNorm reduction across a smaller physical block. + const int reduction_threads = rms_vec ? k / 4 : 1024; + for (int virtual_tid = tid; virtual_tid < reduction_threads; virtual_tid += blockDim.x) { float partial = 0.0f; - for (int64_t i = virtual_tid; i < k; i += 1024) { - const float value = src_row[i]; - partial += value * value; + if constexpr (rms_vec) { + const float4 a = reinterpret_cast(src_row)[virtual_tid]; + partial = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; + } else { + for (int64_t i = virtual_tid; i < k; i += 1024) { + const float value = src_row[i]; + partial += value * value; + } } partial = warp_reduce_sum(partial); if (tid % 32 == 0) { @@ -94,7 +100,8 @@ namespace SD_CUDA_NAMESPACE { } } __syncthreads(); - const float sum = warp_reduce_sum(sums[tid % 32]); + const int lane = tid % 32; + const float sum = warp_reduce_sum(lane < reduction_threads / 32 ? sums[lane] : 0.f); rms_scale = rsqrtf(sum / k + eps); } @@ -108,7 +115,10 @@ namespace SD_CUDA_NAMESPACE { if constexpr (!swiglu) { float value = src_row[i]; if constexpr (rms_modulation) { - value = __fmul_rn(__fmul_rn(value, rms_scale), rms_weight[i]); + value = __fmul_rn(value, rms_scale); + if constexpr (!rms_vec) { + value = __fmul_rn(value, rms_weight[i]); + } } if constexpr (rms_modulation || modulate) { value = __fadd_rn(value, __fmul_rn(value, modulation[i])); @@ -119,6 +129,9 @@ namespace SD_CUDA_NAMESPACE { if constexpr (scaled) { value = __fmaf_rn(value, input_scale, input_bias); } + if constexpr (gelu) { + value = 0.5f * value * (1.0f + tanhf(0.7978845608028654f * value * (1.0f + 0.044715f * value * value))); + } v[j] = value * (1.0f / 16.0f); } else { float gate_value, up_value; @@ -260,7 +273,6 @@ namespace SD_CUDA_NAMESPACE { dst_row[i] = (int8_t)value; } } - } } #endif diff --git a/src/core/cuda/cute_attention.cu b/src/core/cuda/cute_attention.cu index a4224321e..2ded988b1 100644 --- a/src/core/cuda/cute_attention.cu +++ b/src/core/cuda/cute_attention.cu @@ -381,7 +381,8 @@ static __device__ __forceinline__ float convrot_h4_cuda(float a, float b, float return __fadd_rn(__fadd_rn(__fadd_rn(a, b), c), d); } -static __global__ void quantize_attention(const half* src, int8_t* dst, float* scales, int64_t k, int64_t rows, float input_scale, float input_bias) { +template +static __global__ void quantize_attention(const half* src, int8_t* dst, float* scales, int64_t k, int64_t rows, float input_scale, float input_bias, const float* gates, int head_shift) { const int64_t row = blockIdx.x; const int tid = threadIdx.x; if (row >= rows) @@ -398,8 +399,14 @@ static __global__ void quantize_attention(const half* src, int8_t* dst, float* s float v[8]; #pragma unroll for (int j = 0; j < 8; ++j) { - const float value = __fmaf_rn(__half2float(src_row[group * group_size + j * 32 + lane]), input_scale, input_bias); - v[j] = value * (1.0f / 16.0f); + const int64_t col = group * group_size + j * 32 + lane; + float value = __half2float(src_row[col]); + if constexpr (Gated) { + value = __fmul_rn(value, gates[row * (k >> head_shift) + (col >> head_shift)]); + } else { + value = __fmaf_rn(value, input_scale, input_bias); + } + v[j] = value * (1.0f / 16.0f); } // One logical warp owns H256, keeping every butterfly in registers. #pragma unroll @@ -569,23 +576,39 @@ static const ggml_tensor* graph_node(const ggml_cgraph* graph, int index) { return ggml_graph_node(const_cast(graph), index); } +static bool attention_output_view(const ggml_tensor* node, const ggml_tensor* attn) { + return node && (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE) && + node->view_offs == 0 && ggml_is_contiguous(node) && ggml_nelements(node) == ggml_nelements(attn); +} + +static bool attention_output_gate(const ggml_tensor* node, const ggml_tensor* attn) { + const auto* input = node->src[0]; + const auto* gate = node->src[1]; + return node->op == GGML_OP_MUL && input && gate && input->type == GGML_TYPE_F32 && + (attn->ne[0] == 64 || attn->ne[0] == 128) && gate->type == GGML_TYPE_F32 && ggml_is_contiguous(gate) && + ggml_are_same_shape(input, attn) && ggml_are_same_shape(node, input) && ggml_is_contiguous(node) && + gate->ne[0] == 1 && gate->ne[1] == input->ne[1] && gate->ne[2] == input->ne[2] && gate->ne[3] == input->ne[3]; +} + static int output_fusion(ggml_backend_dev_t device, const ggml_cgraph* graph, int first) { const auto* attn = graph_node(graph, first); const auto* previous = attn; const int total = ggml_graph_n_nodes(const_cast(graph)); bool scaled = false; + bool gated = false; for (int count = 1; count < 8 && first + count < total; ++count) { const auto* node = graph_node(graph, first + count); int convrot_group; if (node->src[0] != previous) break; - if (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE) { - if (node->view_offs || !ggml_is_contiguous(node) || ggml_nelements(node) != ggml_nelements(attn)) - break; - } else if (node->op == GGML_OP_SCALE && !scaled) { + if (attention_output_view(node, attn)) { + // The shape-only nodes preserve the flattened row order. + } else if (node->op == GGML_OP_SCALE && !scaled && !gated) { if (!ggml_is_contiguous(node) || !ggml_are_same_shape(previous, node)) break; scaled = true; + } else if (!gated && !scaled && attention_output_gate(node, attn)) { + gated = true; } else if (sd_ggml_convrot_describe(node, &convrot_group)) { if (convrot_group == 256 && previous->ne[0] % 256 == 0 && size_t(previous->ne[0]) * sizeof(float) + 128 <= cuda_device(device)->properties.sharedMemPerBlockOptin) @@ -603,6 +626,26 @@ static int output_fusion(ggml_backend_dev_t device, const ggml_cgraph* graph, in return 1; } +static int attention_hidden_rope_offset(const ggml_cgraph* graph, int first) { + const int count = ggml_graph_n_nodes(const_cast(graph)); + if (first + 4 >= count) + return 0; + const auto* norm = graph_node(graph, first); + const auto* rope = graph_node(graph, first + 3); + if (!sd_cuda::hidden_rope_fusion_supports(norm, graph_node(graph, first + 1), graph_node(graph, first + 2), rope)) + return 0; + const auto* query = rope; + for (int i = first + 4; i < count && i < first + 12; ++i) { + const auto* node = graph_node(graph, i); + if (node->op == GGML_OP_FLASH_ATTN_EXT && node->src[0] == query) + return sd_cuda::hidden_rope_head_major(query, norm, rope) ? i - first : 0; + if (!sd_cuda::hidden_rope_view_of(node, query)) + break; + query = node; + } + return 0; +} + static int attention_match(ggml_backend_dev_t device, const ggml_cgraph* graph, int first, void*) { if (!fusion_enabled()) return 0; @@ -615,11 +658,14 @@ static int attention_match(ggml_backend_dev_t device, const ggml_cgraph* graph, return 0; offset = 5; } else if (graph_node(graph, first)->op == GGML_OP_RMS_NORM) { - if (first + 3 >= ggml_graph_n_nodes(const_cast(graph)) || - !sd_cuda::rope_fusion_supports(graph_node(graph, first), graph_node(graph, first + 1), graph_node(graph, first + 2)) || - graph_node(graph, first + 3)->src[0] != graph_node(graph, first + 2)) - return 0; - offset = 3; + offset = attention_hidden_rope_offset(graph, first); + if (!offset) { + if (first + 3 >= ggml_graph_n_nodes(const_cast(graph)) || + !sd_cuda::rope_fusion_supports(graph_node(graph, first), graph_node(graph, first + 1), graph_node(graph, first + 2)) || + graph_node(graph, first + 3)->src[0] != graph_node(graph, first + 2)) + return 0; + offset = 3; + } } if (!attention_selected(device, graph_node(graph, first + offset))) return 0; @@ -630,19 +676,54 @@ static int attention_match(ggml_backend_dev_t device, const ggml_cgraph* graph, static void attention_optimize(ggml_backend_dev_t device, ggml_cgraph* graph, void*) { if (!fusion_enabled()) return; + const int total = ggml_graph_n_nodes(graph); + for (int i = 1; i < total; ++i) { + const auto* mul = graph_node(graph, i); + if (mul->op != GGML_OP_MUL) + continue; + const auto* attn = mul->src[0]; + while (attention_output_view(attn, mul)) { + attn = attn->src[0]; + } + if (!attn || !attention_selected(device, attn) || !attention_output_gate(mul, attn)) + continue; + for (int j = i - 1; j >= 0 && j >= i - 48; --j) { + if (graph_node(graph, j) != attn) + continue; + int end = j + 1; + while (end < i && attention_output_view(graph_node(graph, end), attn) && + graph_node(graph, end)->src[0] == graph_node(graph, end - 1)) { + ++end; + } + if (end < i && graph_node(graph, end - 1) == mul->src[0]) + ggml_ext_graph_delay(graph, j, end - j, i); + break; + } + } for (int i = 3; i < ggml_graph_n_nodes(const_cast(graph)); ++i) { const auto* attn = graph_node(graph, i); if (!attention_selected(device, attn)) continue; - for (int j = i - 3; j >= 0 && j >= i - 32; --j) { - if (attn->src[0] == graph_node(graph, j + 2) && - sd_cuda::rope_fusion_supports(graph_node(graph, j), graph_node(graph, j + 1), graph_node(graph, j + 2))) { - if (j >= 2 && sd_cuda_i8_rope_supports(device, graph_node(graph, j - 2), graph_node(graph, j - 1), graph_node(graph, j), graph_node(graph, j + 1), graph_node(graph, j + 2)) && - ggml_ext_graph_delay(graph, j - 2, 5, i)) + const auto* query = attn->src[0]; + for (int j = i - 1; j >= 2 && j >= i - 48; --j) { + if (graph_node(graph, j) != query) + continue; + int rope = j; + while (rope > 3 && sd_cuda::hidden_rope_view_of(graph_node(graph, rope), graph_node(graph, rope - 1))) { + --rope; + } + if (rope >= 3 && j - rope < 8 && + sd_cuda::hidden_rope_fusion_supports(graph_node(graph, rope - 3), graph_node(graph, rope - 2), + graph_node(graph, rope - 1), graph_node(graph, rope)) && + sd_cuda::hidden_rope_head_major(query, graph_node(graph, rope - 3), graph_node(graph, rope))) { + ggml_ext_graph_delay(graph, rope - 3, j - rope + 4, i); + } else if (sd_cuda::rope_fusion_supports(graph_node(graph, j - 2), graph_node(graph, j - 1), query)) { + if (j >= 4 && sd_cuda_i8_rope_supports(device, graph_node(graph, j - 4), graph_node(graph, j - 3), graph_node(graph, j - 2), graph_node(graph, j - 1), query) && + ggml_ext_graph_delay(graph, j - 4, 5, i)) break; - ggml_ext_graph_delay(graph, j, 3, i); - break; + ggml_ext_graph_delay(graph, j - 2, 3, i); } + break; } } } @@ -664,10 +745,11 @@ static bool attention_direct_input(const ggml_tensor* src) { } static ggml_status attention_prepare(ggml_backend_t, ggml_tensor* const* nodes, int count, void** state, size_t* workspace_size, void*) { - auto* plan = new AttentionPlan{}; - *state = plan; - plan->index = ggml_ext_op_get(nodes[0]) == sd_ggml_i8_op() ? 5 : nodes[0]->op == GGML_OP_RMS_NORM ? 3 - : 0; + auto* plan = new AttentionPlan{}; + *state = plan; + while (plan->index < count && nodes[plan->index]->op != GGML_OP_FLASH_ATTN_EXT) { + ++plan->index; + } GGML_ASSERT(plan->index < count); const auto* attn = nodes[plan->index]; const auto* dst = nodes[count - 1]; @@ -729,7 +811,10 @@ static ggml_status attention_execute(const ggml_ext_execution_context* execution for (int i = 0; i < 3; ++i) { const auto* src = attn->src[i]; const float scale = i == 0 ? param_f32(attn, 0) : 1.0f; - if (i == 0 && plan.index == 5) { + if (i == 0 && plan.index >= 4 && nodes[0]->op == GGML_OP_RMS_NORM) { + if (sd_cuda::hidden_rope_launch(stream, nodes, work[0], true, scale) != cudaSuccess) + return GGML_STATUS_FAILED; + } else if (i == 0 && plan.index == 5) { if (sd_cuda_i8_rope_launch(stream, nodes, work[0], scale) != cudaSuccess) return GGML_STATUS_FAILED; } else if (i == 0 && plan.index == 3) { @@ -751,10 +836,13 @@ static ggml_status attention_execute(const ggml_ext_execution_context* execution const auto* k = attn->src[1]; auto* dst = nodes[count - 1]; float scale = 1.0f, bias = 0.0f; + const float* gates = nullptr; for (int i = plan.index + 1; i < count; ++i) { if (nodes[i]->op == GGML_OP_SCALE) { scale = param_f32(nodes[i], 0); bias = param_f32(nodes[i], 1); + } else if (nodes[i]->op == GGML_OP_MUL) { + gates = static_cast(nodes[i]->src[1]->data); } } sd_fattn_cute::Params p = {reinterpret_cast(inputs[0]), @@ -781,7 +869,7 @@ static ggml_status attention_execute(const ggml_ext_execution_context* execution error = attention_launch<112, true>(context, p, q->ne[3]); break; case 128: - error = p.dim == 128 && p.nq >= 4096 && p.nq < 8192 && p.nk >= 4096 && p.nk < 8192 && + error = p.dim == 128 && p.nq >= 4096 && p.nk >= 4096 && properties.major == 8 && properties.minor == 9 ? attention_launch<128, true, true>(context, p, q->ne[3]) : attention_launch<128>(context, p, q->ne[3]); @@ -803,11 +891,13 @@ static ggml_status attention_execute(const ggml_ext_execution_context* execution auto* packed = static_cast(dst->data); if (rows != padded_rows && cudaMemsetAsync(packed + width * rows, 0, width * (padded_rows - rows), stream) != cudaSuccess) return GGML_STATUS_FAILED; - if (cudaFuncSetAttribute(quantize_attention, cudaFuncAttributeMaxDynamicSharedMemorySize, + auto quantize = gates ? quantize_attention : quantize_attention; + if (cudaFuncSetAttribute(quantize, cudaFuncAttributeMaxDynamicSharedMemorySize, int(properties.sharedMemPerBlockOptin - 128)) != cudaSuccess) return GGML_STATUS_FAILED; - quantize_attention<<>>(work[3], packed, - reinterpret_cast(packed + width * padded_rows), width, rows, scale, bias); + quantize<<>>(work[3], packed, + reinterpret_cast(packed + width * padded_rows), width, rows, scale, bias, + gates, q->ne[0] == 128 ? 7 : 6); } else { copy_from_half<<<(ggml_nelements(attn) + 255) / 256, 256, 0, stream>>>(work[3], static_cast(dst->data), ggml_nelements(attn), scale, bias, dst->op == GGML_OP_SCALE); } diff --git a/src/core/cuda/i8_gated_residual.cu b/src/core/cuda/i8_gated_residual.cu index 71d24348f..fd71f3bd7 100644 --- a/src/core/cuda/i8_gated_residual.cu +++ b/src/core/cuda/i8_gated_residual.cu @@ -112,9 +112,10 @@ namespace sd_i8_gated { using Residual = cutlass::epilogue::threadblock::VisitorAuxLoad>; using GateMul = cutlass::epilogue::threadblock::VisitorCompute; using Add = cutlass::epilogue::threadblock::VisitorCompute; + using WithBias = cutlass::epilogue::threadblock::Sm80EVT; using Scalar = cutlass::epilogue::threadblock::VisitorScalarBroadcast; - using ScaleOut = cutlass::epilogue::threadblock::Sm80EVT; - using Scaled = std::conditional_t; + using ScaleOut = cutlass::epilogue::threadblock::Sm80EVT; + using Scaled = std::conditional_t; using Gated = cutlass::epilogue::threadblock::Sm80EVT; using WithResidual = cutlass::epilogue::threadblock::Sm80EVT; using Output = WithResidual; @@ -149,7 +150,6 @@ namespace sd_i8_gated { struct DeviceInfo { int ordinal = -1; int major = 0; - int minor = 0; int sms = 0; int threads_per_sm = 0; size_t shared = 0; @@ -167,7 +167,7 @@ namespace sd_i8_gated { int ordinal = query ? query(device) : -1; cudaDeviceProp props = {}; if (ordinal >= 0 && cudaGetDeviceProperties(&props, ordinal) == cudaSuccess) - info = {ordinal, props.major, props.minor, props.multiProcessorCount, props.maxThreadsPerMultiProcessor, size_t(props.sharedMemPerBlockOptin)}; + info = {ordinal, props.major, props.multiProcessorCount, props.maxThreadsPerMultiProcessor, size_t(props.sharedMemPerBlockOptin)}; cache.emplace(device, info); return info; } @@ -211,19 +211,21 @@ namespace sd_i8_gated { } template static typename Types::Gemm::Arguments arguments(const Operation& op, float* output, bool metadata) { - const auto* x = metadata ? nullptr : static_cast(op.mat.input->data); - const auto* w = metadata ? nullptr : static_cast(op.mat.weight->data); - const auto* xs = metadata ? nullptr : op.mat.packed ? reinterpret_cast(x + op.k * ((op.rows + 3) / 4 * 4)) - : static_cast(op.mat.input_scale->data); - const auto* ws = metadata ? nullptr : static_cast(op.mat.weight_scale->data); - const auto* gate = metadata ? nullptr : static_cast(op.gate->data); - auto* residual = metadata ? nullptr : static_cast(op.residual->data); - typename Types::ScaleW::Arguments scales = {{{}, {xs, 0.f, {}}, {}}, {ws, 0.f, {}}, {}}; + const auto* x = metadata ? nullptr : static_cast(op.mat.input->data); + const auto* w = metadata ? nullptr : static_cast(op.mat.weight->data); + const auto* xs = metadata ? nullptr : op.mat.packed ? reinterpret_cast(x + op.k * ((op.rows + 3) / 4 * 4)) + : static_cast(op.mat.input_scale->data); + const auto* ws = metadata ? nullptr : static_cast(op.mat.weight_scale->data); + const auto* bias = metadata || !op.mat.bias ? nullptr : static_cast(op.mat.bias->data); + const auto* gate = metadata ? nullptr : static_cast(op.gate->data); + auto* residual = metadata ? nullptr : static_cast(op.residual->data); + typename Types::ScaleW::Arguments scales = {{{}, {xs, 0.f, {}}, {}}, {ws, 0.f, {}}, {}}; + typename Types::WithBias::Arguments with_bias = {scales, {bias, -0.f, {}}, {}}; typename Types::Scaled::Arguments scaled; - if constexpr (std::is_same::value) - scaled = scales; + if constexpr (std::is_same::value) + scaled = with_bias; else - scaled = {scales, {{op.scale}}, {}}; + scaled = {with_bias, {{op.scale}}, {}}; typename Types::Epilogue::Arguments epilogue = {{{scaled, {gate, 0.f, {}}, {}}, {residual, 0.f, {op.n, cute::_1{}, op.rows * op.n}}, {}}, {output, {op.n, cute::_1{}, op.rows * op.n}}}; return {cutlass::gemm::GemmUniversalMode::kGemm, {int(op.rows), int(op.n), int(op.k)}, 1, epilogue, x, w, nullptr, nullptr, op.rows * op.k, op.n * op.k, 0, 0, op.k, op.k, 0, 0}; } @@ -289,7 +291,16 @@ namespace sd_i8_gated { return op.rows >= 8192 ? configure(op, plan) : configure(op, plan); } static bool configure(const Operation& op, Plan& plan) { - if (plan.device.major == 8 && plan.device.minor == 9 && op.scale == 1.f && + if (op.scale == 1.f && + op.rows >= 8192 && op.n >= 2048 && op.n <= 4096 && op.k >= 4096) { + if (op.k >= 2 * op.n) { + if (configure, false, false>(op, plan)) + return true; + } else if (configure, false, true>(op, plan)) { + return true; + } + } + if (op.scale == 1.f && op.rows >= 4096 && op.rows < 8192 && op.n == 3072 && (op.k == 3072 || op.k == 8192) && configure, false, false>(op, plan)) return true; @@ -332,7 +343,7 @@ namespace sd_i8_gated { const bool scaled = producer->op == GGML_OP_SCALE; const auto* mat = scaled ? producer->src[0] : producer; SDI8Operation op; - if (!sd_ggml_i8_describe(mat, &op) || op.codebook || op.input->type != GGML_TYPE_I8 || !op.weight_scale || op.bias) + if (!sd_ggml_i8_describe(mat, &op) || op.codebook || op.input->type != GGML_TYPE_I8 || !op.weight_scale) continue; int scale_index = -1; for (int j = i - 1; j >= 0 && j >= i - 64; --j) { @@ -362,7 +373,8 @@ namespace sd_i8_gated { for (int i = 0; i < std::min(available, 5); ++i) nodes[i] = ggml_graph_node(const_cast(graph), first + i); SDI8Operation mat; - if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.codebook || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || mat.bias) + if (!sd_ggml_i8_describe(nodes[0], &mat) || mat.codebook || mat.input->type != GGML_TYPE_I8 || !mat.weight_scale || + (mat.bias && !aligned(mat.bias))) return 0; const int64_t rows = ggml_nrows(nodes[0]), n = nodes[0]->ne[0], k = mat.weight->ne[0]; if (rows < (small_rows_enabled(rows, n, k) ? 1 : 128) || rows > INT_MAX || n > INT_MAX || k > INT_MAX || n % 128 || k % 64 || @@ -424,7 +436,7 @@ namespace sd_i8_gated { static bool needs_scratch(const ggml_tensor* dst, const Operation& op) { if (address(dst) % 16 != 0) return true; - for (const auto* input : {op.mat.weight, op.mat.input, op.mat.input_scale, op.mat.weight_scale, op.gate, op.residual, op.prefix}) { + for (const auto* input : {op.mat.weight, op.mat.input, op.mat.input_scale, op.mat.weight_scale, op.mat.bias, op.gate, op.residual, op.prefix}) { if (input == op.residual && !op.prefix && address(input) == address(dst)) continue; if (overlaps(dst, input)) diff --git a/src/core/cuda/modulate.cu b/src/core/cuda/modulate.cu index c4af6f6e0..c941ed02e 100644 --- a/src/core/cuda/modulate.cu +++ b/src/core/cuda/modulate.cu @@ -1,4 +1,7 @@ #include +#include +#include +#include #include "core/ggml_extensions.h" #include "runtime.h" @@ -29,6 +32,157 @@ namespace SD_CUDA_NAMESPACE { } } + template + static __global__ void modulate_rows(const float4* x, const float4* scale, const float4* shift, float4* dst, int64_t row_mask, int64_t count) { + for (int64_t i = int64_t(blockIdx.x) * blockDim.x + threadIdx.x; i < count; i += int64_t(blockDim.x) * gridDim.x) { + const int64_t col = i & row_mask; + const float4 a = x[i]; + const float4 s = scale[col]; + float4 value = make_float4(__fadd_rn(a.x, __fmul_rn(a.x, s.x)), __fadd_rn(a.y, __fmul_rn(a.y, s.y)), + __fadd_rn(a.z, __fmul_rn(a.z, s.z)), __fadd_rn(a.w, __fmul_rn(a.w, s.w))); + if constexpr (Shift) { + const float4 b = shift[col]; + value = make_float4(__fadd_rn(value.x, b.x), __fadd_rn(value.y, b.y), + __fadd_rn(value.z, b.z), __fadd_rn(value.w, b.w)); + } + dst[i] = value; + } + } + + static __device__ float warp_sum(float value) { + for (int offset = 16; offset > 0; offset >>= 1) + value += cuda_shuffle_xor(value, offset, 32); + return value; + } + + template + static __global__ __launch_bounds__(Width / 4) void rms_modulate_rows( + const float4* x, + const float4* scale, + const float4* shift, + float4* dst, + float eps) { + constexpr int warps = Width / (4 * 32); + __shared__ float partials[warps]; + const int col = threadIdx.x; + const int lane = col % 32; + const int64_t index = int64_t(blockIdx.x) * (Width / 4) + col; + const float4 a = x[index]; + // Match the vectorized RMSNorm kernel's reduction order. + const float partial = warp_sum(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); + if (lane == 0) + partials[col / 32] = partial; + __syncthreads(); + const float r = rsqrtf(warp_sum(lane < warps ? partials[lane] : 0.f) / Width + eps); + const float4 y = make_float4(__fmul_rn(a.x, r), __fmul_rn(a.y, r), __fmul_rn(a.z, r), __fmul_rn(a.w, r)); + const float4 s = scale[col]; + const float4 value = make_float4(__fadd_rn(y.x, __fmul_rn(y.x, s.x)), __fadd_rn(y.y, __fmul_rn(y.y, s.y)), + __fadd_rn(y.z, __fmul_rn(y.z, s.z)), __fadd_rn(y.w, __fmul_rn(y.w, s.w))); + if (shift) { + const float4 b = shift[col]; + dst[index] = make_float4(__fadd_rn(value.x, b.x), __fadd_rn(value.y, b.y), + __fadd_rn(value.z, b.z), __fadd_rn(value.w, b.w)); + } else { + dst[index] = value; + } + } + + static bool vector_aligned(const ggml_tensor* tensor) { + if (tensor->type != GGML_TYPE_F32 || !ggml_is_contiguous(tensor)) + return false; + size_t offset = 0; + while (!tensor->data && tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + return (reinterpret_cast(tensor->data) + offset) % 16 == 0; + } + + static bool rms_modulate_supports(const ggml_tensor* norm, const ggml_tensor* mod) { + if (norm->op != GGML_OP_RMS_NORM || !sd_ggml_modulate_describe(mod) || mod->src[0] != norm || + mod->src[1] == norm || mod->src[2] == norm) + return false; + const auto* input = norm->src[0]; + const auto width = input->ne[0]; + const auto row_vector = [&](const ggml_tensor* tensor) { + return tensor->ne[0] == width && ggml_nelements(tensor) == width && vector_aligned(tensor); + }; + return (width == 1024 || width == 2048 || width == 4096) && ggml_nrows(input) <= INT_MAX && + vector_aligned(input) && row_vector(mod->src[1]) && (!mod->src[2] || row_vector(mod->src[2])); + } + + static bool fusion_enabled() { + static const bool disabled = [] { + const char* setting = std::getenv("GGML_CUDA_DISABLE_FUSION"); + return setting && std::atoi(setting) != 0; + }(); + return !disabled; + } + + static int rms_match(ggml_backend_dev_t, const ggml_cgraph* graph, int first, void*) { + auto* g = const_cast(graph); + return fusion_enabled() && first + 1 < ggml_graph_n_nodes(g) && + rms_modulate_supports(ggml_graph_node(g, first), ggml_graph_node(g, first + 1)) + ? 2 + : 0; + } + + static void rms_optimize(ggml_backend_dev_t, ggml_cgraph* graph, void*) { + if (!fusion_enabled()) + return; + for (int i = 1; i < ggml_graph_n_nodes(graph); ++i) { + const auto* mod = ggml_graph_node(graph, i); + const auto* norm = mod->src[0]; + if (!norm || !rms_modulate_supports(norm, mod)) + continue; + for (int j = i - 1; j >= 0 && j >= i - 48; --j) { + if (ggml_graph_node(graph, j) == norm) { + if (j + 1 < i) + ggml_ext_graph_delay(graph, j, 1, i); + break; + } + } + } + } + + static ggml_status rms_prepare(ggml_backend_t, ggml_tensor* const* nodes, int, void**, size_t* bytes, void*) { + const auto* dst = nodes[1]; + *bytes = dst->data || dst->buffer || dst->view_src ? ggml_nbytes(dst) : 0; + return GGML_STATUS_SUCCESS; + } + + static ggml_status rms_execute(const ggml_ext_execution_context* e, ggml_tensor* const* nodes, int, void*, void*) { + ggml_ext_gpu_context context; + if (!cuda_context(e->backend, &context)) + return GGML_STATUS_FAILED; + const auto* norm = nodes[0]; + auto* mod = nodes[1]; + const auto* input = norm->src[0]; + const auto* scale = mod->src[1]; + const auto* shift = mod->src[2]; + const auto dst = reinterpret_cast(mod->data); + bool alias = false; + for (const auto* tensor : {input, scale, shift}) { + if (tensor) { + const auto src = reinterpret_cast(tensor->data); + alias |= dst < src + ggml_nbytes(tensor) && src < dst + ggml_nbytes(mod); + } + } + float eps; + std::memcpy(&eps, norm->op_params, sizeof(eps)); + const auto width = input->ne[0]; + auto kernel = width == 4096 ? rms_modulate_rows<4096> : width == 2048 ? rms_modulate_rows<2048> + : rms_modulate_rows<1024>; + auto stream = static_cast(context.stream); + auto* output = static_cast(alias ? ggml_backend_buffer_get_base(e->workspace) : mod->data); + kernel<<(ggml_nrows(input)), static_cast(width / 4), 0, stream>>>( + static_cast(input->data), static_cast(scale->data), + shift ? static_cast(shift->data) : nullptr, output, eps); + if (cuda_last_error() != cuda_success || (alias && cuda_copy_async(mod->data, output, ggml_nbytes(mod), stream) != cuda_success)) + return GGML_STATUS_FAILED; + return GGML_STATUS_SUCCESS; + } + static bool supports(ggml_backend_dev_t, const ggml_tensor* node, void*) { return sd_ggml_modulate_describe(node); } @@ -67,11 +221,29 @@ namespace SD_CUDA_NAMESPACE { p.scale_stride[d] = scale->nb[d] / sizeof(float); p.shift_stride[d] = shift ? shift->nb[d] / sizeof(float) : 0; } - auto stream = static_cast(context.stream); - auto* output = static_cast(alias ? ggml_backend_buffer_get_base(e->workspace) : dst->data); - const unsigned blocks = unsigned(std::min((p.count + 255) / 256, 65535)); - modulate<<>>(static_cast(x->data), static_cast(scale->data), - shift ? static_cast(shift->data) : nullptr, output, p); + auto stream = static_cast(context.stream); + auto* output = static_cast(alias ? ggml_backend_buffer_get_base(e->workspace) : dst->data); + const auto width = x->ne[0]; + const auto aligned_contiguous = [](const ggml_tensor* tensor) { + return ggml_is_contiguous(tensor) && reinterpret_cast(tensor->data) % 16 == 0; + }; + const auto is_broadcast_row = [&](const ggml_tensor* tensor) { + return tensor->ne[0] == width && ggml_nelements(tensor) == width && aligned_contiguous(tensor); + }; + if (width >= 4 && !(width & (width - 1)) && aligned_contiguous(x) && + is_broadcast_row(scale) && (!shift || is_broadcast_row(shift)) && + reinterpret_cast(output) % 16 == 0) { + const auto vectors = p.count / 4; + const unsigned blocks = unsigned(std::min((vectors + 255) / 256, 65535)); + auto kernel = shift ? modulate_rows : modulate_rows; + kernel<<>>(static_cast(x->data), static_cast(scale->data), + shift ? static_cast(shift->data) : nullptr, + reinterpret_cast(output), width / 4 - 1, vectors); + } else { + const unsigned blocks = unsigned(std::min((p.count + 255) / 256, 65535)); + modulate<<>>(static_cast(x->data), static_cast(scale->data), + shift ? static_cast(shift->data) : nullptr, output, p); + } if (cuda_last_error() != cuda_success || (alias && cuda_copy_async(dst->data, output, ggml_nbytes(dst), stream) != cuda_success)) { return GGML_STATUS_FAILED; } @@ -91,5 +263,16 @@ namespace SD_CUDA_NAMESPACE { desc.destroy = sd_modulate::destroy; desc.execute = sd_modulate::execute; GGML_ASSERT(ggml_ext_register_kernel_ex(device, &desc, GGML_EXT_KERNEL_CAPTURE_SAFE | GGML_EXT_KERNEL_REPLAY_REUSABLE)); + + desc.name = "sd.rms_modulate." SD_CUDA_NAME ".v1"; + desc.op = GGML_OP_RMS_NORM; + desc.custom_op = nullptr; + desc.priority = 200; + desc.supports = nullptr; + desc.match = sd_modulate::rms_match; + desc.optimize = sd_modulate::rms_optimize; + desc.prepare = sd_modulate::rms_prepare; + desc.execute = sd_modulate::rms_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/rope.cu b/src/core/cuda/rope.cu index c012c4042..5ae7c0d6a 100644 --- a/src/core/cuda/rope.cu +++ b/src/core/cuda/rope.cu @@ -12,8 +12,9 @@ namespace SD_CUDA_NAMESPACE { v = __fadd_rn(v, cuda_shuffle_xor(v, mask)); return v; } - template - static __global__ void rms_norm_mul_rope_apply_fused( + + template + static __global__ __launch_bounds__(HiddenDim ? HiddenDim / 4 : 128) void rms_norm_mul_rope_apply_fused( const float* x, const float* weight, const float* pe, @@ -27,56 +28,81 @@ namespace SD_CUDA_NAMESPACE { int rot_half, float eps, float output_scale) { - const int lane = threadIdx.x; - const int64_t row = int64_t(blockIdx.x) * blockDim.y + threadIdx.y; - if (row >= rows) { + 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; + if constexpr (HiddenDim > 0) { + constexpr int threads = HiddenDim / 4; + constexpr int warps = threads / 32; + __shared__ float warp_sums[warps]; + const int tid = threadIdx.y * 32 + lane; + const float4 v = reinterpret_cast(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; + } + __syncthreads(); + scale = rsqrtf(sd_warp_sum(lane < warps ? warp_sums[lane] : 0.f) / HiddenDim + eps); + first = int64_t(blockIdx.x) * head_count + threadIdx.y; + end = (int64_t(blockIdx.x) + 1) * head_count; + } else if (first >= rows) { return; } - const int64_t head = row % heads; - const int64_t token = (row / heads) % tokens; - const int64_t batch = row / (heads * tokens); - const float* x_row = x + head * nb1 + token * nb2 + batch * nb3; - float v[D / 32], sums[8] = {}; -#pragma unroll - for (int j = 0; j < D / 32; ++j) { - v[j] = x_row[j * 32 + lane]; - sums[j] = sd_warp_sum(__fmul_rn(v[j], v[j])); - } - // 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])), - __fadd_rn(__fadd_rn(sums[1], sums[5]), __fadd_rn(sums[3], sums[7]))); - const float scale = rsqrtf(sum / float(D) + eps); - T* out = dst + ((batch * heads + head) * tokens + token) * D; + for (int64_t row = first; row < end; row += HiddenDim > 0 ? HiddenDim / 128 : 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::value ? row : (batch * heads + head) * tokens + token; + T* out = dst + out_row * D; + float v[D / 32], sums[8] = {}; #pragma unroll - for (int j = 0; j < D / 32; ++j) { - const int col = j * 32 + lane; - const float value = affine ? __fmul_rn(__fmul_rn(scale, v[j]), weight[col]) : __fmul_rn(scale, v[j]); - float rotated = value; - if constexpr (interleaved) { - const float other = cuda_shuffle_xor(value, 1, 32); - if (col < 2 * rot_half) { - const float* m = pe + 4 * (token * rot_half + col / 2); - const float4 matrix = make_float4(m[0], m[1], m[2], m[3]); - rotated = lane % 2 == 0 - ? __fadd_rn(__fmul_rn(value, matrix.x), __fmul_rn(other, matrix.y)) - : __fadd_rn(__fmul_rn(other, matrix.z), __fmul_rn(value, matrix.w)); + for (int j = 0; j < D / 32; ++j) { + v[j] = x_row[j * 32 + lane]; + if constexpr (HiddenDim == 0) { + sums[j] = sd_warp_sum(__fmul_rn(v[j], v[j])); } - } else { - if (col < 2 * rot_half) { + } + if constexpr (HiddenDim == 0) { + // 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])), + __fadd_rn(__fadd_rn(sums[1], sums[5]), __fadd_rn(sums[3], sums[7]))); + scale = rsqrtf(sum / float(D) + eps); + } +#pragma unroll + for (int j = 0; j < D / 32; ++j) { + const int col = j * 32 + lane; + const float value = affine ? __fmul_rn(__fmul_rn(scale, v[j]), weight_row[col]) : __fmul_rn(scale, v[j]); + float rotated = value; + if constexpr (interleaved) { + const float other = cuda_shuffle_xor(value, 1, 32); + if (col < 2 * rot_half) { + const float* m = pe + 4 * (position * rot_half + col / 2); + const float4 matrix = make_float4(m[0], m[1], m[2], m[3]); + rotated = lane % 2 == 0 + ? __fadd_rn(__fmul_rn(value, matrix.x), __fmul_rn(other, matrix.y)) + : __fadd_rn(__fmul_rn(other, matrix.z), __fmul_rn(value, matrix.w)); + } + } else if (col < 2 * rot_half) { const int partner = col < rot_half ? col + rot_half : col - rot_half; - const float other = affine ? __fmul_rn(__fmul_rn(scale, x_row[partner]), weight[partner]) : __fmul_rn(scale, x_row[partner]); - const float* m = pe + 4 * (token * rot_half + col % rot_half); + const float other = affine ? __fmul_rn(__fmul_rn(scale, x_row[partner]), weight_row[partner]) : __fmul_rn(scale, x_row[partner]); + const float* m = pe + 4 * (position * rot_half + col % rot_half); const float4 matrix = make_float4(m[0], m[1], m[2], m[3]); rotated = col < rot_half ? __fsub_rn(__fmul_rn(value, matrix.x), __fmul_rn(other, matrix.z)) : __fadd_rn(__fmul_rn(other, matrix.z), __fmul_rn(value, matrix.x)); } - } - if constexpr (std::is_same::value) { - out[col] = __float2half_rn(__fmul_rn(rotated, output_scale)); - } else { - out[col] = rotated; + if constexpr (std::is_same::value) { + out[col] = __float2half_rn(__fmul_rn(rotated, output_scale)); + } else { + out[col] = rotated; + } } } } @@ -165,7 +191,7 @@ namespace SD_CUDA_NAMESPACE { bool rope_fusion_supports(const ggml_tensor* norm, const ggml_tensor* mul, const ggml_tensor* rope) { if (norm->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || !rope_is_node(rope) || - mul->src[0] != norm || rope->src[0] != mul || !rope_supports(nullptr, rope, nullptr)) + mul->src[0] != norm || rope->src[0] != mul || !rope_supports(nullptr, rope, nullptr) || rope->src[1]->ne[1] != 2) return false; const auto* x = norm->src[0]; const auto* weight = mul->src[1]; @@ -188,10 +214,112 @@ namespace SD_CUDA_NAMESPACE { return x && x->type == GGML_TYPE_F32 && x->ne[0] == 64 && x->nb[0] == sizeof(float) && x->nb[1] % sizeof(float) == 0 && x->nb[2] % sizeof(float) == 0 && x->nb[3] % sizeof(float) == 0 && - ggml_are_same_shape(x, norm) && ggml_is_contiguous(pe) && + ggml_are_same_shape(x, norm) && ggml_is_contiguous(pe) && pe->ne[1] == 2 && ggml_nrows(x) > 0 && (ggml_nrows(x) + 3) / 4 <= INT_MAX; } + static bool hidden_rope_aligned(const ggml_tensor* tensor) { + size_t offset = 0; + while (!tensor->data && tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + return (reinterpret_cast(tensor->data) + offset) % 16 == 0; + } + + bool hidden_rope_fusion_supports(const ggml_tensor* norm, const ggml_tensor* mul, const ggml_tensor* reshape, const ggml_tensor* rope) { + if (!norm || !mul || !reshape || !rope_is_node(rope) || norm->op != GGML_OP_RMS_NORM || + mul->op != GGML_OP_MUL || mul->src[0] != norm || reshape->op != GGML_OP_RESHAPE || + 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]; + 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 && + ggml_are_same_shape(x, norm) && ggml_are_same_shape(x, mul) && + reshape->ne[1] == 1 && 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) && + hidden_rope_aligned(x) && hidden_rope_aligned(weight) && + pe->view_offs % 16 == 0 && reinterpret_cast(pe->data) % 16 == 0; + } + + template + static void hidden_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, T* output, float scale) { + const auto* x = nodes[0]->src[0]; + const auto* weight = nodes[1]->src[1]; + const auto* pe = nodes[3]->src[1]; + const auto tokens = ggml_nrows(x); + constexpr int heads = HiddenDim / HeadDim; + auto kernel = rope_interleaved(nodes[3]) + ? rms_norm_mul_rope_apply_fused + : rms_norm_mul_rope_apply_fused; + kernel<<(tokens), dim3(32, HiddenDim / 128), 0, stream>>>( + static_cast(x->data), static_cast(weight->data), static_cast(pe->data), output, + heads, tokens, tokens * heads, HeadDim, HiddenDim, 0, HeadDim / 2, param_f32(nodes[0], 0), scale); + } + + template + 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) { + hidden_rope_launch<4096, 128>(stream, nodes, output, scale); + } else if (dim == 4096) { + hidden_rope_launch<4096, 64>(stream, nodes, output, scale); + } else if (head_dim == 128) { + hidden_rope_launch<2048, 128>(stream, nodes, output, scale); + } else { + hidden_rope_launch<2048, 64>(stream, nodes, output, scale); + } + return cuda_last_error(); + } + + CUDAError hidden_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, void* output, bool fp16, float scale) { + return fp16 ? hidden_rope_launch(stream, nodes, static_cast(output), scale) + : hidden_rope_launch(stream, nodes, static_cast(output), scale); + } + + bool hidden_rope_view_of(const ggml_tensor* view, const ggml_tensor* source) { + return view && source && view->src[0] == source && view->view_offs == 0 && + ggml_nelements(view) == ggml_nelements(source) && + (view->op == GGML_OP_RESHAPE || view->op == GGML_OP_VIEW || view->op == GGML_OP_PERMUTE); + } + + 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); + } + + static int hidden_rope_cast_count(ggml_cgraph* graph, int first) { + const auto* norm = ggml_graph_node(graph, first); + const auto* rope = ggml_graph_node(graph, first + 3); + const auto* prev = rope; + for (int i = first + 4; i < ggml_graph_n_nodes(graph) && i < first + 12; ++i) { + const auto* node = ggml_graph_node(graph, i); + if (node->src[0] != prev) + break; + if (node->op == GGML_OP_CPY && node->type == GGML_TYPE_F16 && ggml_is_contiguous(node) && + ggml_are_same_shape(node, prev)) { + if (hidden_rope_head_major(prev, norm, rope)) + return i - first + 1; + break; + } + if (!hidden_rope_view_of(node, prev)) + break; + prev = node; + } + return 4; + } + template static CUDAError rms_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, T* output, float scale) { const auto* x = nodes[0]->src[0]; @@ -234,6 +362,11 @@ namespace SD_CUDA_NAMESPACE { if (disabled) return 0; auto* g = const_cast(graph); + if (first + 3 < ggml_graph_n_nodes(g) && + hidden_rope_fusion_supports(ggml_graph_node(g, first), ggml_graph_node(g, first + 1), + ggml_graph_node(g, first + 2), ggml_graph_node(g, first + 3))) { + 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))) return 2; @@ -270,6 +403,19 @@ namespace SD_CUDA_NAMESPACE { for (int i = 2; i + 1 < total; ++i) { const auto* mul = ggml_graph_node(graph, i); const auto* rope = ggml_graph_node(graph, i + 1); + if (mul->op == GGML_OP_RESHAPE && mul->src[0] && + hidden_rope_fusion_supports(mul->src[0]->src[0], mul->src[0], mul, rope)) { + const auto* affine = mul->src[0]; + for (int j = i - 1; j > 0 && j >= i - 64; --j) { + if (ggml_graph_node(graph, j) == affine && ggml_graph_node(graph, j - 1) == affine->src[0]) { + if (j + 1 < i) { + ggml_ext_graph_delay(graph, j - 1, 2, i); + } + break; + } + } + continue; + } if (rope_non_affine_fusion_supports(rope->src[0], rope)) { for (int j = i; j >= 0 && j >= i - 64; --j) { if (ggml_graph_node(graph, j) == rope->src[0]) { @@ -322,14 +468,18 @@ namespace SD_CUDA_NAMESPACE { ggml_ext_gpu_context context; if (!cuda_context(execution->backend, &context)) return GGML_STATUS_FAILED; - auto stream = static_cast(context.stream); - const auto* rope = nodes[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 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; CUDAError error; - if (count == 2) { + 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>>>( diff --git a/src/core/cuda/rope.h b/src/core/cuda/rope.h index 0d45f689e..bba34b858 100644 --- a/src/core/cuda/rope.h +++ b/src/core/cuda/rope.h @@ -6,6 +6,10 @@ namespace SD_CUDA_NAMESPACE { bool rope_fusion_supports(const ggml_tensor* norm, const ggml_tensor* mul, const ggml_tensor* rope); CUDAError rms_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, void* output, bool fp16, float scale); + bool hidden_rope_fusion_supports(const ggml_tensor* norm, const ggml_tensor* mul, const ggml_tensor* reshape, const ggml_tensor* rope); + bool hidden_rope_view_of(const ggml_tensor* view, const ggml_tensor* source); + bool hidden_rope_head_major(const ggml_tensor* view, const ggml_tensor* norm, const ggml_tensor* rope); + CUDAError hidden_rope_launch(CUDAStream stream, ggml_tensor* const* nodes, void* output, bool fp16, float scale); } #endif diff --git a/src/core/ggml_extend_backend.cpp b/src/core/ggml_extend_backend.cpp index e39909257..dbf9044ff 100644 --- a/src/core/ggml_extend_backend.cpp +++ b/src/core/ggml_extend_backend.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -357,6 +358,16 @@ bool sd_backend_is(ggml_backend_t backend, const std::string& name) { return lower_copy(dev_name).find(lower_copy(name)) != std::string::npos; } +bool sd_backend_is_cuda_family(ggml_backend_t backend) { + const auto dev = backend != nullptr ? ggml_backend_get_device(backend) : nullptr; + const auto reg = dev != nullptr ? ggml_backend_dev_backend_reg(dev) : nullptr; + if (reg == nullptr) { + return false; + } + const char* name = ggml_backend_reg_name(reg); + return std::strcmp(name, "CUDA") == 0 || std::strcmp(name, "ROCm") == 0 || std::strcmp(name, "MUSA") == 0; +} + static std::string get_default_backend_name() { ggml_backend_load_all_once(); // should pick the same backend preference as ggml_backend_init_best diff --git a/src/core/ggml_extend_backend.h b/src/core/ggml_extend_backend.h index 181c0d10c..d16ef51ab 100644 --- a/src/core/ggml_extend_backend.h +++ b/src/core/ggml_extend_backend.h @@ -92,6 +92,7 @@ class SDBackendManager { bool sd_backend_is(ggml_backend_t backend, const std::string& name); bool sd_backend_is_cpu(ggml_backend_t backend); +bool sd_backend_is_cuda_family(ggml_backend_t backend); bool sd_backend_supports_cuda_mma(ggml_backend_t backend); bool sd_backend_supports_hip_mma(ggml_backend_t backend); bool sd_backend_supports_conv_implicit_gemm(ggml_backend_t backend, bool conv3d); diff --git a/src/core/segment_graph_bindings.cpp b/src/core/segment_graph_bindings.cpp index ba72116f3..72a773abd 100644 --- a/src/core/segment_graph_bindings.cpp +++ b/src/core/segment_graph_bindings.cpp @@ -15,12 +15,6 @@ namespace sd { : tensor_cache_(tensor_cache), graph_(graph) { GGML_ASSERT(graph_ != nullptr); - for (int i = 0; i < ggml_graph_n_nodes(graph_); ++i) { - ggml_tensor* tensor = ggml_graph_node(graph_, i); - Topology topology{tensor->op, {}, tensor->view_src, tensor->flags}; - std::copy(std::begin(tensor->src), std::end(tensor->src), topology.sources.begin()); - topology_[tensor] = topology; - } for (const auto& segment : plan.segments) { for (const auto& input : segment.input_refs) { if (input.type != ggml_graph_cut::Segment::INPUT_EXTERNAL) { @@ -35,8 +29,15 @@ namespace sd { } } + void SegmentGraphBindings::remember(ggml_tensor* tensor) { + Topology topology{tensor, tensor->op, {}, tensor->view_src, tensor->flags}; + std::copy(std::begin(tensor->src), std::end(tensor->src), topology.sources.begin()); + topology_.push_back(topology); + } + void SegmentGraphBindings::reset(const ggml_graph_cut::Segment& segment) { restore(); + topology_.reserve(segment.internal_node_indices.size() + segment.input_refs.size() + 2 * segment.output_node_indices.size()); for (const auto& input : segment.input_refs) { ggml_tensor* tensor = ggml_graph_cut::input_tensor(graph_, input); if (tensor == nullptr) { @@ -44,6 +45,7 @@ namespace sd { } switch (input.type) { case ggml_graph_cut::Segment::INPUT_PREVIOUS_CUT: + remember(tensor); tensor->buffer = nullptr; tensor->data = nullptr; tensor->extra = nullptr; @@ -71,19 +73,32 @@ namespace sd { if (node == nullptr) { continue; } + remember(node); node->buffer = nullptr; node->data = nullptr; node->extra = nullptr; } + // The segment builder marks outputs and the storage backing output views. + for (int node_index : segment.output_node_indices) { + auto* output = ggml_graph_node(graph_, node_index); + if (output == nullptr) { + continue; + } + remember(output); + if (output->view_src != nullptr) { + remember(output->view_src); + } + } } void SegmentGraphBindings::restore() { for (const auto& entry : topology_) { - entry.first->op = entry.second.op; - entry.first->view_src = entry.second.view_source; - entry.first->flags = entry.second.flags; - std::copy(entry.second.sources.begin(), entry.second.sources.end(), std::begin(entry.first->src)); + entry.tensor->op = entry.op; + entry.tensor->view_src = entry.view_source; + entry.tensor->flags = entry.flags; + std::copy(entry.sources.begin(), entry.sources.end(), std::begin(entry.tensor->src)); } + topology_.clear(); } bool SegmentGraphBindings::bind_cached_inputs( @@ -106,14 +121,14 @@ namespace sd { return false; } if (input_tensor->view_src != nullptr) { - cached_view_sources[topology_.at(input_tensor).view_source] = cached_tensor; - input_tensor->view_src = cached_tensor; - input_tensor->buffer = nullptr; - input_tensor->data = cached_tensor->data == nullptr - ? nullptr - : static_cast(static_cast(cached_tensor->data) + - input_tensor->view_offs); - input_tensor->extra = cached_tensor->extra; + cached_view_sources[input_tensor->view_src] = cached_tensor; + input_tensor->view_src = cached_tensor; + input_tensor->buffer = nullptr; + input_tensor->data = cached_tensor->data == nullptr + ? nullptr + : static_cast(static_cast(cached_tensor->data) + + input_tensor->view_offs); + input_tensor->extra = cached_tensor->extra; } else { input_tensor->buffer = cached_tensor->buffer; input_tensor->data = cached_tensor->data; @@ -127,7 +142,7 @@ namespace sd { // ggml flattens view chains, so descendants also need the cached root. for (int node_index : segment.internal_node_indices) { ggml_tensor* node = ggml_graph_node(graph_, node_index); - auto cached_source = cached_view_sources.find(topology_.at(node).view_source); + auto cached_source = cached_view_sources.find(node->view_src); if (cached_source != cached_view_sources.end()) { node->view_src = cached_source->second; } diff --git a/src/core/segment_graph_bindings.h b/src/core/segment_graph_bindings.h index 08aba156b..6e3e4129c 100644 --- a/src/core/segment_graph_bindings.h +++ b/src/core/segment_graph_bindings.h @@ -3,6 +3,7 @@ #include #include +#include #include "ggml.h" struct ggml_backend_buffer; @@ -40,12 +41,15 @@ namespace sd { ggml_cgraph* graph_ = nullptr; std::unordered_map external_bindings_; struct Topology { + ggml_tensor* tensor; ggml_op op; std::array sources; ggml_tensor* view_source; int flags; }; - std::unordered_map topology_; + std::vector topology_; + + void remember(ggml_tensor* tensor); }; } diff --git a/src/core/vulkan/int8.cpp b/src/core/vulkan/int8.cpp index e48bdc940..2b60df8eb 100644 --- a/src/core/vulkan/int8.cpp +++ b/src/core/vulkan/int8.cpp @@ -670,17 +670,17 @@ namespace sd_vulkan_i8 { if (op.codebook && alias) dst.offset = GGML_PAD(size_t(chunk_cols) * k, d.info.buffer_alignment); - const auto destination = concat ? range(dst, ggml_nbytes(concat->src[0]), ggml_nbytes(tail)) : dst; - const uint32_t output_stride = uint32_t(tail->ne[0]); + const auto destination = concat ? range(dst, ggml_nbytes(concat->src[0]), ggml_nbytes(tail)) : dst; + const uint32_t output_stride = uint32_t(tail->ne[0]); ggml_ext_vulkan_binding bindings[] = {{op.weight}, {op.input, nullptr, 0, scale_offset}, {op.weight_scale}, {op.input, nullptr, scale_offset, size_t(rows) * 4}, {op.bias ? op.bias : op.weight_scale}, destination, {up_mat ? up.weight : gate}, {up_mat ? up.weight_scale : residual}}; - auto multiply_chunk = [&](uint32_t first, uint32_t cols) { + auto multiply_chunk = [&](uint32_t first, uint32_t cols) { const uint32_t output_cols = glu ? uint32_t(glu->ne[0]) : cols; - auto dispatch = [&](ggml_ext_vulkan_pipeline pipeline, uint32_t tile_cols, uint32_t tile_rows, - std::initializer_list constants, uint32_t row_offset, uint32_t dispatch_rows) { + auto dispatch = [&](ggml_ext_vulkan_pipeline pipeline, uint32_t tile_cols, uint32_t tile_rows, + std::initializer_list constants, uint32_t row_offset, uint32_t dispatch_rows) { if (!dispatch_rows) return GGML_STATUS_SUCCESS; - MatParameters pc = {cols * (up_mat ? 2u : 1u), rows, k, op.bias ? 1u : 0u, row_offset, output_scale, - group_columns(output_cols, k, tile_cols, glu != nullptr), output_stride, first}; + MatParameters pc = {cols * (up_mat ? 2u : 1u), rows, k, op.bias ? 1u : 0u, row_offset, output_scale, + group_columns(output_cols, k, tile_cols, glu != nullptr), output_stride, first}; pipeline.constants = constants.begin(); pipeline.constant_count = uint32_t(constants.size()); const uint32_t groups[] = {(output_cols + tile_cols - 1) / tile_cols, (dispatch_rows + tile_rows - 1) / tile_rows, 1}; @@ -688,15 +688,15 @@ namespace sd_vulkan_i8 { }; ggml_status status = GGML_STATUS_SUCCESS; if (d.cm2) { - const bool large_k = k % 4096 == 0 || (rows >= cols && k >= cols); + const bool large_k = k % 4096 == 0 || (rows >= cols && k >= cols); // The aligned store uses a row stride rounded down to 128 columns. const bool aligned_output = cols % 128 == 0 && output_stride % 128 == 0; - const uint32_t full_rows = (glu || aligned_output) ? rows / 128 * 128 : 0; - auto pipeline = residual ? SD_VK_PIPELINE(mul_mat_i8_residual_cm2, 8, MatParameters) : up_mat ? SD_VK_PIPELINE(mul_mat_i8_swiglu_split_cm2, 8, MatParameters) - : SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm2, 6, MatParameters); - const uint32_t tile_cols = glu ? 64 : 128; - const uint32_t full_k = (glu || large_k) && k % 128 == 0 ? 128u : 64u; - status = dispatch(pipeline, tile_cols, 128, {128, 1, glu ? 1u : 0u, tile_cols, full_k}, 0, full_rows); + const uint32_t full_rows = (glu || aligned_output) ? rows / 128 * 128 : 0; + auto pipeline = residual ? SD_VK_PIPELINE(mul_mat_i8_residual_cm2, 8, MatParameters) : up_mat ? SD_VK_PIPELINE(mul_mat_i8_swiglu_split_cm2, 8, MatParameters) + : SD_VK_PIPELINE(mul_mat_i8_tensorwise_cm2, 6, MatParameters); + const uint32_t tile_cols = glu ? 64 : 128; + const uint32_t full_k = (glu || large_k) && k % 128 == 0 ? 128u : 64u; + status = dispatch(pipeline, tile_cols, 128, {128, 1, glu ? 1u : 0u, tile_cols, full_k}, 0, full_rows); if (status == GGML_STATUS_SUCCESS) { const bool small = d.cm2_small && (glu || aligned_output) && rows - full_rows <= 32; const uint32_t tail_cols = small || glu ? 64 : 128, tail_rows = small ? 32 : glu ? 128 @@ -725,9 +725,9 @@ namespace sd_vulkan_i8 { const uint32_t cols = std::min(chunk_cols, n - first); if (op.codebook) { const size_t packed_row = op.weight->nb[1], scale_row = op.relative_scale->nb[1]; - bindings[0] = {nullptr, e->workspace, 0, size_t(cols) * k}; - bindings[2] = range({op.weight_scale}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float)); - bindings[4] = op.bias ? range({op.bias}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float)) : bindings[2]; + bindings[0] = {nullptr, e->workspace, 0, size_t(cols) * k}; + bindings[2] = range({op.weight_scale}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float)); + bindings[4] = op.bias ? range({op.bias}, size_t(first) * sizeof(float), size_t(cols) * sizeof(float)) : bindings[2]; const ggml_ext_vulkan_binding decode_inputs[] = { range({op.weight}, first * packed_row, cols * packed_row), {op.codebook}, @@ -735,9 +735,9 @@ namespace sd_vulkan_i8 { bindings[0], }; const uint32_t groups_count = cols * (k / 16); - const uint32_t groups[] = {std::min((groups_count + 127) / 128, d.info.max_group_count[0]), 1, 1}; - const auto pipeline = SD_VK_PIPELINE(decode_w4a8, 4, uint32_t); - const auto status = d.api->dispatch(e->backend, &pipeline, decode_inputs, &groups_count, groups); + const uint32_t groups[] = {std::min((groups_count + 127) / 128, d.info.max_group_count[0]), 1, 1}; + const auto pipeline = SD_VK_PIPELINE(decode_w4a8, 4, uint32_t); + const auto status = d.api->dispatch(e->backend, &pipeline, decode_inputs, &groups_count, groups); if (status != GGML_STATUS_SUCCESS) return status; } diff --git a/src/model/common/block.hpp b/src/model/common/block.hpp index d8e193a91..daa6bfa90 100644 --- a/src/model/common/block.hpp +++ b/src/model/common/block.hpp @@ -219,9 +219,9 @@ class GELU : public UnaryBlock { // return: [ne3, ne2, ne1, dim_out] auto proj = std::dynamic_pointer_cast(blocks["proj"]); - x = proj->forward(ctx, x); - x = ggml_ext_gelu(ctx, x, true); - return x; + // Let the allocator reuse the projection buffer when GELU runs separately. + // An explicit in-place write prevents folding GELU into ConvRot quantization. + return ggml_ext_gelu(ctx, proj->forward(ctx, x)); } }; diff --git a/src/model/common/ltx.hpp b/src/model/common/ltx.hpp index c66a1e7cf..b28a013af 100644 --- a/src/model/common/ltx.hpp +++ b/src/model/common/ltx.hpp @@ -178,13 +178,13 @@ namespace LTXV { bool rope_interleaved) { auto ctx = runner_ctx->ggml_ctx; GGML_ASSERT(x->ne[0] == heads * dim_head); - auto x4 = ggml_reshape_4d(ctx, x, dim_head, heads, x->ne[1], x->ne[2]); if (pe != nullptr && pe->ne[3] == x->ne[1] * heads) { - auto x_flat = ggml_reshape_4d(ctx, x4, dim_head, 1, x->ne[1] * heads, x->ne[2]); + auto x_flat = ggml_reshape_4d(ctx, x, dim_head, 1, x->ne[1] * heads, x->ne[2]); auto out_flat = Rope::apply_rope(runner_ctx, x_flat, pe, rope_interleaved); auto out4 = ggml_reshape_4d(ctx, out_flat, dim_head, heads, x->ne[1], x->ne[2]); return ggml_reshape_3d(ctx, out4, heads * dim_head, x->ne[1], x->ne[2]); } + auto x4 = ggml_reshape_4d(ctx, x, dim_head, heads, x->ne[1], x->ne[2]); return Rope::apply_rope(runner_ctx, x4, pe, rope_interleaved); } @@ -266,14 +266,18 @@ namespace LTXV { k = apply_hidden_rope(ctx, k, k_pe, heads, dim_head, rope_interleaved); } - auto out = ggml_ext_attention_ext(ctx, - q, - k, - v, - heads, - mask, - false, - ctx->flash_attn_enabled); + const bool strided_qk = ctx->flash_attn_enabled && !ctx->sage_attn_enabled && + q->ne[2] == 1 && k->ne[2] == 1 && v->ne[2] == 1 && + sd_backend_is_cuda_family(ctx->backend); + if (strided_qk) { + auto split_heads = [&](ggml_tensor* x) { + return ggml_reshape_4d(ctx->ggml_ctx, x, dim_head, heads, x->ne[1], 1); + }; + q = ggml_permute(ctx->ggml_ctx, split_heads(q), 0, 2, 1, 3); + k = ggml_permute(ctx->ggml_ctx, split_heads(k), 0, 2, 1, 3); + v = split_heads(v); + } + auto out = ggml_ext_attention_ext(ctx, q, k, v, heads, mask, strided_qk, ctx->flash_attn_enabled); if (blocks.count("to_gate_logits") > 0) { auto to_gate_logits = std::dynamic_pointer_cast(blocks["to_gate_logits"]); @@ -283,7 +287,6 @@ namespace LTXV { gates = ggml_reshape_4d(ctx->ggml_ctx, gates, 1, heads, gate_logits->ne[1], gate_logits->ne[2]); auto out4 = ggml_reshape_4d(ctx->ggml_ctx, out, dim_head, heads, out->ne[1], out->ne[2]); - gates = ggml_repeat(ctx->ggml_ctx, gates, out4); out4 = ggml_mul(ctx->ggml_ctx, out4, gates); out = ggml_reshape_3d(ctx->ggml_ctx, out4, heads * dim_head, out4->ne[2], out4->ne[3]); } diff --git a/src/model/diffusion/ltxv.hpp b/src/model/diffusion/ltxv.hpp index f06f9d0a2..cd6a89667 100644 --- a/src/model/diffusion/ltxv.hpp +++ b/src/model/diffusion/ltxv.hpp @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include "core/pe_cache.h" @@ -968,8 +970,53 @@ namespace LTXV { ->forward(ctx, ggml_ext_scale(ctx, av_ca_audio_timestep, av_ca_factor)) .first; - sd::ggml_graph_cut::mark_graph_cut(vx, "ltxav.prelude", "vx"); - sd::ggml_graph_cut::mark_graph_cut(ax, "ltxav.prelude", "ax"); + auto mark_prelude = [](ggml_tensor* tensor, const char* name) { + sd::ggml_graph_cut::mark_graph_cut(tensor, "ltxav.prelude", name); + }; + mark_prelude(vx, "vx"); + mark_prelude(ax, "ax"); + + // Otherwise each offloaded transformer segment uploads the same prompt inputs. + const auto device = ctx->backend ? ggml_backend_get_device(ctx->backend) : nullptr; + if (device && ggml_backend_dev_type(device) != GGML_BACKEND_DEVICE_TYPE_CPU) { + v_context = ggml_cont(ctx->ggml_ctx, v_context); + mark_prelude(v_context, "v_context"); + mark_prelude(a_context, "a_context"); + } + + // Per-token timestep projections can be too large to keep live across + // the whole graph under the offload budget. + auto retain_timestep = [&](ggml_tensor* value, const char* name) { + if (value != nullptr && value->ne[1] == 1) { + mark_prelude(value, name); + } + }; + retain_timestep(v_timestep_mod, "v_timestep_mod"); + retain_timestep(a_timestep_mod, "a_timestep_mod"); + retain_timestep(v_embedded_time, "v_embedded_time"); + retain_timestep(a_embedded_time, "a_embedded_time"); + retain_timestep(v_prompt_timestep_mod, "v_prompt_timestep_mod"); + retain_timestep(a_prompt_timestep_mod, "a_prompt_timestep_mod"); + retain_timestep(av_ca_video_scale_shift_timestep, "v_cross_scale_shift"); + retain_timestep(av_ca_a2v_gate_noise_timestep, "v_cross_gate"); + retain_timestep(av_ca_audio_scale_shift_timestep, "a_cross_scale_shift"); + retain_timestep(av_ca_v2a_gate_noise_timestep, "a_cross_gate"); + + // Graph cuts retain computed tensors. Materialize the shared RoPE inputs once + // so later segments can consume them without repeatedly uploading them. + auto retain_rope = [&](ggml_tensor* pe, const char* name) { + if (pe != nullptr && pe->buffer == nullptr) { + if (pe->op == GGML_OP_NONE) { + pe = ggml_dup(ctx->ggml_ctx, pe); + } + mark_prelude(pe, name); + } + return pe; + }; + v_pe = retain_rope(v_pe, "v_pe"); + a_pe = retain_rope(a_pe, "a_pe"); + v_cross_pe = retain_rope(v_cross_pe, "v_cross_pe"); + a_cross_pe = retain_rope(a_cross_pe, "a_cross_pe"); for (int i = 0; i < config.num_layers; i++) { auto block = std::dynamic_pointer_cast(blocks["transformer_blocks." + std::to_string(i)]); @@ -1017,6 +1064,8 @@ namespace LTXV { struct LTXAVRunner : public DiffusionModelRunner { sd::PECache pe_cache_; + std::optional device_pe_key_; + bool device_pe_cache_enabled_ = true; LTXAVConfig config; LTXAVModelBlock model; sd::Tensor vx_input_cache; @@ -1100,6 +1149,22 @@ namespace LTXV { return ggml_concat(ctx, vx, ax, 3); } + ggml_tensor* make_video_rope_input(const sd::PECacheKey& key, + const std::function()>& build, + bool cache_on_device) { + if (cache_on_device) { + if (auto* cached = get_cache_tensor_by_name(key.name())) { + return cached; + } + } + auto* input = make_input(pe_cache_.get_or_create(key, build)); + if (cache_on_device) { + input = ggml_dup(compute_ctx, input); + cache(key.name(), input); + } + return input; + } + ggml_cgraph* build_graph(const sd::Tensor& x_tensor, const sd::Tensor& timesteps_tensor, const sd::Tensor& context_tensor = {}, @@ -1145,31 +1210,44 @@ namespace LTXV { video_pe_key.add(config.num_attention_heads).add(config.attention_head_dim).add(config.positional_embedding_max_pos); video_pe_key.add(std::get<0>(config.vae_scale_factors)).add(std::get<1>(config.vae_scale_factors)); video_pe_key.add(std::get<2>(config.vae_scale_factors)); - auto video_pe = make_input(pe_cache_.get_or_create(video_pe_key, [&]() { - std::vector video_pe_vec; - if (has_video_positions) { - GGML_ASSERT(video_positions_tensor.shape()[2] == video_token_count); - video_pe_vec = build_video_rope_matrix_from_positions(video_positions_tensor, - static_cast(config.hidden_size), - static_cast(config.num_attention_heads), - config.positional_embedding_theta, - config.positional_embedding_max_pos, - config.use_middle_indices_grid); - } else { - video_pe_vec = build_video_rope_matrix(vx->ne[0], - vx->ne[1], - vx->ne[2], - static_cast(config.hidden_size), - static_cast(config.num_attention_heads), - video_frame_rate, - config.positional_embedding_theta, - config.positional_embedding_max_pos, - config.vae_scale_factors, - config.causal_temporal_positioning, - config.use_middle_indices_grid); - } - return sd::Tensor({2, 2, config.attention_head_dim / 2, video_token_count * config.num_attention_heads}, std::move(video_pe_vec)); - })); + constexpr int64_t minimum_cached_video_elements = 4 * 1024 * 1024; + const bool cache_video_rope = device_pe_cache_enabled_ && sd_backend_is_cuda_family(runtime_backend) && + video_token_count * config.hidden_size >= minimum_cached_video_elements; + // Both video RoPE inputs depend on the same geometry, frame rate and positions. + if (device_pe_key_ && !(*device_pe_key_ == video_pe_key)) { + free_cache_ctx_and_buffer(); + device_pe_key_.reset(); + } + if (cache_video_rope && !device_pe_key_) { + device_pe_key_ = video_pe_key; + } + auto video_pe = make_video_rope_input( + video_pe_key, [&]() { + std::vector video_pe_vec; + if (has_video_positions) { + GGML_ASSERT(video_positions_tensor.shape()[2] == video_token_count); + video_pe_vec = build_video_rope_matrix_from_positions(video_positions_tensor, + static_cast(config.hidden_size), + static_cast(config.num_attention_heads), + config.positional_embedding_theta, + config.positional_embedding_max_pos, + config.use_middle_indices_grid); + } else { + video_pe_vec = build_video_rope_matrix(vx->ne[0], + vx->ne[1], + vx->ne[2], + static_cast(config.hidden_size), + static_cast(config.num_attention_heads), + video_frame_rate, + config.positional_embedding_theta, + config.positional_embedding_max_pos, + config.vae_scale_factors, + config.causal_temporal_positioning, + config.use_middle_indices_grid); + } + return sd::Tensor({2, 2, config.attention_head_dim / 2, video_token_count * config.num_attention_heads}, std::move(video_pe_vec)); + }, + cache_video_rope); ggml_tensor* audio_pe = nullptr; ggml_tensor* video_cross_pe = nullptr; @@ -1196,30 +1274,32 @@ namespace LTXV { video_cross_pe_key.add(config.use_middle_indices_grid).add(config.audio_cross_attention_dim); video_cross_pe_key.add(config.audio_num_attention_heads).add(config.audio_attention_head_dim); video_cross_pe_key.add(temporal_max_pos).add(std::get<0>(config.vae_scale_factors)); - video_cross_pe = make_input(pe_cache_.get_or_create(video_cross_pe_key, [&]() { - std::vector video_cross_pe_vec; - if (has_video_positions) { - video_cross_pe_vec = build_video_temporal_rope_matrix_from_positions(video_positions_tensor, - static_cast(config.audio_cross_attention_dim), - static_cast(config.audio_num_attention_heads), - config.positional_embedding_theta, - temporal_max_pos, - true); - } else { - video_cross_pe_vec = build_video_temporal_rope_matrix(vx->ne[0], - vx->ne[1], - vx->ne[2], - static_cast(config.audio_cross_attention_dim), - static_cast(config.audio_num_attention_heads), - video_frame_rate, - config.positional_embedding_theta, - temporal_max_pos, - std::get<0>(config.vae_scale_factors), - config.causal_temporal_positioning, - true); - } - return sd::Tensor({2, 2, config.audio_attention_head_dim / 2, video_token_count * config.audio_num_attention_heads}, std::move(video_cross_pe_vec)); - })); + video_cross_pe = make_video_rope_input( + video_cross_pe_key, [&]() { + std::vector video_cross_pe_vec; + if (has_video_positions) { + video_cross_pe_vec = build_video_temporal_rope_matrix_from_positions(video_positions_tensor, + static_cast(config.audio_cross_attention_dim), + static_cast(config.audio_num_attention_heads), + config.positional_embedding_theta, + temporal_max_pos, + true); + } else { + video_cross_pe_vec = build_video_temporal_rope_matrix(vx->ne[0], + vx->ne[1], + vx->ne[2], + static_cast(config.audio_cross_attention_dim), + static_cast(config.audio_num_attention_heads), + video_frame_rate, + config.positional_embedding_theta, + temporal_max_pos, + std::get<0>(config.vae_scale_factors), + config.causal_temporal_positioning, + true); + } + return sd::Tensor({2, 2, config.audio_attention_head_dim / 2, video_token_count * config.audio_num_attention_heads}, std::move(video_cross_pe_vec)); + }, + cache_video_rope); sd::PECacheKey audio_cross_pe_key("ltxav_audio_cross_pe"); audio_cross_pe_key.add(ax->ne[1]).add(config.audio_cross_attention_dim).add(config.audio_num_attention_heads); @@ -1267,6 +1347,12 @@ namespace LTXV { return build_graph(x, timesteps, context, audio_x, audio_timesteps, audio_length, frame_rate, video_positions, audio_context); }; auto out = restore_trailing_singleton_dims(GGMLRunner::compute(get_graph, n_threads, false), x.dim()); + if (out.empty() && device_pe_key_ && last_compute_status() == GGML_STATUS_ALLOC_FAILED) { + free_cache_ctx_and_buffer(); + device_pe_key_.reset(); + device_pe_cache_enabled_ = false; + out = restore_trailing_singleton_dims(GGMLRunner::compute(get_graph, n_threads, false), x.dim()); + } return out; }