From e2d1bd63eb17330b836aed8cdb3a56e1d96adb9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Fri, 18 Sep 2026 22:55:52 +0200 Subject: [PATCH 01/13] Vulkan: fuse Q@K^T and softmax on the SDPA decode path At sequence length 1 the attn-weights matmul and the softmax that follows it are two dispatches with a round trip through attn_weights in between. Fuse them: one work group per (s, q_h) walks the whole context row, keeps it in shared memory, and writes softmax-normalized weights directly. The sequence length is only known once sizes are current, because a dynamic-shape export reports the max bound at graph build time. Adding or dropping a node cannot be deferred to resize time the way a shader pick can, so all three nodes are built and each global work group picker collapses to zero for the path it is not serving; DispatchNode::encode skips a zero dispatch. The fused shader holds the attn_weights row in shared memory, so it is only selected while that row fits (see kFusedSoftmaxMaxContextTexels). Qwen3-0.6B on Adreno 840, same binary, arms interleaved and selected by an env toggle: 1668 -> 1640 dispatches per token, one per layer for 28 layers, and decode 90.9 -> 97.1 tok/s at a 16-token prompt. At a 400-token prompt the two are within noise of each other (69.4 vs 67.5), which is what the loss of context-axis parallelism predicts. --- ...dpa_compute_attn_weights_coop_softmax.glsl | 241 ++++++++++++++++++ ...dpa_compute_attn_weights_coop_softmax.yaml | 25 ++ .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 125 +++++++++ 3 files changed, 391 insertions(+) create mode 100644 backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl create mode 100644 backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl new file mode 100644 index 00000000000..f9b89b2876f --- /dev/null +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl @@ -0,0 +1,241 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +#version 450 core + +#define PRECISION ${PRECISION} +#define VEC4_T ${texel_load_type(DTYPE, IO_STORAGE)} +#define T ${texel_load_component_type(DTYPE, IO_STORAGE)} + +$if IO_STORAGE == "buffer": + #define OUTPUT_BUFFER + #define INPUT_BUFFER + #define ATTN_WEIGHTS_BUFFER +$if K_CACHE_STORAGE == "buffer": + #define K_CACHE_BUFFER + +#define Q_LAYOUT DHSB +#define K_LAYOUT DHSB + +#define TILE_K4 ${TILE_K4} +#define TILE_N4 ${TILE_N4} + +#define TILE_M 1 +#define TILE_K ${TILE_K4 * 4} +#define TILE_N ${TILE_N4 * 4} + +#define NUM_WORKERS_PER_OUT 64 + +// Cap on the attn_weights row held in shared memory, in texels. The host only +// selects this shader when div_up_4(max_context_len) fits within this bound +// (see use_fused_qk_softmax() in SDPA.cpp), so the indexing below is in range. +#define MAX_CONTEXT_TEXEL_LEN 1024 + +${define_required_extensions(IO_STORAGE, DTYPE)} + +layout(std430) buffer; + +#include "common.glslh" + +${layout_declare_tensor(B, "w", "t_attn_weights", DTYPE, IO_STORAGE, is_scalar_array=False)} +${layout_declare_tensor(B, "r", "t_q", DTYPE, IO_STORAGE, is_scalar_array=False)} +${layout_declare_tensor(B, "r", "t_k", DTYPE, K_CACHE_STORAGE, is_scalar_array=False)} + +${layout_declare_ubo(B, "ivec4", "q_sizes")} +${layout_declare_ubo(B, "ivec4", "k_sizes")} +${layout_declare_ubo(B, "int", "input_pos")} + +layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; + +${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} + +#include "sdpa_fp_q_projected_tile_load.glslh" +#include "sdpa_fp_k_cache_tile_load.glslh" +#include "linear_fp_output_tile_fp_compute.glslh" +#include "sdpa_fp_attn_weight_tile_store.glslh" + +// The attn_weights row after scale and causal masking, plus per-worker scratch +// for the row-max and exp-sum tree reductions. +shared T row_attn_w_x[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_y[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_z[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_w[MAX_CONTEXT_TEXEL_LEN]; +shared T shared_max[NUM_WORKERS_PER_OUT]; +shared T shared_sum[NUM_WORKERS_PER_OUT]; + +/* + * Fused Q @ K^T and softmax for the decode path (sequence length 1). + * + * The coop sibling of this shader dispatches one work group per (c4, q_h) and + * tree-reduces across head_dim, each group emitting one texel of attn_weights; + * a separate shader then performs the softmax across the context dim in a + * three-pass max/subtract/normalize algorithm. + * + * This variant instead dispatches one work group per (s, q_h), whose 64 workers + * cooperatively walk every c4 of that row. The row stays in shared memory, so + * the group can reduce it to row_max and exp_sum and write normalized softmax + * values straight to t_attn_weights. That removes one dispatch per layer along + * with the round trip through attn_weights between the matmul and the softmax. + * + * The trade-off is the loss of parallelism along the context axis (from one + * work group per context tile down to one), which is why the host restricts + * this shader to sequence length 1, where per-dispatch overhead dominates. + */ +void main() { + const int worker_id = int(gl_LocalInvocationID.x); + + // idx along the output seq_len dim; this shader is only dispatched for S == 1 + const int s = int(gl_GlobalInvocationID.y); + // idx along output num_q_heads dim + const int q_h = int(gl_GlobalInvocationID.z); + + // head dimension + const int D = q_sizes.x; + // texel size of head_dim, over which the dot product is accumulated + const int D4 = div_up_4(D); + // number of Q heads + const int Q_H = q_sizes.y; + // sequence length + const int S = q_sizes.z; + const int S_aligned = align_up_4(S); + + // number of K/V heads + const int KV_H = k_sizes.y; + // Max context length + const int C = k_sizes.z; + const int C4 = div_up_4(C); + + int kv_h = q_h; + if (KV_H < Q_H) { + kv_h = q_h / (Q_H / KV_H); + } + + // current context length + const int context_len = input_pos + S; + const int context_texel_len = div_up_4(context_len); + + // bounds check + if (s >= S || q_h >= Q_H) { + return; + } + + const VEC4_T inv_scale_vec = VEC4_T(inv_scale); + T local_max = T(negative_infinity_val); + + FPInputTile q_tile; + FPWeightTile w_tile; + FPOutTile out_tile; + + // Pass 1: compute the attn_weight texels this worker owns, apply scale and + // the causal mask, stash the row in shared memory and track a local max. + // Worker w owns c4 = w, w + 64, w + 128, ... + for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { + const int c = mul_4(c4); + + initialize(out_tile); + + // If the tile is completely inside the mask region there is nothing to + // compute; every element is negative infinity. + const bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); + if (tile_in_mask_region) { + const VEC4_T negative_infinity_vec = VEC4_T(negative_infinity_val); + set_out_tile_to_vec(out_tile, negative_infinity_vec); + } else { + for (int d4 = 0; d4 < D4; ++d4) { + load_q_projected_tile_with_checks( + q_tile, d4, s, q_h, D4, D, S, Q_H); + + load_k_cache_tile_with_checks( + w_tile, d4, c, kv_h, D4, D, context_len, C, KV_H); + + fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); + } + + apply_scale_and_mask(out_tile, inv_scale_vec, input_pos, c, s); + } + + // TILE_M is 1 and TILE_N4 is 1, so the tile holds a single texel. + VEC4_T raw = out_tile.data[0][0]; + + // Positions past context_len inside the final texel must not contribute to + // the row max; setting them to negative infinity makes their exp() zero. + if (c + 0 >= context_len) { + raw.x = T(negative_infinity_val); + } + if (c + 1 >= context_len) { + raw.y = T(negative_infinity_val); + } + if (c + 2 >= context_len) { + raw.z = T(negative_infinity_val); + } + if (c + 3 >= context_len) { + raw.w = T(negative_infinity_val); + } + + row_attn_w_x[c4] = raw.x; + row_attn_w_y[c4] = raw.y; + row_attn_w_z[c4] = raw.z; + row_attn_w_w[c4] = raw.w; + + local_max = max(local_max, max(max(raw.x, raw.y), max(raw.z, raw.w))); + } + + // Reduce the row max across workers. + shared_max[worker_id] = local_max; + memoryBarrierShared(); + barrier(); + + for (int i = NUM_WORKERS_PER_OUT / 2; i > 0; i /= 2) { + if (worker_id < i) { + shared_max[worker_id] = + max(shared_max[worker_id], shared_max[worker_id + i]); + } + memoryBarrierShared(); + barrier(); + } + const T row_max = shared_max[0]; + + // Pass 2: each worker sums exp(x - row_max) over the texels it owns. + T local_sum = T(0); + for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { + local_sum += exp(row_attn_w_x[c4] - row_max); + local_sum += exp(row_attn_w_y[c4] - row_max); + local_sum += exp(row_attn_w_z[c4] - row_max); + local_sum += exp(row_attn_w_w[c4] - row_max); + } + + shared_sum[worker_id] = local_sum; + memoryBarrierShared(); + barrier(); + + for (int i = NUM_WORKERS_PER_OUT / 2; i > 0; i /= 2) { + if (worker_id < i) { + shared_sum[worker_id] = shared_sum[worker_id] + shared_sum[worker_id + i]; + } + memoryBarrierShared(); + barrier(); + } + const T row_sum = shared_sum[0]; + + // Pass 3: write exp(x - row_max) / row_sum. Out of bounds positions in the + // final texel were set to negative infinity above, so they store zero, which + // is what the consumer's load-with-checks would have supplied anyway. + for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { + VEC4_T raw; + raw.x = row_attn_w_x[c4]; + raw.y = row_attn_w_y[c4]; + raw.z = row_attn_w_z[c4]; + raw.w = row_attn_w_w[c4]; + + FPOutTile out_tile_normalized; + out_tile_normalized.data[0][0] = exp(raw - VEC4_T(row_max)) / row_sum; + + store_attn_weight_tile_with_checks( + out_tile_normalized, c4, s, q_h, context_texel_len, S_aligned, Q_H); + } +} diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml new file mode 100644 index 00000000000..acbb96295c8 --- /dev/null +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml @@ -0,0 +1,25 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + +sdpa_compute_attn_weights_coop_softmax: + parameter_names_with_default_values: + DTYPE: float + IO_STORAGE: texture3d + K_CACHE_STORAGE: texture3d + TILE_K4: 1 + TILE_N4: 1 + generate_variant_forall: + combination: + parameter_names: [IO_STORAGE, K_CACHE_STORAGE] + combos: + - parameter_values: [texture3d, texture3d] + - parameter_values: [buffer, texture3d] + - parameter_values: [buffer, buffer] + DTYPE: + - VALUE: float + - VALUE: half + shader_variants: + - NAME: sdpa_compute_attn_weights_coop_softmax diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 39854b23d02..0c6ffd7bba1 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -78,6 +78,32 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { return graph->size_at(-3, q_projected) == 1; } +// Largest attn_weights row, in texels, that the fused QK+softmax shader can +// hold in shared memory. Must match MAX_CONTEXT_TEXEL_LEN in +// sdpa_compute_attn_weights_coop_softmax.glsl. +constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; + +// Whether the decode path should use the single fused QK+softmax dispatch +// instead of the separate attn-weights and softmax pair. +// +// All three nodes are added to the graph, because which one is wanted depends +// on the sequence length, and that is only known once sizes are current: a +// dynamic-shape export reports the max bound at graph build time, never 1. +// Each node's global work group picker calls this and collapses to a zero work +// group when it is not the chosen path, which DispatchNode::encode skips. +bool use_fused_qk_softmax( + ComputeGraph* graph, + const ValueRef q, + const ValueRef k) { + if (!is_single_token(graph, q)) { + return false; + } + // The fused shader keeps the whole attn_weights row in shared memory, so it + // is only valid while that row fits. + const int64_t max_context_len = graph->size_at(-3, k); + return utils::div_up_4(max_context_len) <= kFusedSoftmaxMaxContextTexels; +} + // // Resize functions // @@ -275,6 +301,12 @@ GlobalWorkGrid pick_sdpa_qk_gwg( const ValueRef q = resize_args.at(0); const ValueRef k = resize_args.at(1); const ValueRef input_pos_symint = resize_args.at(2); + + // Decode is served by the single fused QK+softmax node. + if (mode == SDPAMode::LLM && use_fused_qk_softmax(graph, q, k)) { + return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + } + const SDPADims d = compute_sdpa_dims(*graph, q, k, input_pos_symint, mode); // Dispatch grid: (context_len tiles, S tiles, H * B). @@ -303,6 +335,42 @@ LocalWorkGroup pick_sdpa_qk_lwg( return default_pick_lwg(graph, shader, gwg, args, resize_args); } +vkapi::ShaderInfo pick_sdpa_qk_softmax_shader( + ComputeGraph* graph, + const std::vector& args, + const std::vector& resize_args) { + (void)resize_args; + const ValueRef q = args.at(1).refs.at(0); + const ValueRef k = args.at(1).refs.at(1); + + std::string shader_name = "sdpa_compute_attn_weights_coop_softmax"; + add_storage_type_suffix(shader_name, graph->storage_type_of(q)); + add_storage_type_suffix(shader_name, graph->storage_type_of(k)); + add_dtype_suffix(shader_name, graph->dtype_of(q)); + return VK_KERNEL_FROM_STR(shader_name); +} + +GlobalWorkGrid pick_sdpa_qk_softmax_gwg( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + (void)shader; + (void)args; + const ValueRef q = resize_args.at(0); + const ValueRef k = resize_args.at(1); + + // Prefill is served by the separate attn-weights and softmax nodes. + if (!use_fused_qk_softmax(graph, q, k)) { + return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + } + + const uint32_t num_q_heads = graph->size_at(-2, q); + const uint32_t seq_len = graph->size_at(-3, q); + return GlobalWorkGrid( + {1u, seq_len, num_q_heads}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); +} + GlobalWorkGrid pick_sdpa_softmax_gwg( ComputeGraph* graph, const vkapi::ShaderInfo& shader, @@ -311,6 +379,13 @@ GlobalWorkGrid pick_sdpa_softmax_gwg( (void)shader; const SDPAMode mode = mode_of(resize_args); const ValueRef q = resize_args.at(0); + + // Decode folds this into the fused QK+softmax node. + if (mode == SDPAMode::LLM && + use_fused_qk_softmax(graph, q, resize_args.at(1))) { + return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + } + // LLM reads H from axis -2, fused from axis -3 (handled by // compute_sdpa_dims). const int64_t num_q_heads = (mode == SDPAMode::LLM) @@ -486,6 +561,43 @@ void add_sdpa_kv_cache_update_node( // kDummyValueRef to indicate no bias. scale_val is always passed as // a spec const; the LLM path computes it per head_dim and FUSED may // inherit from the caller-supplied scale. +// Decode-only fused Q @ K^T + softmax. Writes normalized weights straight to +// attn_weights_softmax, removing the separate softmax dispatch and the round +// trip through attn_weights. LLM mode only. +void add_sdpa_compute_attn_weights_with_softmax_node( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const float scale_val, + const ValueRef attn_weights_softmax) { + vkapi::ParamsBindList param_ubos = { + graph.sizes_ubo(q), + graph.sizes_ubo(k), + graph.get_or_create_int_param_buffer(input_pos_symint), + }; + + const ValueRef mode_ref = static_cast(SDPAMode::LLM); + + graph.execute_nodes().emplace_back(new DynamicDispatchNode( + graph, + pick_sdpa_qk_softmax_shader, + pick_sdpa_qk_softmax_gwg, + pick_required_lwg, + // Inputs and Outputs + {{attn_weights_softmax, vkapi::kWrite}, {{q, k}, vkapi::kRead}}, + // Shader param buffers + param_ubos, + // Push Constants + {}, + // Specialization Constants + {scale_val}, + // Resize Args: [q, k, input_pos_symint, mode] + {q, k, input_pos_symint, mode_ref}, + // Resizing Logic + resize_sdpa_attn_weights_softmax_node)); +} + void add_sdpa_compute_attn_weights_node( ComputeGraph& graph, const ValueRef q, @@ -765,6 +877,19 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { const int32_t head_dim_size = graph.size_at(-1, q_projected); const float scale_val = 1.0f / std::sqrt(static_cast(head_dim_size)); + // Decode (S == 1) is served by a single fused QK+softmax dispatch, prefill by + // the separate pair below. Both are built: the sequence length is only known + // once sizes are current, since a dynamic-shape export reports the max bound + // at graph build time. Each node's global work group picker collapses to zero + // when it is not the chosen path, and DispatchNode::encode skips it. + add_sdpa_compute_attn_weights_with_softmax_node( + graph, + q_projected, + k_cache, + input_pos_symint, + scale_val, + attn_weights_softmax); + add_sdpa_compute_attn_weights_node( graph, q_projected, From 8c348f932120a44614821cdeef781c5b74ece94a Mon Sep 17 00:00:00 2001 From: Mateusz Sluszniak Date: Sat, 19 Sep 2026 00:30:25 +0200 Subject: [PATCH 02/13] Vulkan: gate the fused SDPA decode path on the live context length The fused QK+softmax dispatch reduces a whole attn_weights row inside one work group, so its parallelism is capped at num_q_heads work groups while the separate pair gets one work group per context texel. Measured on Qwen3-0.6B/Adreno, it wins 3.6-6.2% below ~192 tokens and costs 9-11% beyond ~550, crossing over around 220. The gate now reads the live context length instead of the K cache bound, so it re-decides every token: the pickers are re-run from DynamicDispatchNode::trigger_resize. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 36 ++++++++++++++----- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 0c6ffd7bba1..de07106d94e 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -83,6 +83,20 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { // sdpa_compute_attn_weights_coop_softmax.glsl. constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; +// Context length past which the separate attn-weights and softmax pair is +// faster than the fused dispatch. The fused shader reduces the whole row +// inside one work group, so its parallelism is capped at num_q_heads work +// groups; the separate pair spreads the same work over one work group per +// context texel. Below the cutoff the saved dispatch and the saved round trip +// of attn_weights through global memory dominate; above it the lost +// parallelism does. +constexpr int64_t kFusedSoftmaxMaxContextLen = 256; + +// The cutoff also has to keep the row inside the shader's shared memory. +static_assert( + kFusedSoftmaxMaxContextLen <= kFusedSoftmaxMaxContextTexels * 4, + "fused QK+softmax cutoff exceeds the shader's shared attn_weights row"); + // Whether the decode path should use the single fused QK+softmax dispatch // instead of the separate attn-weights and softmax pair. // @@ -91,17 +105,20 @@ constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; // dynamic-shape export reports the max bound at graph build time, never 1. // Each node's global work group picker calls this and collapses to a zero work // group when it is not the chosen path, which DispatchNode::encode skips. +// Pickers are re-run from DynamicDispatchNode::trigger_resize, so the choice +// is re-made every token and follows the context length as it grows. bool use_fused_qk_softmax( ComputeGraph* graph, const ValueRef q, - const ValueRef k) { + const ValueRef k, + const ValueRef input_pos_symint) { if (!is_single_token(graph, q)) { return false; } - // The fused shader keeps the whole attn_weights row in shared memory, so it - // is only valid while that row fits. - const int64_t max_context_len = graph->size_at(-3, k); - return utils::div_up_4(max_context_len) <= kFusedSoftmaxMaxContextTexels; + const int64_t context_len = + compute_sdpa_dims(*graph, q, k, input_pos_symint, SDPAMode::LLM) + .context_len; + return context_len <= kFusedSoftmaxMaxContextLen; } // @@ -303,7 +320,8 @@ GlobalWorkGrid pick_sdpa_qk_gwg( const ValueRef input_pos_symint = resize_args.at(2); // Decode is served by the single fused QK+softmax node. - if (mode == SDPAMode::LLM && use_fused_qk_softmax(graph, q, k)) { + if (mode == SDPAMode::LLM && + use_fused_qk_softmax(graph, q, k, input_pos_symint)) { return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); } @@ -360,8 +378,8 @@ GlobalWorkGrid pick_sdpa_qk_softmax_gwg( const ValueRef q = resize_args.at(0); const ValueRef k = resize_args.at(1); - // Prefill is served by the separate attn-weights and softmax nodes. - if (!use_fused_qk_softmax(graph, q, k)) { + // Prefill, and decode past the cutoff, are served by the separate nodes. + if (!use_fused_qk_softmax(graph, q, k, resize_args.at(2))) { return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); } @@ -382,7 +400,7 @@ GlobalWorkGrid pick_sdpa_softmax_gwg( // Decode folds this into the fused QK+softmax node. if (mode == SDPAMode::LLM && - use_fused_qk_softmax(graph, q, resize_args.at(1))) { + use_fused_qk_softmax(graph, q, resize_args.at(1), resize_args.at(2))) { return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); } From 5d95155d6124410dd6d18dacf7e61732fcd7ec0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 14:34:19 +0200 Subject: [PATCH 03/13] Vulkan: generate the fused SDPA decode shader from the coop template The fused Q @ K^T + softmax shader was a standalone copy of the coop attn-weights shader plus a hand-rolled softmax. Share both instead: - Move the 3-pass softmax of sdpa_attn_weights_softmax.glsl into sdpa_attn_weights_softmax_row.glslh. The softmax shader reads its row from global memory, the fused shader from shared memory. - Generate sdpa_compute_attn_weights_coop_softmax_* as a FUSE_SOFTMAX variant of sdpa_compute_attn_weights_coop.glsl, with the per-tile Q @ K^T accumulation factored into compute_attn_weight_tile() for both variants. The existing coop and softmax variants compile to SPIR-V with the same per-opcode instruction counts as before. --- .../ops/glsl/sdpa_attn_weights_softmax.glsl | 136 +--------- .../glsl/sdpa_attn_weights_softmax_row.glslh | 178 +++++++++++++ .../glsl/sdpa_compute_attn_weights_coop.glsl | 210 ++++++++++++--- .../glsl/sdpa_compute_attn_weights_coop.yaml | 3 + ...dpa_compute_attn_weights_coop_softmax.glsl | 241 ------------------ ...dpa_compute_attn_weights_coop_softmax.yaml | 25 -- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 2 +- 7 files changed, 357 insertions(+), 438 deletions(-) create mode 100644 backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh delete mode 100644 backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl delete mode 100644 backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl index 6c095e66255..d3d1464f9bd 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax.glsl @@ -42,11 +42,6 @@ $if MODE == "llm": layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; -// Shared memory for cooperative max finding and exp sum reduction. -// For fused SDPA, reductions happen in fp32 for numerical stability. -shared SOFTMAX_ACC_T shared_max[NUM_WORKERS_PER_WG]; -shared SOFTMAX_ACC_T shared_exp_sum[NUM_WORKERS_PER_WG]; - SOFTMAX_IN_VEC4_T load_attn_weights_c4( const int c4, const int s, @@ -76,6 +71,8 @@ void store_attn_weights_softmax_c4( #endif } +#include "sdpa_attn_weights_softmax_row.glslh" + /* * 3-pass numerically stable softmax over the context_len dimension of * attention weights. @@ -119,7 +116,6 @@ void main() { #else const int context_len = k_sizes.y; #endif - const int context_texel_len = div_up_4(context_len); // LLM: attn_weights S dim is padded to S_aligned; fused: not padded. #ifdef HAS_INPUT_POS @@ -134,131 +130,5 @@ void main() { return; } - const int context_len_aligned_down = context_len - mod_4(context_len); - const int C4_limit = div_4(context_len_aligned_down); - - // ========================================================================= - // Pass 1: Find the maximum value across the row for numerical stability. - // Without this, exp(x) can overflow float32 when x > ~88.7. - // ========================================================================= - - SOFTMAX_ACC_T local_max = SOFTMAX_ACC_T(-1.0 / 0.0); // -infinity - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - for (int comp = 0; comp < 4; comp++) { - local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); - } - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); - } - } - } - } - - shared_max[worker_id] = local_max; - - memoryBarrierShared(); - barrier(); - - // Tree reduction to find the global max - for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { - if (worker_id < i) { - shared_max[worker_id] = max( - shared_max[worker_id], shared_max[worker_id + i]); - } - memoryBarrierShared(); - barrier(); - } - - const SOFTMAX_ACC_T global_max = shared_max[0]; - - // ========================================================================= - // Pass 2: Compute sum(exp(x - max)) using the global max for stability - // ========================================================================= - - SOFTMAX_ACC_T local_exp_sum = SOFTMAX_ACC_T(0); - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - for (int comp = 0; comp < 4; comp++) { - local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); - } - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); - } - } - } - } - - shared_exp_sum[worker_id] = local_exp_sum; - - memoryBarrierShared(); - barrier(); - - // Tree reduction to compute the overall exp sum - for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { - if (worker_id < i) { - shared_exp_sum[worker_id] = shared_exp_sum[worker_id] + - shared_exp_sum[worker_id + i]; - } - memoryBarrierShared(); - barrier(); - } - - local_exp_sum = shared_exp_sum[0]; - - // ========================================================================= - // Pass 3: Normalize each element: out = exp(x - max) / sum(exp(x - max)) - // ========================================================================= - - for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - VEC4_T out_texel; - [[unroll]] for (int comp = 0; comp < 4; comp++) { - out_texel[comp] = T( - exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); - } - store_attn_weights_softmax_c4( - out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); - } - if (worker_id == 0) { - for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { - const int c_base = mul_4(c4); - SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( - c4, s, q_h, context_texel_len, attn_S, Q_H); - - VEC4_T out_texel = VEC4_T(0); - [[unroll]] for (int comp = 0; comp < 4; comp++) { - if (c_base + comp < context_len) { - out_texel[comp] = T( - exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); - } - } - store_attn_weights_softmax_c4( - out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); - } - } + softmax_attn_weights_row(worker_id, s, q_h, context_len, attn_S, Q_H); } diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh new file mode 100644 index 00000000000..3611c9fd223 --- /dev/null +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_attn_weights_softmax_row.glslh @@ -0,0 +1,178 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* + * Cooperative softmax over one row of attention weights, shared by the + * standalone softmax shader and the fused QK + softmax variant of the coop + * attention weights shader. + * + * Required macros: + * NUM_WORKERS_PER_WG - number of invocations in the work group + * SOFTMAX_IN_VEC4_T - texel type returned by load_attn_weights_c4 + * SOFTMAX_ACC_T - scalar type the max and exp sum are reduced in + * VEC4_T, T - texel and scalar type of the softmax output + * + * Required functions, defined before including this file: + * SOFTMAX_IN_VEC4_T load_attn_weights_c4(c4, s, q_h, C4, S, Q_H) + * void store_attn_weights_softmax_c4(VEC4_T, c4, s, q_h, C4, S, Q_H) + */ + +#ifndef SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH +#define SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH + +#extension GL_EXT_control_flow_attributes : require + +// Shared memory for cooperative max finding and exp sum reduction. +// For fused SDPA, reductions happen in fp32 for numerical stability. +shared SOFTMAX_ACC_T shared_max[NUM_WORKERS_PER_WG]; +shared SOFTMAX_ACC_T shared_exp_sum[NUM_WORKERS_PER_WG]; + +/* + * 3-pass numerically stable softmax over the first context_len elements of + * row (s, q_h). attn_S is the S extent of the attention weight tensors. Every + * invocation of the work group must call this, since it contains barriers. + */ +void softmax_attn_weights_row( + const int worker_id, + const int s, + const int q_h, + const int context_len, + const int attn_S, + const int Q_H) { + const int context_texel_len = div_up_4(context_len); + + const int context_len_aligned_down = context_len - mod_4(context_len); + const int C4_limit = div_4(context_len_aligned_down); + + // ========================================================================= + // Pass 1: Find the maximum value across the row for numerical stability. + // Without this, exp(x) can overflow float32 when x > ~88.7. + // ========================================================================= + + SOFTMAX_ACC_T local_max = SOFTMAX_ACC_T(-1.0 / 0.0); // -infinity + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + for (int comp = 0; comp < 4; comp++) { + local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); + } + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + local_max = max(local_max, SOFTMAX_ACC_T(in_texel[comp])); + } + } + } + } + + shared_max[worker_id] = local_max; + + memoryBarrierShared(); + barrier(); + + // Tree reduction to find the global max + for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { + if (worker_id < i) { + shared_max[worker_id] = max( + shared_max[worker_id], shared_max[worker_id + i]); + } + memoryBarrierShared(); + barrier(); + } + + const SOFTMAX_ACC_T global_max = shared_max[0]; + + // ========================================================================= + // Pass 2: Compute sum(exp(x - max)) using the global max for stability + // ========================================================================= + + SOFTMAX_ACC_T local_exp_sum = SOFTMAX_ACC_T(0); + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + for (int comp = 0; comp < 4; comp++) { + local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); + } + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + local_exp_sum += exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max); + } + } + } + } + + shared_exp_sum[worker_id] = local_exp_sum; + + memoryBarrierShared(); + barrier(); + + // Tree reduction to compute the overall exp sum + for (int i = NUM_WORKERS_PER_WG / 2; i > 0; i >>= 1) { + if (worker_id < i) { + shared_exp_sum[worker_id] = shared_exp_sum[worker_id] + + shared_exp_sum[worker_id + i]; + } + memoryBarrierShared(); + barrier(); + } + + local_exp_sum = shared_exp_sum[0]; + + // ========================================================================= + // Pass 3: Normalize each element: out = exp(x - max) / sum(exp(x - max)) + // ========================================================================= + + for (int c4 = worker_id; c4 < C4_limit; c4 += NUM_WORKERS_PER_WG) { + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + VEC4_T out_texel; + [[unroll]] for (int comp = 0; comp < 4; comp++) { + out_texel[comp] = T( + exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); + } + store_attn_weights_softmax_c4( + out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); + } + if (worker_id == 0) { + for (int c4 = C4_limit; c4 < context_texel_len; ++c4) { + const int c_base = mul_4(c4); + SOFTMAX_IN_VEC4_T in_texel = load_attn_weights_c4( + c4, s, q_h, context_texel_len, attn_S, Q_H); + + VEC4_T out_texel = VEC4_T(0); + [[unroll]] for (int comp = 0; comp < 4; comp++) { + if (c_base + comp < context_len) { + out_texel[comp] = T( + exp(SOFTMAX_ACC_T(in_texel[comp]) - global_max) / local_exp_sum); + } + } + store_attn_weights_softmax_c4( + out_texel, c4, s, q_h, context_texel_len, attn_S, Q_H); + } + } +} + +#endif // SDPA_ATTN_WEIGHTS_SOFTMAX_ROW_GLSLH diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl index b7f14f435fa..31f85e4cdf1 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl @@ -31,6 +31,13 @@ $if K_CACHE_STORAGE == "buffer": #define NUM_WORKERS_PER_OUT 64 +$if FUSE_SOFTMAX: + #define FUSE_SOFTMAX + // Cap on the attn_weights row held in shared memory, in texels. The host only + // selects this variant when the context fits within this bound (see + // use_fused_qk_softmax() in SDPA.cpp), so the indexing below is in range. + #define MAX_CONTEXT_TEXEL_LEN 1024 + ${define_required_extensions(IO_STORAGE, DTYPE)} layout(std430) buffer; @@ -54,22 +61,139 @@ ${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} #include "linear_fp_output_tile_fp_compute.glslh" #include "sdpa_fp_attn_weight_tile_store.glslh" +#ifdef FUSE_SOFTMAX + +// The scaled and masked attn_weights row, one array per texel component. +shared T row_attn_w_x[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_y[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_z[MAX_CONTEXT_TEXEL_LEN]; +shared T row_attn_w_w[MAX_CONTEXT_TEXEL_LEN]; + +#define NUM_WORKERS_PER_WG NUM_WORKERS_PER_OUT +#define SOFTMAX_IN_VEC4_T VEC4_T +#define SOFTMAX_ACC_T T + +// The softmax reads the row back from shared memory... +VEC4_T load_attn_weights_c4( + const int c4, + const int s, + const int q_h, + const int C4, + const int S, + const int Q_H) { + return VEC4_T( + row_attn_w_x[c4], row_attn_w_y[c4], row_attn_w_z[c4], row_attn_w_w[c4]); +} + +// ...and writes the normalized weights to t_attn_weights. +void store_attn_weights_softmax_c4( + const VEC4_T out_texel, + const int c4, + const int s, + const int q_h, + const int C4, + const int S, + const int Q_H) { + store_attn_weight_c4(out_texel, c4, s, q_h, C4, S, Q_H); +} + +#include "sdpa_attn_weights_softmax_row.glslh" + +#else + shared FPOutTile partial_sums[NUM_WORKERS_PER_OUT]; +#endif + +/* + * Accumulates Q @ K^T for the attn_weights tile at (c, s, q_h) over the head + * dim texels d4_start, d4_start + d4_step, ... A tile entirely inside the + * causal mask is set to negative infinity instead, and true is returned, in + * which case no scale or mask needs to be applied to it. + */ +bool compute_attn_weight_tile( + out FPOutTile out_tile, + const int d4_start, + const int d4_step, + const int c, + const int s, + const int q_h, + const int kv_h, + const int D4, + const int D, + const int S, + const int Q_H, + const int context_len, + const int C, + const int KV_H) { + initialize(out_tile); + + FPInputTile q_tile; + FPWeightTile w_tile; + + // If the tile is completely inside the mask region, then there is no need to + // compute the output tile. All the elements in the output tile can be set to + // negative infinity. + bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); + if (tile_in_mask_region) { + const VEC4_T negative_infinity_vec = VEC4_T(negative_infinity_val); + set_out_tile_to_vec(out_tile, negative_infinity_vec); + } + // Otherwise, need to actually compute output tile + else { + for (int d4 = d4_start; d4 < D4; d4 += d4_step) { + load_q_projected_tile_with_checks( + q_tile, + d4, + s, + q_h, + D4, + D, + S, + Q_H); + + load_k_cache_tile_with_checks( + w_tile, + d4, + c, + kv_h, + D4, + D, + context_len, + C, + KV_H); + + fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); + } + } + return tile_in_mask_region; +} + /* * See the tiled variant of this shader for the implemented behavior. This * shader is implements an optimization for cases where sequence length is 1; in * these cases, the matrix multiplication being performed is akin to gemv, which * benefits from using a co-operative algorithm for reduction. For this shader * the entire work group co-operates to compute one reduction output. + * + * The FUSE_SOFTMAX variant instead dispatches one work group per (s, q_h) row. + * Each worker computes whole texels of the row, which is kept in shared memory + * so that the work group can apply the softmax and write normalized weights + * directly. That saves the separate softmax dispatch and the round trip of + * attn_weights through global memory, at the cost of parallelism along the + * context dim, so the host only selects it for short contexts. */ void main() { +#ifdef FUSE_SOFTMAX + const int worker_id = int(gl_LocalInvocationID.x); + + // idx along the output seq_len dim + const int s = int(gl_GlobalInvocationID.y); +#else const int worker_id = int(gl_LocalInvocationID.y); const int tile_idx_x = int(gl_GlobalInvocationID.x); - // idx along output num_q_heads dim - const int q_h = int(gl_GlobalInvocationID.z); // idx along the output context_len dim const int c = tile_idx_x * TILE_N; @@ -78,6 +202,9 @@ void main() { // idx along the output seq_len dim. Note that for this shader seq_len will be // 1. const int s = 0; +#endif + // idx along output num_q_heads dim + const int q_h = int(gl_GlobalInvocationID.z); // head dimension const int D = q_sizes.x; @@ -104,53 +231,59 @@ void main() { const int context_len = input_pos + S; const int context_texel_len = div_up_4(context_len); +#ifdef FUSE_SOFTMAX // bounds check - if (c >= context_len || s >= S || q_h >= Q_H) { + if (s >= S || q_h >= Q_H) { return; } - FPOutTile out_tile; - initialize(out_tile); + // Compute the row into shared memory; worker w owns c4 = w, w + 64, ... + for (int c4 = worker_id; c4 < context_texel_len; + c4 += NUM_WORKERS_PER_OUT) { + const int c = mul_4(c4); - FPInputTile q_tile; - FPWeightTile w_tile; + FPOutTile out_tile; + const bool tile_in_mask_region = compute_attn_weight_tile( + out_tile, 0, 1, c, s, q_h, kv_h, D4, D, S, Q_H, context_len, C, KV_H); + if (!tile_in_mask_region) { + VEC4_T inv_scale_vec = VEC4_T(inv_scale); + apply_scale_and_mask(out_tile, inv_scale_vec, input_pos, c, s); + } - // If the tile is completely inside the mask region, then there is no need to - // compute the output tile. All the elements in the output tile can be set to - // negative infinity. - bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); - if (tile_in_mask_region) { - const VEC4_T negative_infinity_vec = VEC4_T(negative_infinity_val); - set_out_tile_to_vec(out_tile, negative_infinity_vec); + // TILE_M and TILE_N4 are 1, so the tile holds a single texel. + row_attn_w_x[c4] = out_tile.data[0][0].x; + row_attn_w_y[c4] = out_tile.data[0][0].y; + row_attn_w_z[c4] = out_tile.data[0][0].z; + row_attn_w_w[c4] = out_tile.data[0][0].w; } - // Otherwise, need to actually compute output tile - else { - for (int d4 = worker_id; d4 < D4; d4 += NUM_WORKERS_PER_OUT) { - load_q_projected_tile_with_checks( - q_tile, - d4, - s, - q_h, - D4, - D, - S, - Q_H); - load_k_cache_tile_with_checks( - w_tile, - d4, - c, - kv_h, - D4, - D, - context_len, - C, - KV_H); + memoryBarrierShared(); + barrier(); - fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); - } + softmax_attn_weights_row(worker_id, s, q_h, context_len, S_aligned, Q_H); +#else + // bounds check + if (c >= context_len || s >= S || q_h >= Q_H) { + return; } + FPOutTile out_tile; + const bool tile_in_mask_region = compute_attn_weight_tile( + out_tile, + worker_id, + NUM_WORKERS_PER_OUT, + c, + s, + q_h, + kv_h, + D4, + D, + S, + Q_H, + context_len, + C, + KV_H); + partial_sums[worker_id] = out_tile; memoryBarrierShared(); @@ -189,4 +322,5 @@ void main() { S_aligned, Q_H); } +#endif } diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml index d5cadc36060..479a47d01c8 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml @@ -11,6 +11,7 @@ sdpa_compute_attn_weights_coop: K_CACHE_STORAGE: texture3d TILE_K4: 1 TILE_N4: 1 + FUSE_SOFTMAX: false generate_variant_forall: combination: parameter_names: [IO_STORAGE, K_CACHE_STORAGE] @@ -23,3 +24,5 @@ sdpa_compute_attn_weights_coop: - VALUE: half shader_variants: - NAME: sdpa_compute_attn_weights_coop + - NAME: sdpa_compute_attn_weights_coop_softmax + FUSE_SOFTMAX: true diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl deleted file mode 100644 index f9b89b2876f..00000000000 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.glsl +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * All rights reserved. - * - * This source code is licensed under the BSD-style license found in the - * LICENSE file in the root directory of this source tree. - */ - -#version 450 core - -#define PRECISION ${PRECISION} -#define VEC4_T ${texel_load_type(DTYPE, IO_STORAGE)} -#define T ${texel_load_component_type(DTYPE, IO_STORAGE)} - -$if IO_STORAGE == "buffer": - #define OUTPUT_BUFFER - #define INPUT_BUFFER - #define ATTN_WEIGHTS_BUFFER -$if K_CACHE_STORAGE == "buffer": - #define K_CACHE_BUFFER - -#define Q_LAYOUT DHSB -#define K_LAYOUT DHSB - -#define TILE_K4 ${TILE_K4} -#define TILE_N4 ${TILE_N4} - -#define TILE_M 1 -#define TILE_K ${TILE_K4 * 4} -#define TILE_N ${TILE_N4 * 4} - -#define NUM_WORKERS_PER_OUT 64 - -// Cap on the attn_weights row held in shared memory, in texels. The host only -// selects this shader when div_up_4(max_context_len) fits within this bound -// (see use_fused_qk_softmax() in SDPA.cpp), so the indexing below is in range. -#define MAX_CONTEXT_TEXEL_LEN 1024 - -${define_required_extensions(IO_STORAGE, DTYPE)} - -layout(std430) buffer; - -#include "common.glslh" - -${layout_declare_tensor(B, "w", "t_attn_weights", DTYPE, IO_STORAGE, is_scalar_array=False)} -${layout_declare_tensor(B, "r", "t_q", DTYPE, IO_STORAGE, is_scalar_array=False)} -${layout_declare_tensor(B, "r", "t_k", DTYPE, K_CACHE_STORAGE, is_scalar_array=False)} - -${layout_declare_ubo(B, "ivec4", "q_sizes")} -${layout_declare_ubo(B, "ivec4", "k_sizes")} -${layout_declare_ubo(B, "int", "input_pos")} - -layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; - -${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} - -#include "sdpa_fp_q_projected_tile_load.glslh" -#include "sdpa_fp_k_cache_tile_load.glslh" -#include "linear_fp_output_tile_fp_compute.glslh" -#include "sdpa_fp_attn_weight_tile_store.glslh" - -// The attn_weights row after scale and causal masking, plus per-worker scratch -// for the row-max and exp-sum tree reductions. -shared T row_attn_w_x[MAX_CONTEXT_TEXEL_LEN]; -shared T row_attn_w_y[MAX_CONTEXT_TEXEL_LEN]; -shared T row_attn_w_z[MAX_CONTEXT_TEXEL_LEN]; -shared T row_attn_w_w[MAX_CONTEXT_TEXEL_LEN]; -shared T shared_max[NUM_WORKERS_PER_OUT]; -shared T shared_sum[NUM_WORKERS_PER_OUT]; - -/* - * Fused Q @ K^T and softmax for the decode path (sequence length 1). - * - * The coop sibling of this shader dispatches one work group per (c4, q_h) and - * tree-reduces across head_dim, each group emitting one texel of attn_weights; - * a separate shader then performs the softmax across the context dim in a - * three-pass max/subtract/normalize algorithm. - * - * This variant instead dispatches one work group per (s, q_h), whose 64 workers - * cooperatively walk every c4 of that row. The row stays in shared memory, so - * the group can reduce it to row_max and exp_sum and write normalized softmax - * values straight to t_attn_weights. That removes one dispatch per layer along - * with the round trip through attn_weights between the matmul and the softmax. - * - * The trade-off is the loss of parallelism along the context axis (from one - * work group per context tile down to one), which is why the host restricts - * this shader to sequence length 1, where per-dispatch overhead dominates. - */ -void main() { - const int worker_id = int(gl_LocalInvocationID.x); - - // idx along the output seq_len dim; this shader is only dispatched for S == 1 - const int s = int(gl_GlobalInvocationID.y); - // idx along output num_q_heads dim - const int q_h = int(gl_GlobalInvocationID.z); - - // head dimension - const int D = q_sizes.x; - // texel size of head_dim, over which the dot product is accumulated - const int D4 = div_up_4(D); - // number of Q heads - const int Q_H = q_sizes.y; - // sequence length - const int S = q_sizes.z; - const int S_aligned = align_up_4(S); - - // number of K/V heads - const int KV_H = k_sizes.y; - // Max context length - const int C = k_sizes.z; - const int C4 = div_up_4(C); - - int kv_h = q_h; - if (KV_H < Q_H) { - kv_h = q_h / (Q_H / KV_H); - } - - // current context length - const int context_len = input_pos + S; - const int context_texel_len = div_up_4(context_len); - - // bounds check - if (s >= S || q_h >= Q_H) { - return; - } - - const VEC4_T inv_scale_vec = VEC4_T(inv_scale); - T local_max = T(negative_infinity_val); - - FPInputTile q_tile; - FPWeightTile w_tile; - FPOutTile out_tile; - - // Pass 1: compute the attn_weight texels this worker owns, apply scale and - // the causal mask, stash the row in shared memory and track a local max. - // Worker w owns c4 = w, w + 64, w + 128, ... - for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { - const int c = mul_4(c4); - - initialize(out_tile); - - // If the tile is completely inside the mask region there is nothing to - // compute; every element is negative infinity. - const bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); - if (tile_in_mask_region) { - const VEC4_T negative_infinity_vec = VEC4_T(negative_infinity_val); - set_out_tile_to_vec(out_tile, negative_infinity_vec); - } else { - for (int d4 = 0; d4 < D4; ++d4) { - load_q_projected_tile_with_checks( - q_tile, d4, s, q_h, D4, D, S, Q_H); - - load_k_cache_tile_with_checks( - w_tile, d4, c, kv_h, D4, D, context_len, C, KV_H); - - fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); - } - - apply_scale_and_mask(out_tile, inv_scale_vec, input_pos, c, s); - } - - // TILE_M is 1 and TILE_N4 is 1, so the tile holds a single texel. - VEC4_T raw = out_tile.data[0][0]; - - // Positions past context_len inside the final texel must not contribute to - // the row max; setting them to negative infinity makes their exp() zero. - if (c + 0 >= context_len) { - raw.x = T(negative_infinity_val); - } - if (c + 1 >= context_len) { - raw.y = T(negative_infinity_val); - } - if (c + 2 >= context_len) { - raw.z = T(negative_infinity_val); - } - if (c + 3 >= context_len) { - raw.w = T(negative_infinity_val); - } - - row_attn_w_x[c4] = raw.x; - row_attn_w_y[c4] = raw.y; - row_attn_w_z[c4] = raw.z; - row_attn_w_w[c4] = raw.w; - - local_max = max(local_max, max(max(raw.x, raw.y), max(raw.z, raw.w))); - } - - // Reduce the row max across workers. - shared_max[worker_id] = local_max; - memoryBarrierShared(); - barrier(); - - for (int i = NUM_WORKERS_PER_OUT / 2; i > 0; i /= 2) { - if (worker_id < i) { - shared_max[worker_id] = - max(shared_max[worker_id], shared_max[worker_id + i]); - } - memoryBarrierShared(); - barrier(); - } - const T row_max = shared_max[0]; - - // Pass 2: each worker sums exp(x - row_max) over the texels it owns. - T local_sum = T(0); - for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { - local_sum += exp(row_attn_w_x[c4] - row_max); - local_sum += exp(row_attn_w_y[c4] - row_max); - local_sum += exp(row_attn_w_z[c4] - row_max); - local_sum += exp(row_attn_w_w[c4] - row_max); - } - - shared_sum[worker_id] = local_sum; - memoryBarrierShared(); - barrier(); - - for (int i = NUM_WORKERS_PER_OUT / 2; i > 0; i /= 2) { - if (worker_id < i) { - shared_sum[worker_id] = shared_sum[worker_id] + shared_sum[worker_id + i]; - } - memoryBarrierShared(); - barrier(); - } - const T row_sum = shared_sum[0]; - - // Pass 3: write exp(x - row_max) / row_sum. Out of bounds positions in the - // final texel were set to negative infinity above, so they store zero, which - // is what the consumer's load-with-checks would have supplied anyway. - for (int c4 = worker_id; c4 < context_texel_len; c4 += NUM_WORKERS_PER_OUT) { - VEC4_T raw; - raw.x = row_attn_w_x[c4]; - raw.y = row_attn_w_y[c4]; - raw.z = row_attn_w_z[c4]; - raw.w = row_attn_w_w[c4]; - - FPOutTile out_tile_normalized; - out_tile_normalized.data[0][0] = exp(raw - VEC4_T(row_max)) / row_sum; - - store_attn_weight_tile_with_checks( - out_tile_normalized, c4, s, q_h, context_texel_len, S_aligned, Q_H); - } -} diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml deleted file mode 100644 index acbb96295c8..00000000000 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop_softmax.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# Copyright (c) Meta Platforms, Inc. and affiliates. -# All rights reserved. -# -# This source code is licensed under the BSD-style license found in the -# LICENSE file in the root directory of this source tree. - -sdpa_compute_attn_weights_coop_softmax: - parameter_names_with_default_values: - DTYPE: float - IO_STORAGE: texture3d - K_CACHE_STORAGE: texture3d - TILE_K4: 1 - TILE_N4: 1 - generate_variant_forall: - combination: - parameter_names: [IO_STORAGE, K_CACHE_STORAGE] - combos: - - parameter_values: [texture3d, texture3d] - - parameter_values: [buffer, texture3d] - - parameter_values: [buffer, buffer] - DTYPE: - - VALUE: float - - VALUE: half - shader_variants: - - NAME: sdpa_compute_attn_weights_coop_softmax diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index de07106d94e..e6577a08c29 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -80,7 +80,7 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { // Largest attn_weights row, in texels, that the fused QK+softmax shader can // hold in shared memory. Must match MAX_CONTEXT_TEXEL_LEN in -// sdpa_compute_attn_weights_coop_softmax.glsl. +// sdpa_compute_attn_weights_coop.glsl. constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; // Context length past which the separate attn-weights and softmax pair is From b9a353a66d19577ceef7133a26c797f8c12e7f07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 14:34:19 +0200 Subject: [PATCH 04/13] Vulkan: fix the zero dispatch and resize of the fused SDPA decode node Two bugs in the fused Q @ K^T + softmax node: - A node not serving the current path returned a zero grid without a required local work group, so pick_required_lwg threw while building the graph, and every model on the LLM SDPA path aborted at load. Zero grids now carry the node's lwg. - The fused node resized its output with the softmax resize, which copies the shape of args[1]; for this node that is q, so the output took q's shape and overflowed its texture when q is wider than the attn_weights row. It now uses the attn_weights resize. --- backends/vulkan/runtime/graph/ops/impl/SDPA.cpp | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index e6577a08c29..9f5b5a365c0 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -322,7 +322,10 @@ GlobalWorkGrid pick_sdpa_qk_gwg( // Decode is served by the single fused QK+softmax node. if (mode == SDPAMode::LLM && use_fused_qk_softmax(graph, q, k, input_pos_symint)) { - return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + // The zero grid still carries the coop shader's local work group, since + // the lwg picker requires one. + return GlobalWorkGrid( + {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(1u, 64u, 1u)); } const SDPADims d = compute_sdpa_dims(*graph, q, k, input_pos_symint, mode); @@ -380,7 +383,8 @@ GlobalWorkGrid pick_sdpa_qk_softmax_gwg( // Prefill, and decode past the cutoff, are served by the separate nodes. if (!use_fused_qk_softmax(graph, q, k, resize_args.at(2))) { - return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + return GlobalWorkGrid( + {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); } const uint32_t num_q_heads = graph->size_at(-2, q); @@ -401,7 +405,8 @@ GlobalWorkGrid pick_sdpa_softmax_gwg( // Decode folds this into the fused QK+softmax node. if (mode == SDPAMode::LLM && use_fused_qk_softmax(graph, q, resize_args.at(1), resize_args.at(2))) { - return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid); + return GlobalWorkGrid( + {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); } // LLM reads H from axis -2, fused from axis -3 (handled by @@ -612,8 +617,9 @@ void add_sdpa_compute_attn_weights_with_softmax_node( {scale_val}, // Resize Args: [q, k, input_pos_symint, mode] {q, k, input_pos_symint, mode_ref}, - // Resizing Logic - resize_sdpa_attn_weights_softmax_node)); + // Resizing Logic: the output has the attn_weights shape, and args[1] + // holds {q, k}, not an attn_weights tensor to copy the shape from. + resize_sdpa_attn_weights_node)); } void add_sdpa_compute_attn_weights_node( From f5aeaced6cad758516d1f7ca7ab801a281104adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 14:34:19 +0200 Subject: [PATCH 05/13] Vulkan: add the fused SDPA decode node to the test_sdpa mirror test_sdpa builds the SDPA nodes itself to mirror sdpa_impl. Without the fused node, the separate pair is skipped on short decode contexts and nothing writes attn_weights_softmax. --- backends/vulkan/runtime/graph/ops/impl/SDPA.h | 11 +++++++++++ backends/vulkan/test/custom_ops/impl/TestSDPA.cpp | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.h b/backends/vulkan/runtime/graph/ops/impl/SDPA.h index fa51ebef111..33d7d2ae9ab 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.h +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.h @@ -35,6 +35,17 @@ void add_sdpa_compute_attn_weights_node( const ValueRef attn_weights, const SDPAMode mode); +// Decode-only fused Q @ K^T + softmax, LLM mode. It is added alongside the +// separate attn-weights and softmax nodes; their work group pickers make sure +// exactly one of the two paths dispatches for the current context length. +void add_sdpa_compute_attn_weights_with_softmax_node( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const float scale_val, + const ValueRef attn_weights_softmax); + void add_sdpa_attn_weights_softmax_node( ComputeGraph& graph, const ValueRef attn_weights, diff --git a/backends/vulkan/test/custom_ops/impl/TestSDPA.cpp b/backends/vulkan/test/custom_ops/impl/TestSDPA.cpp index 4a59210cf9c..e23fc920a5c 100644 --- a/backends/vulkan/test/custom_ops/impl/TestSDPA.cpp +++ b/backends/vulkan/test/custom_ops/impl/TestSDPA.cpp @@ -76,6 +76,14 @@ static void test_sdpa_impl( const int32_t head_dim_size = graph.size_at(-1, q_projected); const float scale_val = 1.0f / std::sqrt(static_cast(head_dim_size)); + add_sdpa_compute_attn_weights_with_softmax_node( + graph, + q_projected, + k_cache, + input_pos_symint, + scale_val, + attn_weights_softmax); + add_sdpa_compute_attn_weights_node( graph, q_projected, From 73125c941fc5f0f35dd7911b1fb14aee6f13fdcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 20 Oct 2026 14:24:14 +0200 Subject: [PATCH 06/13] Vulkan SDPA: size the fused decode row storage to the 256-token gate The fused QK+softmax shader declared a 1024-texel shared row, 16896 bytes with the softmax reductions in fp32, over the 16384-byte minimum maxComputeSharedMemorySize. Size it to the 64 texels the host gate allows (2048 bytes total), derive the gate from that texel count, and static_assert the footprint against the Vulkan minimum. --- .../glsl/sdpa_compute_attn_weights_coop.glsl | 4 +++- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 24 +++++++++++-------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl index 7c428ef4554..2181726b070 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl @@ -36,7 +36,9 @@ $if FUSE_SOFTMAX: // Cap on the attn_weights row held in shared memory, in texels. The host only // selects this variant when the context fits within this bound (see // use_fused_qk_softmax() in SDPA.cpp), so the indexing below is in range. - #define MAX_CONTEXT_TEXEL_LEN 1024 + // Must equal kFusedSoftmaxMaxContextTexels in SDPA.cpp, which derives the + // host's context length cutoff from it. + #define MAX_CONTEXT_TEXEL_LEN 64 ${define_required_extensions(IO_STORAGE, DTYPE)} diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 44dbbc00d1c..3ac6e4e1404 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -77,11 +77,6 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { return graph->size_at(-3, q_projected) == 1; } -// Largest attn_weights row, in texels, that the fused QK+softmax shader can -// hold in shared memory. Must match MAX_CONTEXT_TEXEL_LEN in -// sdpa_compute_attn_weights_coop.glsl. -constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; - // Context length past which the separate attn-weights and softmax pair is // faster than the fused dispatch. The fused shader reduces the whole row // inside one work group, so its parallelism is capped at num_q_heads work @@ -89,12 +84,21 @@ constexpr int64_t kFusedSoftmaxMaxContextTexels = 1024; // context texel. Below the cutoff the saved dispatch and the saved round trip // of attn_weights through global memory dominate; above it the lost // parallelism does. -constexpr int64_t kFusedSoftmaxMaxContextLen = 256; - -// The cutoff also has to keep the row inside the shader's shared memory. +// +// The fused shader sizes its shared attn_weights row to exactly this cutoff: +// MAX_CONTEXT_TEXEL_LEN in sdpa_compute_attn_weights_coop.glsl must equal +// kFusedSoftmaxMaxContextTexels. Raising the cutoff means raising both. +constexpr int64_t kFusedSoftmaxMaxContextTexels = 64; +constexpr int64_t kFusedSoftmaxMaxContextLen = + kFusedSoftmaxMaxContextTexels * 4; + +// The fused shader's shared memory: four row arrays (one per texel component) +// plus the softmax helper's two 64-entry reductions, all fp32 in the worst +// case. Keep it within the 16 KiB maxComputeSharedMemorySize that Vulkan +// guarantees, so no device rejects the pipeline. static_assert( - kFusedSoftmaxMaxContextLen <= kFusedSoftmaxMaxContextTexels * 4, - "fused QK+softmax cutoff exceeds the shader's shared attn_weights row"); + (4 * kFusedSoftmaxMaxContextTexels + 2 * 64) * sizeof(float) <= 16384, + "fused QK+softmax shared memory exceeds the Vulkan minimum limit"); // Whether the decode path should use the single fused QK+softmax dispatch // instead of the separate attn-weights and softmax pair. From 56d0ed126238a4408ea54307739b47ddc63fd717 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 20 Oct 2026 14:25:07 +0200 Subject: [PATCH 07/13] Vulkan SDPA: skip separate decode QK only when a fused node exists testing.compute_attn_weight_with_kv_cache adds only the separate QK node and reads its raw output, so suppressing it on decode left stale prefill logits in attn_weights. The QK and softmax nodes now take an explicit has_fused_qk_softmax flag, carried in their resize args, and only stand down when it is set. sdpa_impl and the test_sdpa mirror set it; the raw attn-weights helper keeps the default and always dispatches. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 39 +++++++++++++------ backends/vulkan/runtime/graph/ops/impl/SDPA.h | 16 ++++++-- .../ops/benchmark/test_ops/impl/TestSDPA.cpp | 6 ++- 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 3ac6e4e1404..cf5827ef412 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -213,6 +213,15 @@ static inline SDPAMode mode_of(const std::vector& resize_args) { return static_cast(resize_args.at(3)); } +// The separate LLM QK and softmax nodes carry a fifth resize arg: whether the +// same graph also holds the fused QK+softmax node. Only then may they stand +// down on decode; a graph without it (e.g. the raw attn-weights test op) must +// keep producing scaled and masked logits. +static inline bool has_fused_qk_softmax_node( + const std::vector& resize_args) { + return resize_args.size() > 4 && resize_args.at(4) != 0; +} + // Upper bound on the GQA group size the coop-GQA shader supports; must match // MAX_GROUP_SIZE in the GQA branch of sdpa_compute_out_coop.glsl. constexpr int64_t kMaxGqaGroupSize = 8; @@ -322,8 +331,8 @@ GlobalWorkGrid pick_sdpa_qk_gwg( const ValueRef k = resize_args.at(1); const ValueRef input_pos_symint = resize_args.at(2); - // Decode is served by the single fused QK+softmax node. - if (mode == SDPAMode::LLM && + // Decode is served by the single fused QK+softmax node, if there is one. + if (mode == SDPAMode::LLM && has_fused_qk_softmax_node(resize_args) && use_fused_qk_softmax(graph, q, k, input_pos_symint)) { // The zero grid still carries the coop shader's local work group, since // the lwg picker requires one. @@ -405,8 +414,8 @@ GlobalWorkGrid pick_sdpa_softmax_gwg( const SDPAMode mode = mode_of(resize_args); const ValueRef q = resize_args.at(0); - // Decode folds this into the fused QK+softmax node. - if (mode == SDPAMode::LLM && + // Decode folds this into the fused QK+softmax node, if there is one. + if (mode == SDPAMode::LLM && has_fused_qk_softmax_node(resize_args) && use_fused_qk_softmax(graph, q, resize_args.at(1), resize_args.at(2))) { return GlobalWorkGrid( {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); @@ -633,7 +642,8 @@ void add_sdpa_compute_attn_weights_node( const ValueRef attn_mask, const float scale_val, const ValueRef attn_weights, - const SDPAMode mode) { + const SDPAMode mode, + const bool has_fused_qk_softmax) { vkapi::ParamsBindList param_ubos = { graph.sizes_ubo(q), graph.sizes_ubo(k), @@ -662,8 +672,9 @@ void add_sdpa_compute_attn_weights_node( {}, // Specialization Constants {scale_val}, - // Resize Args: [q, k, input_pos_symint_or_dummy, mode] - {q, k, input_pos_symint, mode_ref}, + // Resize Args: [q, k, input_pos_symint_or_dummy, mode, + // has_fused_qk_softmax] + {q, k, input_pos_symint, mode_ref, has_fused_qk_softmax ? 1 : 0}, // Resizing Logic resize_sdpa_attn_weights_node)); } @@ -675,7 +686,8 @@ void add_sdpa_attn_weights_softmax_node( const ValueRef k, const ValueRef input_pos_symint, const ValueRef attn_weights_softmax, - const SDPAMode mode) { + const SDPAMode mode, + const bool has_fused_qk_softmax) { std::string shader_name; if (mode == SDPAMode::LLM) { shader_name = "sdpa_attn_weights_softmax"; @@ -714,8 +726,9 @@ void add_sdpa_attn_weights_softmax_node( {}, // Specialization Constants {}, - // Resize Args: [q, k, input_pos_symint_or_dummy, mode] - {q, k, input_pos_symint, mode_ref}, + // Resize Args: [q, k, input_pos_symint_or_dummy, mode, + // has_fused_qk_softmax] + {q, k, input_pos_symint, mode_ref, has_fused_qk_softmax ? 1 : 0}, // Resizing Logic resize_sdpa_attn_weights_softmax_node)); } @@ -925,7 +938,8 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, - SDPAMode::LLM); + SDPAMode::LLM, + /*has_fused_qk_softmax=*/true); add_sdpa_attn_weights_softmax_node( graph, @@ -934,7 +948,8 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { k_cache, input_pos_symint, attn_weights_softmax, - SDPAMode::LLM); + SDPAMode::LLM, + /*has_fused_qk_softmax=*/true); add_sdpa_compute_out_node( graph, diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.h b/backends/vulkan/runtime/graph/ops/impl/SDPA.h index 33d7d2ae9ab..c076a372205 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.h +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.h @@ -25,6 +25,11 @@ namespace vkcompute { // enum class SDPAMode { LLM, FUSED }; +// has_fused_qk_softmax: the graph also holds the node added by +// add_sdpa_compute_attn_weights_with_softmax_node for the same attention. Only +// then does this node (and the matching softmax node) skip its dispatch on +// decode within the fused cutoff. Leave it false when attn_weights itself is +// the wanted output. void add_sdpa_compute_attn_weights_node( ComputeGraph& graph, const ValueRef q, @@ -33,11 +38,13 @@ void add_sdpa_compute_attn_weights_node( const ValueRef attn_mask, const float scale_val, const ValueRef attn_weights, - const SDPAMode mode); + const SDPAMode mode, + const bool has_fused_qk_softmax = false); // Decode-only fused Q @ K^T + softmax, LLM mode. It is added alongside the -// separate attn-weights and softmax nodes; their work group pickers make sure -// exactly one of the two paths dispatches for the current context length. +// separate attn-weights and softmax nodes, which must be created with +// has_fused_qk_softmax = true; their work group pickers then make sure exactly +// one of the two paths dispatches for the current context length. void add_sdpa_compute_attn_weights_with_softmax_node( ComputeGraph& graph, const ValueRef q, @@ -53,7 +60,8 @@ void add_sdpa_attn_weights_softmax_node( const ValueRef k, const ValueRef input_pos_symint, const ValueRef attn_weights_softmax, - const SDPAMode mode); + const SDPAMode mode, + const bool has_fused_qk_softmax = false); // Scalar values for the shader_override knob (see add_sdpa_compute_out_node). constexpr int64_t kShaderOverrideForceNonGqa = 0; diff --git a/backends/vulkan/test/ops/benchmark/test_ops/impl/TestSDPA.cpp b/backends/vulkan/test/ops/benchmark/test_ops/impl/TestSDPA.cpp index e23fc920a5c..6b53422c993 100644 --- a/backends/vulkan/test/ops/benchmark/test_ops/impl/TestSDPA.cpp +++ b/backends/vulkan/test/ops/benchmark/test_ops/impl/TestSDPA.cpp @@ -92,7 +92,8 @@ static void test_sdpa_impl( /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, - SDPAMode::LLM); + SDPAMode::LLM, + /*has_fused_qk_softmax=*/true); add_sdpa_attn_weights_softmax_node( graph, @@ -101,7 +102,8 @@ static void test_sdpa_impl( k_cache, input_pos_symint, attn_weights_softmax, - SDPAMode::LLM); + SDPAMode::LLM, + /*has_fused_qk_softmax=*/true); add_sdpa_compute_out_node( graph, From 3fc445046a36c45a02638516672f1cc43ae55cda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 14:06:56 +0100 Subject: [PATCH 08/13] Vulkan SDPA: select the fused decode path in one place The separate QK and softmax nodes carried a has_fused_qk_softmax flag in their resize args as a fake ValueRef, the choice was re-derived in three pickers, and the flag leaked into the public builders as default parameters. The LLM attention now builds its nodes in add_sdpa_llm_attn_weights_softmax_nodes, which gives the separate pair pickers that stand down beside the fused node, all reading use_fused_qk_softmax. The public builders are unchanged from main. The fused shader applies only the causal mask, so the fused node is only added when there is no attn_mask. Add kShaderOverrideForceSeparateQkSoftmax and a separate_qk_softmax benchmark route, which serve a short decode context with the separate pair, to A/B the fusion on one shape. The AV path treats it as auto. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 423 +++++++++++------- backends/vulkan/runtime/graph/ops/impl/SDPA.h | 29 +- .../operators/attention/sdpa/SdpaRoutes.cpp | 8 +- 3 files changed, 271 insertions(+), 189 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index a4171c88a6b..dddb44a4186 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -83,11 +83,14 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { // groups; the separate pair spreads the same work over one work group per // context texel. Below the cutoff the saved dispatch and the saved round trip // of attn_weights through global memory dominate; above it the lost -// parallelism does. +// parallelism does. Measured on Adreno 840 only (Qwen3-0.6B, crossover near +// 220 tokens); kShaderOverrideForceSeparateQkSoftmax A/Bs the two paths on one +// shape. // -// The fused shader sizes its shared attn_weights row to exactly this cutoff: -// MAX_CONTEXT_TEXEL_LEN in sdpa_compute_attn_weights_coop.glsl must equal -// kFusedSoftmaxMaxContextTexels. Raising the cutoff means raising both. +// The fused shader also sizes its shared attn_weights row to this cutoff: its +// MAX_CONTEXT_TEXEL_LEN parameter in sdpa_compute_attn_weights_coop.yaml must +// equal kFusedSoftmaxMaxContextTexels, and the shader writes nothing for a +// longer context. constexpr int64_t kFusedSoftmaxMaxContextTexels = 64; constexpr int64_t kFusedSoftmaxMaxContextLen = kFusedSoftmaxMaxContextTexels * 4; @@ -100,30 +103,6 @@ static_assert( (4 * kFusedSoftmaxMaxContextTexels + 2 * 64) * sizeof(float) <= 16384, "fused QK+softmax shared memory exceeds the Vulkan minimum limit"); -// Whether the decode path should use the single fused QK+softmax dispatch -// instead of the separate attn-weights and softmax pair. -// -// All three nodes are added to the graph, because which one is wanted depends -// on the sequence length, and that is only known once sizes are current: a -// dynamic-shape export reports the max bound at graph build time, never 1. -// Each node's global work group picker calls this and collapses to a zero work -// group when it is not the chosen path, which DispatchNode::encode skips. -// Pickers are re-run from DynamicDispatchNode::trigger_resize, so the choice -// is re-made every token and follows the context length as it grows. -bool use_fused_qk_softmax( - ComputeGraph* graph, - const ValueRef q, - const ValueRef k, - const ValueRef input_pos_symint) { - if (!is_single_token(graph, q)) { - return false; - } - const int64_t context_len = - compute_sdpa_dims(*graph, q, k, input_pos_symint, SDPAMode::LLM) - .context_len; - return context_len <= kFusedSoftmaxMaxContextLen; -} - // // Resize functions // @@ -213,15 +192,6 @@ static inline SDPAMode mode_of(const std::vector& resize_args) { return static_cast(resize_args.at(3)); } -// The separate LLM QK and softmax nodes carry a fifth resize arg: whether the -// same graph also holds the fused QK+softmax node. Only then may they stand -// down on decode; a graph without it (e.g. the raw attn-weights test op) must -// keep producing scaled and masked logits. -static inline bool has_fused_qk_softmax_node( - const std::vector& resize_args) { - return resize_args.size() > 4 && resize_args.at(4) != 0; -} - // Upper bound on the GQA group size the coop-GQA shader supports; must match // MAX_GROUP_SIZE in the GQA branch of sdpa_compute_out_coop.glsl. constexpr int64_t kMaxGqaGroupSize = 8; @@ -248,13 +218,16 @@ bool use_gqa_av_coop( // Resolve whether the AV decode path uses the GQA-reuse coop shader, honoring // the test-only shader_override knob (see SDPA.h): auto selects via // use_gqa_av_coop; kShaderOverrideForceNonGqa forces off; any other value -// forces the GQA family on. +// except kShaderOverrideForceSeparateQkSoftmax, which only concerns the QK and +// softmax nodes, forces the GQA family on. bool resolve_use_gqa( ComputeGraph* graph, const ValueRef shader_override, const int64_t num_q_heads, const int64_t num_kv_heads) { - if (shader_override == kDummyValueRef) { + if (shader_override == kDummyValueRef || + graph->extract_scalar(shader_override) == + kShaderOverrideForceSeparateQkSoftmax) { return use_gqa_av_coop(graph, num_q_heads, num_kv_heads); } const bool force_gqa = graph->extract_scalar(shader_override) != @@ -330,16 +303,6 @@ GlobalWorkGrid pick_sdpa_qk_gwg( const ValueRef q = resize_args.at(0); const ValueRef k = resize_args.at(1); const ValueRef input_pos_symint = resize_args.at(2); - - // Decode is served by the single fused QK+softmax node, if there is one. - if (mode == SDPAMode::LLM && has_fused_qk_softmax_node(resize_args) && - use_fused_qk_softmax(graph, q, k, input_pos_symint)) { - // The zero grid still carries the coop shader's local work group, since - // the lwg picker requires one. - return GlobalWorkGrid( - {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(1u, 64u, 1u)); - } - const SDPADims d = compute_sdpa_dims(*graph, q, k, input_pos_symint, mode); // Dispatch grid: (context_len tiles, S tiles, H * B). @@ -368,43 +331,6 @@ LocalWorkGroup pick_sdpa_qk_lwg( return default_pick_lwg(graph, shader, gwg, args, resize_args); } -vkapi::ShaderInfo pick_sdpa_qk_softmax_shader( - ComputeGraph* graph, - const std::vector& args, - const std::vector& resize_args) { - (void)resize_args; - const ValueRef q = args.at(1).refs.at(0); - const ValueRef k = args.at(1).refs.at(1); - - std::string shader_name = "sdpa_compute_attn_weights_coop_softmax"; - add_storage_type_suffix(shader_name, graph->storage_type_of(q)); - add_storage_type_suffix(shader_name, graph->storage_type_of(k)); - add_dtype_suffix(shader_name, graph->dtype_of(q)); - return VK_KERNEL_FROM_STR(shader_name); -} - -GlobalWorkGrid pick_sdpa_qk_softmax_gwg( - ComputeGraph* graph, - const vkapi::ShaderInfo& shader, - const std::vector& args, - const std::vector& resize_args) { - (void)shader; - (void)args; - const ValueRef q = resize_args.at(0); - const ValueRef k = resize_args.at(1); - - // Prefill, and decode past the cutoff, are served by the separate nodes. - if (!use_fused_qk_softmax(graph, q, k, resize_args.at(2))) { - return GlobalWorkGrid( - {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); - } - - const uint32_t num_q_heads = graph->size_at(-2, q); - const uint32_t seq_len = graph->size_at(-3, q); - return GlobalWorkGrid( - {1u, seq_len, num_q_heads}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); -} - GlobalWorkGrid pick_sdpa_softmax_gwg( ComputeGraph* graph, const vkapi::ShaderInfo& shader, @@ -413,14 +339,6 @@ GlobalWorkGrid pick_sdpa_softmax_gwg( (void)shader; const SDPAMode mode = mode_of(resize_args); const ValueRef q = resize_args.at(0); - - // Decode folds this into the fused QK+softmax node, if there is one. - if (mode == SDPAMode::LLM && has_fused_qk_softmax_node(resize_args) && - use_fused_qk_softmax(graph, q, resize_args.at(1), resize_args.at(2))) { - return GlobalWorkGrid( - {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); - } - // LLM reads H from axis -2, fused from axis -3 (handled by // compute_sdpa_dims). const int64_t num_q_heads = (mode == SDPAMode::LLM) @@ -607,45 +525,9 @@ void add_sdpa_kv_cache_update_node( // kDummyValueRef to indicate no bias. scale_val is always passed as // a spec const; the LLM path computes it per head_dim and FUSED may // inherit from the caller-supplied scale. -// Decode-only fused Q @ K^T + softmax. Writes normalized weights straight to -// attn_weights_softmax, removing the separate softmax dispatch and the round -// trip through attn_weights. LLM mode only. -void add_sdpa_compute_attn_weights_with_softmax_node( - ComputeGraph& graph, - const ValueRef q, - const ValueRef k, - const ValueRef input_pos_symint, - const float scale_val, - const ValueRef attn_weights_softmax) { - vkapi::ParamsBindList param_ubos = { - graph.sizes_ubo(q), - graph.sizes_ubo(k), - graph.get_or_create_int_param_buffer(input_pos_symint), - }; - - const ValueRef mode_ref = static_cast(SDPAMode::LLM); - - graph.execute_nodes().emplace_back(new DynamicDispatchNode( - graph, - pick_sdpa_qk_softmax_shader, - pick_sdpa_qk_softmax_gwg, - pick_required_lwg, - // Inputs and Outputs - {{attn_weights_softmax, vkapi::kWrite}, {{q, k}, vkapi::kRead}}, - // Shader param buffers - param_ubos, - // Push Constants - {}, - // Specialization Constants - {scale_val}, - // Resize Args: [q, k, input_pos_symint, mode] - {q, k, input_pos_symint, mode_ref}, - // Resizing Logic: the output has the attn_weights shape, and args[1] - // holds {q, k}, not an attn_weights tensor to copy the shape from. - resize_sdpa_attn_weights_node)); -} - -void add_sdpa_compute_attn_weights_node( +// Shared by add_sdpa_compute_attn_weights_node and the LLM attention with a +// fused decode node, which passes its own global work group picker. +void add_sdpa_compute_attn_weights_node_impl( ComputeGraph& graph, const ValueRef q, const ValueRef k, @@ -654,7 +536,8 @@ void add_sdpa_compute_attn_weights_node( const float scale_val, const ValueRef attn_weights, const SDPAMode mode, - const bool has_fused_qk_softmax) { + const DynamicDispatchNode::PickGwgFn& pick_gwg, + const ValueRef shader_override) { vkapi::ParamsBindList param_ubos = { graph.sizes_ubo(q), graph.sizes_ubo(k), @@ -673,7 +556,7 @@ void add_sdpa_compute_attn_weights_node( graph.execute_nodes().emplace_back(new DynamicDispatchNode( graph, pick_sdpa_qk_shader, - pick_sdpa_qk_gwg, + pick_gwg, pick_sdpa_qk_lwg, // Inputs and Outputs {{attn_weights, vkapi::kWrite}, {read_inputs, vkapi::kRead}}, @@ -684,13 +567,37 @@ void add_sdpa_compute_attn_weights_node( // Specialization Constants {scale_val}, // Resize Args: [q, k, input_pos_symint_or_dummy, mode, - // has_fused_qk_softmax] - {q, k, input_pos_symint, mode_ref, has_fused_qk_softmax ? 1 : 0}, + // shader_override_or_dummy] + {q, k, input_pos_symint, mode_ref, shader_override}, // Resizing Logic resize_sdpa_attn_weights_node)); } -void add_sdpa_attn_weights_softmax_node( +void add_sdpa_compute_attn_weights_node( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const ValueRef attn_mask, + const float scale_val, + const ValueRef attn_weights, + const SDPAMode mode) { + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + attn_mask, + scale_val, + attn_weights, + mode, + pick_sdpa_qk_gwg, + kDummyValueRef); +} + +// Shared by add_sdpa_attn_weights_softmax_node and the LLM attention with a +// fused decode node, which passes its own global work group picker. +void add_sdpa_attn_weights_softmax_node_impl( ComputeGraph& graph, const ValueRef attn_weights, const ValueRef q, @@ -698,7 +605,8 @@ void add_sdpa_attn_weights_softmax_node( const ValueRef input_pos_symint, const ValueRef attn_weights_softmax, const SDPAMode mode, - const bool has_fused_qk_softmax) { + const DynamicDispatchNode::PickGwgFn& pick_gwg, + const ValueRef shader_override) { std::string shader_name; if (mode == SDPAMode::LLM) { shader_name = "sdpa_attn_weights_softmax"; @@ -727,7 +635,7 @@ void add_sdpa_attn_weights_softmax_node( graph.execute_nodes().emplace_back(new DynamicDispatchNode( graph, VK_KERNEL_FROM_STR(shader_name), - pick_sdpa_softmax_gwg, + pick_gwg, pick_required_lwg, // Inputs and Outputs {{attn_weights_softmax, vkapi::kWrite}, {attn_weights, vkapi::kRead}}, @@ -738,12 +646,216 @@ void add_sdpa_attn_weights_softmax_node( // Specialization Constants {}, // Resize Args: [q, k, input_pos_symint_or_dummy, mode, - // has_fused_qk_softmax] - {q, k, input_pos_symint, mode_ref, has_fused_qk_softmax ? 1 : 0}, + // shader_override_or_dummy] + {q, k, input_pos_symint, mode_ref, shader_override}, // Resizing Logic resize_sdpa_attn_weights_softmax_node)); } +void add_sdpa_attn_weights_softmax_node( + ComputeGraph& graph, + const ValueRef attn_weights, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const ValueRef attn_weights_softmax, + const SDPAMode mode) { + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + mode, + pick_sdpa_softmax_gwg, + kDummyValueRef); +} + +// +// Fused decode QK+softmax +// +// An LLM attention without an attn_mask also gets a decode-only node that +// computes Q @ K^T and the softmax in one dispatch. All three nodes are built, +// because the sequence length is only known once sizes are current: a +// dynamic-shape export reports the max bound at graph build time, never 1. +// Their global work group pickers are re-run from +// DynamicDispatchNode::trigger_resize, so the choice below is re-made every +// token, and the nodes not serving the current step get a zero grid, which +// DispatchNode::encode skips. A zero grid still carries the node's local work +// group, since the lwg picker requires one. All three nodes take the resize +// args [q, k, input_pos_symint, mode, shader_override_or_dummy]. +// + +// Whether the fused node, rather than the separate attn-weights and softmax +// pair, serves the current step. +bool use_fused_qk_softmax( + ComputeGraph* graph, + const std::vector& resize_args) { + const ValueRef q = resize_args.at(0); + const ValueRef k = resize_args.at(1); + const ValueRef input_pos_symint = resize_args.at(2); + const ValueRef shader_override = resize_args.at(4); + if (!is_single_token(graph, q)) { + return false; + } + if (shader_override != kDummyValueRef && + graph->extract_scalar(shader_override) == + kShaderOverrideForceSeparateQkSoftmax) { + return false; + } + const int64_t context_len = + compute_sdpa_dims(*graph, q, k, input_pos_symint, SDPAMode::LLM) + .context_len; + return context_len <= kFusedSoftmaxMaxContextLen; +} + +vkapi::ShaderInfo pick_sdpa_qk_softmax_shader( + ComputeGraph* graph, + const std::vector& args, + const std::vector& resize_args) { + (void)resize_args; + const ValueRef q = args.at(1).refs.at(0); + const ValueRef k = args.at(1).refs.at(1); + + std::string shader_name = "sdpa_compute_attn_weights_coop_softmax"; + add_storage_type_suffix(shader_name, graph->storage_type_of(q)); + add_storage_type_suffix(shader_name, graph->storage_type_of(k)); + add_dtype_suffix(shader_name, graph->dtype_of(q)); + return VK_KERNEL_FROM_STR(shader_name); +} + +GlobalWorkGrid pick_sdpa_qk_softmax_gwg( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + (void)shader; + (void)args; + const LocalWorkGroup lwg(64u, 1u, 1u); + if (!use_fused_qk_softmax(graph, resize_args)) { + return GlobalWorkGrid({0u, 0u, 0u}, kTiledWorkGrid, lwg); + } + const ValueRef q = resize_args.at(0); + const uint32_t num_q_heads = graph->size_at(-2, q); + const uint32_t seq_len = graph->size_at(-3, q); + return GlobalWorkGrid({1u, seq_len, num_q_heads}, kTiledWorkGrid, lwg); +} + +// The separate pair stands down whenever the fused node serves the step. +GlobalWorkGrid pick_sdpa_qk_gwg_beside_fused_decode( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + if (use_fused_qk_softmax(graph, resize_args)) { + // The coop shader's local work group + return GlobalWorkGrid( + {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(1u, 64u, 1u)); + } + return pick_sdpa_qk_gwg(graph, shader, args, resize_args); +} + +GlobalWorkGrid pick_sdpa_softmax_gwg_beside_fused_decode( + ComputeGraph* graph, + const vkapi::ShaderInfo& shader, + const std::vector& args, + const std::vector& resize_args) { + if (use_fused_qk_softmax(graph, resize_args)) { + return GlobalWorkGrid( + {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); + } + return pick_sdpa_softmax_gwg(graph, shader, args, resize_args); +} + +// Adds the attn-weights and softmax nodes of an LLM attention, and the fused +// decode node unless there is an attn_mask, which the fused shader does not +// apply. +void add_sdpa_llm_attn_weights_softmax_nodes( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k, + const ValueRef input_pos_symint, + const ValueRef attn_mask, + const float scale_val, + const ValueRef attn_weights, + const ValueRef attn_weights_softmax, + const ValueRef shader_override) { + const bool has_fused_decode_node = !is_valid(attn_mask); + if (!has_fused_decode_node) { + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + attn_mask, + scale_val, + attn_weights, + SDPAMode::LLM, + pick_sdpa_qk_gwg, + shader_override); + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + SDPAMode::LLM, + pick_sdpa_softmax_gwg, + shader_override); + return; + } + + const ValueRef mode_ref = static_cast(SDPAMode::LLM); + + // Writes normalized weights straight to attn_weights_softmax, removing the + // softmax dispatch and the round trip through attn_weights. + graph.execute_nodes().emplace_back(new DynamicDispatchNode( + graph, + pick_sdpa_qk_softmax_shader, + pick_sdpa_qk_softmax_gwg, + pick_required_lwg, + // Inputs and Outputs + {{attn_weights_softmax, vkapi::kWrite}, {{q, k}, vkapi::kRead}}, + // Shader param buffers + {graph.sizes_ubo(q), + graph.sizes_ubo(k), + graph.get_or_create_int_param_buffer(input_pos_symint)}, + // Push Constants + {}, + // Specialization Constants + {scale_val}, + // Resize Args + {q, k, input_pos_symint, mode_ref, shader_override}, + // Resizing Logic: the output has the attn_weights shape, and args[1] + // holds {q, k}, not an attn_weights tensor to copy the shape from. + resize_sdpa_attn_weights_node)); + + add_sdpa_compute_attn_weights_node_impl( + graph, + q, + k, + input_pos_symint, + /*attn_mask=*/kDummyValueRef, + scale_val, + attn_weights, + SDPAMode::LLM, + pick_sdpa_qk_gwg_beside_fused_decode, + shader_override); + + add_sdpa_attn_weights_softmax_node_impl( + graph, + attn_weights, + q, + k, + input_pos_symint, + attn_weights_softmax, + SDPAMode::LLM, + pick_sdpa_softmax_gwg_beside_fused_decode, + shader_override); +} + void add_sdpa_compute_out_node( ComputeGraph& graph, const ValueRef attn_weights_softmax, @@ -932,20 +1044,7 @@ void sdpa_impl_with_shader_override( ? 1.0f / std::sqrt(static_cast(head_dim_size)) : graph.extract_scalar(scale); - // Decode (S == 1) is served by a single fused QK+softmax dispatch, prefill by - // the separate pair below. Both are built: the sequence length is only known - // once sizes are current, since a dynamic-shape export reports the max bound - // at graph build time. Each node's global work group picker collapses to zero - // when it is not the chosen path, and DispatchNode::encode skips it. - add_sdpa_compute_attn_weights_with_softmax_node( - graph, - q_projected, - k_cache, - input_pos_symint, - scale_val, - attn_weights_softmax); - - add_sdpa_compute_attn_weights_node( + add_sdpa_llm_attn_weights_softmax_nodes( graph, q_projected, k_cache, @@ -953,18 +1052,8 @@ void sdpa_impl_with_shader_override( /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, - SDPAMode::LLM, - /*has_fused_qk_softmax=*/true); - - add_sdpa_attn_weights_softmax_node( - graph, - attn_weights, - q_projected, - k_cache, - input_pos_symint, attn_weights_softmax, - SDPAMode::LLM, - /*has_fused_qk_softmax=*/true); + shader_override); add_sdpa_compute_out_node( graph, diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.h b/backends/vulkan/runtime/graph/ops/impl/SDPA.h index ac00f958e83..79a5d7ba252 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.h +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.h @@ -30,11 +30,6 @@ void sdpa_impl_with_shader_override( const std::vector& args, ValueRef shader_override); -// has_fused_qk_softmax: the graph also holds the node added by -// add_sdpa_compute_attn_weights_with_softmax_node for the same attention. Only -// then does this node (and the matching softmax node) skip its dispatch on -// decode within the fused cutoff. Leave it false when attn_weights itself is -// the wanted output. void add_sdpa_compute_attn_weights_node( ComputeGraph& graph, const ValueRef q, @@ -43,20 +38,7 @@ void add_sdpa_compute_attn_weights_node( const ValueRef attn_mask, const float scale_val, const ValueRef attn_weights, - const SDPAMode mode, - const bool has_fused_qk_softmax = false); - -// Decode-only fused Q @ K^T + softmax, LLM mode. It is added alongside the -// separate attn-weights and softmax nodes, which must be created with -// has_fused_qk_softmax = true; their work group pickers then make sure exactly -// one of the two paths dispatches for the current context length. -void add_sdpa_compute_attn_weights_with_softmax_node( - ComputeGraph& graph, - const ValueRef q, - const ValueRef k, - const ValueRef input_pos_symint, - const float scale_val, - const ValueRef attn_weights_softmax); + const SDPAMode mode); void add_sdpa_attn_weights_softmax_node( ComputeGraph& graph, @@ -65,14 +47,14 @@ void add_sdpa_attn_weights_softmax_node( const ValueRef k, const ValueRef input_pos_symint, const ValueRef attn_weights_softmax, - const SDPAMode mode, - const bool has_fused_qk_softmax = false); + const SDPAMode mode); // Scalar values for the shader_override knob (see add_sdpa_compute_out_node). constexpr int64_t kShaderOverrideForceNonGqa = 0; constexpr int64_t kShaderOverrideForceGqa = 1; constexpr int64_t kShaderOverrideForceTile2 = 2; constexpr int64_t kShaderOverrideForceBase = 3; +constexpr int64_t kShaderOverrideForceSeparateQkSoftmax = 4; // shader_override: test-only knob selecting the single-token decode AV shader. // It is a ValueRef holding one of the kShaderOverride* int64 scalars above, or @@ -88,6 +70,11 @@ constexpr int64_t kShaderOverrideForceBase = 3; // variant (tile2 on Adreno). // kShaderOverrideForceTile2 — force the tiled variant regardless of vendor. // kShaderOverrideForceBase — force the base variant regardless of vendor. +// kShaderOverrideForceSeparateQkSoftmax — keep the decode AV shader on auto, +// but serve a short decode context with the +// separate attn-weights and softmax nodes instead +// of the fused QK+softmax node, to A/B the fusion +// on one shape. Only sdpa_impl reads it. // Lets the benchmark/test exercise every AV shader on the same shape, and gives // the Adreno-only tile2 variant deterministic coverage on any device. Forcing // the GQA family requires a GQA-eligible shape (Hq divisible by Hkv, group size diff --git a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp index 8df993ff582..843c0ddef78 100644 --- a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp +++ b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/SdpaRoutes.cpp @@ -24,7 +24,9 @@ Json build_sdpa_route( const char* name = Override == kShaderOverrideForceGqa ? "gqa" : Override == kShaderOverrideForceTile2 ? "gqa_tile2" : Override == kShaderOverrideForceBase ? "gqa_base" - : "non_gqa"; + : Override == kShaderOverrideForceSeparateQkSoftmax + ? "separate_qk_softmax" + : "non_gqa"; return {{"name", name}, {"options", options}}; } @@ -45,6 +47,10 @@ REGISTER_OPERATOR_ROUTES { llama.custom_sdpa.default, gqa_base, (build_sdpa_route)); + REGISTER_OPERATOR_ROUTE( + llama.custom_sdpa.default, + separate_qk_softmax, + (build_sdpa_route)); } } // namespace From b663d9a2fee4aabeb55751d1059d44b8af9fbba2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 14:06:57 +0100 Subject: [PATCH 09/13] Vulkan SDPA: bound the fused decode row in the shader The shared attn_weights row size came from a #define that only a comment tied to the host cutoff, and nothing on the device kept a longer context from writing past the row. Make MAX_CONTEXT_TEXEL_LEN a YAML parameter and have the whole work group return for a context that does not fit. Read the loop invariant sizes in compute_attn_weight_tile() instead of passing them, and note why the row is split per component. --- .../glsl/sdpa_compute_attn_weights_coop.glsl | 50 ++++++++----------- .../glsl/sdpa_compute_attn_weights_coop.yaml | 3 ++ 2 files changed, 24 insertions(+), 29 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl index 31692aecf16..79313281e64 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl @@ -35,10 +35,8 @@ $if FUSE_SOFTMAX: #define FUSE_SOFTMAX // Cap on the attn_weights row held in shared memory, in texels. The host only // selects this variant when the context fits within this bound (see - // use_fused_qk_softmax() in SDPA.cpp), so the indexing below is in range. - // Must equal kFusedSoftmaxMaxContextTexels in SDPA.cpp, which derives the - // host's context length cutoff from it. - #define MAX_CONTEXT_TEXEL_LEN 64 + // use_fused_qk_softmax() in SDPA.cpp); a longer context writes nothing. + #define MAX_CONTEXT_TEXEL_LEN ${MAX_CONTEXT_TEXEL_LEN} ${define_required_extensions(IO_STORAGE, DTYPE)} @@ -65,7 +63,8 @@ ${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} #ifdef FUSE_SOFTMAX -// The scaled and masked attn_weights row, one array per texel component. +// The scaled and masked attn_weights row, one array per texel component, so +// that the workers, which each own one texel, access consecutive words. shared T row_attn_w_x[MAX_CONTEXT_TEXEL_LEN]; shared T row_attn_w_y[MAX_CONTEXT_TEXEL_LEN]; shared T row_attn_w_z[MAX_CONTEXT_TEXEL_LEN]; @@ -121,13 +120,16 @@ bool compute_attn_weight_tile( const int s, const int q_h, const int kv_h, - const int D4, - const int D, - const int S, - const int Q_H, - const int context_len, - const int C, - const int KV_H) { + const int context_len) { + // head dim, sequence length, number of Q heads, max context length and + // number of K heads + const int D = q_sizes.x; + const int D4 = div_up_4(D); + const int S = q_sizes.z; + const int Q_H = q_sizes.y; + const int C = k_sizes.z; + const int KV_H = k_sizes.y; + initialize(out_tile); FPInputTile q_tile; @@ -213,10 +215,6 @@ void main() { // idx along output num_q_heads dim const int q_h = int(gl_GlobalInvocationID.z); - // head dimension - const int D = q_sizes.x; - // texel size of head_dim, over which the dot product is accumulated - const int D4 = div_up_4(D); // number of Q heads const int Q_H = q_sizes.y; // sequence length @@ -225,9 +223,6 @@ void main() { // number of K/V heads const int KV_H = k_sizes.y; - // Max context length - const int C = k_sizes.z; - const int C4 = div_up_4(C); int kv_h = q_h; if (KV_H < Q_H) { @@ -239,8 +234,11 @@ void main() { const int context_texel_len = div_up_4(context_len); #ifdef FUSE_SOFTMAX - // bounds check - if (s >= S || q_h >= Q_H) { + // bounds check. A context longer than the shared row is never selected by + // the host; if it is dispatched anyway, write nothing rather than overrun the + // row. s and q_h are uniform over the work group, so the whole work group + // returns together and the barriers below stay uniform. + if (s >= S || q_h >= Q_H || context_texel_len > MAX_CONTEXT_TEXEL_LEN) { return; } @@ -251,7 +249,7 @@ void main() { FPOutTile out_tile; const bool tile_in_mask_region = compute_attn_weight_tile( - out_tile, 0, 1, c, s, q_h, kv_h, D4, D, S, Q_H, context_len, C, KV_H); + out_tile, 0, 1, c, s, q_h, kv_h, context_len); if (!tile_in_mask_region) { VEC4_T inv_scale_vec = VEC4_T(inv_scale); apply_scale_and_mask(out_tile, inv_scale_vec, input_pos, c, s); @@ -283,13 +281,7 @@ void main() { s, q_h, kv_h, - D4, - D, - S, - Q_H, - context_len, - C, - KV_H); + context_len); partial_sums[worker_id] = out_tile; diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml index 479a47d01c8..482cc307488 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml @@ -12,6 +12,9 @@ sdpa_compute_attn_weights_coop: TILE_K4: 1 TILE_N4: 1 FUSE_SOFTMAX: false + # Shared attn_weights row of the FUSE_SOFTMAX variant, in texels. Must equal + # kFusedSoftmaxMaxContextTexels in SDPA.cpp. + MAX_CONTEXT_TEXEL_LEN: 64 generate_variant_forall: combination: parameter_names: [IO_STORAGE, K_CACHE_STORAGE] From e6261fa001af6fd8fbc14d00097596a0682a9e28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 14:06:57 +0100 Subject: [PATCH 10/13] Vulkan SDPA: test decode across the fused QK+softmax cutoff Every KV cache decode test stayed under 256 tokens of context, so only the fused node was exercised on decode. Add op tests whose decode steps cross the cutoff, in fp16 and with an unaligned head dim, and benchmark correctness cases at contexts 255 to 257 for both routes and storages. --- backends/vulkan/test/op_tests/sdpa_test.cpp | 18 +++ .../attention/sdpa/cases/correctness.json | 144 ++++++++++++++++++ 2 files changed, 162 insertions(+) diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 0a1cd408ca1..4ca1474c585 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -1124,6 +1124,24 @@ TEST(VulkanSDPATest, test_sdpa_op_unaligned_head_dim) { test_vulkan_sdpa(0, {3, 1, 1, 2}, head_dim, num_heads, num_kv_heads, 1); } +// Decode within 256 tokens of context is served by the fused QK+softmax node, +// and beyond it by the separate attn-weights and softmax pair. These decode +// steps cross that cutoff, so one graph switches paths on resize. +const std::vector kDecodeAcrossFusedCutoff = + {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff) { + test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 64, 8, 2, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_fp16) { + test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 64, 8, 2, 1, at::kHalf); +} + +TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_unaligned_dim) { + test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 6, 4, 2, 1); +} + // q, k and v arrive with NaN in their head_dim padding, as when the ops that // produce them leave padding unwritten. Only the logical head_dim may be read. void test_vulkan_sdpa_ignores_head_dim_padding(const int seq_len) { diff --git a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json index 3b22b6e78aa..8c43cfc9fa6 100644 --- a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json +++ b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json @@ -449,5 +449,149 @@ {"tensor": {"name": "output", "sizes": [1, 1, 32, 64], "dtype": "float16", "storage": "texture3d", "layout": "width", "data": {"fill": 0}}} ] ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P254 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 254}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P255 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 255}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P256 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 256}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P254 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 254}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P255 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 255}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa fused_qk_softmax_cutoff decode D64 H8 Hkv2 S1 C320 P256 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 320, 2, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 256}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] } ] From 82866824149dc4adae8680efbd67e9429337ef5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 3 Dec 2026 10:10:32 +0100 Subject: [PATCH 11/13] Vulkan SDPA: use the fused decode path only up to head_dim 64 The fused QK+softmax shader loops serially over the head dim, and on Adreno 840 it was slower than the separate pair for D128 and D256 at every context length. Build the fused node only for head_dim <= 64. Drop the unreachable attn_mask branch, and derive the zero grids' local work group from the regular pickers. Test D128 and D256 short decode. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 49 ++++++---- backends/vulkan/test/op_tests/sdpa_test.cpp | 20 ++++ .../attention/sdpa/cases/correctness.json | 96 +++++++++++++++++++ 3 files changed, 146 insertions(+), 19 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index dddb44a4186..5cd25769ae0 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -87,6 +87,12 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { // 220 tokens); kShaderOverrideForceSeparateQkSoftmax A/Bs the two paths on one // shape. // +// Each fused worker also loops serially over the whole head dim, while the +// separate pair splits it across the work group, so the fused path loses as +// head_dim grows: on Adreno 840 it was slower for D128 and D256 at every +// context length. It is used only up to kFusedSoftmaxMaxHeadDim until a +// multi-device sweep shows otherwise. +// // The fused shader also sizes its shared attn_weights row to this cutoff: its // MAX_CONTEXT_TEXEL_LEN parameter in sdpa_compute_attn_weights_coop.yaml must // equal kFusedSoftmaxMaxContextTexels, and the shader writes nothing for a @@ -94,6 +100,7 @@ bool is_single_token(ComputeGraph* graph, const ValueRef& q_projected) { constexpr int64_t kFusedSoftmaxMaxContextTexels = 64; constexpr int64_t kFusedSoftmaxMaxContextLen = kFusedSoftmaxMaxContextTexels * 4; +constexpr int64_t kFusedSoftmaxMaxHeadDim = 64; // The fused shader's shared memory: four row arrays (one per texel component) // plus the softmax helper's two 64-entry reductions, all fp32 in the worst @@ -675,10 +682,11 @@ void add_sdpa_attn_weights_softmax_node( // // Fused decode QK+softmax // -// An LLM attention without an attn_mask also gets a decode-only node that -// computes Q @ K^T and the softmax in one dispatch. All three nodes are built, -// because the sequence length is only known once sizes are current: a -// dynamic-shape export reports the max bound at graph build time, never 1. +// An LLM attention with head_dim <= kFusedSoftmaxMaxHeadDim also gets a +// decode-only node that computes Q @ K^T and the softmax in one dispatch. All +// three nodes are built, because the sequence length is only known once sizes +// are current: a dynamic-shape export reports the max bound at graph build +// time, never 1. // Their global work group pickers are re-run from // DynamicDispatchNode::trigger_resize, so the choice below is re-made every // token, and the nodes not serving the current step get a zero grid, which @@ -696,7 +704,8 @@ bool use_fused_qk_softmax( const ValueRef k = resize_args.at(1); const ValueRef input_pos_symint = resize_args.at(2); const ValueRef shader_override = resize_args.at(4); - if (!is_single_token(graph, q)) { + if (!is_single_token(graph, q) || + graph->size_at(-1, q) > kFusedSoftmaxMaxHeadDim) { return false; } if (shader_override != kDummyValueRef && @@ -742,18 +751,23 @@ GlobalWorkGrid pick_sdpa_qk_softmax_gwg( return GlobalWorkGrid({1u, seq_len, num_q_heads}, kTiledWorkGrid, lwg); } +// A grid that DispatchNode::encode skips, keeping the picker's intent and +// required local work group. +GlobalWorkGrid zero_grid_of(const GlobalWorkGrid& gwg) { + return GlobalWorkGrid({0u, 0u, 0u}, gwg.intent(), gwg.required_lwg_size()); +} + // The separate pair stands down whenever the fused node serves the step. GlobalWorkGrid pick_sdpa_qk_gwg_beside_fused_decode( ComputeGraph* graph, const vkapi::ShaderInfo& shader, const std::vector& args, const std::vector& resize_args) { + GlobalWorkGrid gwg = pick_sdpa_qk_gwg(graph, shader, args, resize_args); if (use_fused_qk_softmax(graph, resize_args)) { - // The coop shader's local work group - return GlobalWorkGrid( - {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(1u, 64u, 1u)); + return zero_grid_of(gwg); } - return pick_sdpa_qk_gwg(graph, shader, args, resize_args); + return gwg; } GlobalWorkGrid pick_sdpa_softmax_gwg_beside_fused_decode( @@ -761,34 +775,32 @@ GlobalWorkGrid pick_sdpa_softmax_gwg_beside_fused_decode( const vkapi::ShaderInfo& shader, const std::vector& args, const std::vector& resize_args) { + GlobalWorkGrid gwg = pick_sdpa_softmax_gwg(graph, shader, args, resize_args); if (use_fused_qk_softmax(graph, resize_args)) { - return GlobalWorkGrid( - {0u, 0u, 0u}, kTiledWorkGrid, LocalWorkGroup(64u, 1u, 1u)); + return zero_grid_of(gwg); } - return pick_sdpa_softmax_gwg(graph, shader, args, resize_args); + return gwg; } // Adds the attn-weights and softmax nodes of an LLM attention, and the fused -// decode node unless there is an attn_mask, which the fused shader does not -// apply. +// decode node when head_dim allows it. The fused shader applies no attn_mask, +// so a masked attention must not come through here. void add_sdpa_llm_attn_weights_softmax_nodes( ComputeGraph& graph, const ValueRef q, const ValueRef k, const ValueRef input_pos_symint, - const ValueRef attn_mask, const float scale_val, const ValueRef attn_weights, const ValueRef attn_weights_softmax, const ValueRef shader_override) { - const bool has_fused_decode_node = !is_valid(attn_mask); - if (!has_fused_decode_node) { + if (graph.size_at(-1, q) > kFusedSoftmaxMaxHeadDim) { add_sdpa_compute_attn_weights_node_impl( graph, q, k, input_pos_symint, - attn_mask, + /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, SDPAMode::LLM, @@ -1049,7 +1061,6 @@ void sdpa_impl_with_shader_override( q_projected, k_cache, input_pos_symint, - /*attn_mask=*/kDummyValueRef, scale_val, attn_weights, attn_weights_softmax, diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 4ca1474c585..508d4cd69ad 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -1142,6 +1142,26 @@ TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_unaligned_dim) { test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 6, 4, 2, 1); } +// Above a head_dim of 64 the fused node is not built, so the separate pair +// serves every decode step, including a short context. +const std::vector kShortDecode = {1, 1, 1, 1}; + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128) { + test_vulkan_sdpa(10, kShortDecode, 128, 8, 2, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128_fp16) { + test_vulkan_sdpa(10, kShortDecode, 128, 8, 2, 1, at::kHalf); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256) { + test_vulkan_sdpa(10, kShortDecode, 256, 8, 1, 1); +} + +TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256_fp16) { + test_vulkan_sdpa(10, kShortDecode, 256, 8, 1, 1, at::kHalf); +} + // q, k and v arrive with NaN in their head_dim padding, as when the ops that // produce them leave padding unwritten. Only the logical head_dim may be read. void test_vulkan_sdpa_ignores_head_dim_padding(const int seq_len) { diff --git a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json index 8c43cfc9fa6..001488c7a95 100644 --- a/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json +++ b/backends/vulkan/test/ops/benchmark_v2/operators/attention/sdpa/cases/correctness.json @@ -593,5 +593,101 @@ {"tensor": {"name": "output", "sizes": [1, 1, 8, 64], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} ] ] + }, + { + "name": "sdpa head_dim_above_fused decode D128 H16 Hkv8 S1 C64 P30 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 16, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 8, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 8, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 16, 128], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D128 H16 Hkv8 S1 C64 P30 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 16, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 8, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 8, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 16, 128], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D256 H8 Hkv1 S1 C64 P30 float32", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.001, "rtol": 0.001}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 1, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 1, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 256], "dtype": "float32", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] + }, + { + "name": "sdpa head_dim_above_fused decode D256 H8 Hkv1 S1 C64 P30 float16", + "operator": "llama.custom_sdpa.default", + "target_ms": 100, + "warmup_runs": 3, + "benchmark_runs": 10, + "max_dispatches": 200, + "validation_method": {"function": "is_close", "atol": 0.01, "rtol": 0.01}, + "route": "v_ROUTE", + "sweep_variables": {"v_ROUTE": ["gqa", "separate_qk_softmax"], "v_STORAGE": ["texture3d", "buffer"]}, + "args_sweep": [ + [ + {"tensor": {"name": "q", "sizes": [1, 1, 8, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "k_cache", "sizes": [1, 64, 1, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"tensor": {"name": "value_cache", "sizes": [1, 64, 1, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"rand_uniform_float": [-1, 1]}}}, + {"int": 30}, + null, + {"float": 0.0}, + {"bool": true}, + null, + {"tensor": {"name": "output", "sizes": [1, 1, 8, 256], "dtype": "float16", "storage": "v_STORAGE", "layout": "width", "data": {"fill": 0}}} + ] + ] } ] From 750e7c3cecfce43ea1d7abab78221cc7805b1ba7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 3 Dec 2026 10:10:33 +0100 Subject: [PATCH 12/13] Vulkan CI: validate the sdpa correctness cases --- .github/workflows/pull.yml | 2 +- .github/workflows/vulkan.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pull.yml b/.github/workflows/pull.yml index 45fc50dcefc..15bfb2013de 100644 --- a/.github/workflows/pull.yml +++ b/.github/workflows/pull.yml @@ -2132,7 +2132,7 @@ jobs: PYTHON_EXECUTABLE=python bash backends/vulkan/test/ops/benchmark_v2/build.sh for op in binary/add gemm/linear/qw/q8csw convolution/qw/q8csw gemm/linear/qw/q4gsw \ quantization/choose_qparams_per_row quantize/q8ta clone/q8ta binary/q8ta \ - warp; do + warp attention/sdpa; do ./cmake-out/backends/vulkan/test/ops/benchmark_v2/etvk_ops_bench --validation_only \ --config=backends/vulkan/test/ops/benchmark_v2/operators/${op}/cases/correctness.json done diff --git a/.github/workflows/vulkan.yml b/.github/workflows/vulkan.yml index ec81451f6cd..ce1d8472293 100644 --- a/.github/workflows/vulkan.yml +++ b/.github/workflows/vulkan.yml @@ -124,7 +124,7 @@ jobs: PYTHON_EXECUTABLE=python bash backends/vulkan/test/ops/benchmark_v2/build.sh for op in binary/add gemm/linear/qw/q8csw convolution/qw/q8csw gemm/linear/qw/q4gsw \ quantization/choose_qparams_per_row quantize/q8ta clone/q8ta binary/q8ta \ - warp; do + warp attention/sdpa; do ./cmake-out/backends/vulkan/test/ops/benchmark_v2/etvk_ops_bench --validation_only \ --config=backends/vulkan/test/ops/benchmark_v2/operators/${op}/cases/correctness.json done From dc5e32019298db4fb12f44b45eaa0ddcb2296910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 3 Dec 2026 10:31:06 +0100 Subject: [PATCH 13/13] Vulkan SDPA test: prefill the cache, and compare fp16 at fp16 tolerances The decode tests started at a non-zero position, but the update_cache path leaves earlier cache rows unwritten while the reference reads zeros, so they failed on MoltenVK regardless of the fused path. Prefill from position 0 instead. fp16 runs also compared with fp32 allclose tolerances, and ATTN_WEIGHT_ONLY built an fp32 output for an fp16 graph. --- backends/vulkan/test/op_tests/sdpa_test.cpp | 32 ++++++++++++--------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 508d4cd69ad..f2df9ded53f 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -324,7 +324,9 @@ void test_vulkan_sdpa( // Get reference output at::Tensor out = at::empty_like(q); if (mode == SDPAMode::ATTN_WEIGHT_ONLY) { - out = at::empty({batch_size, num_heads, init_seq_len, init_seq_len}); + out = at::empty( + {batch_size, num_heads, init_seq_len, init_seq_len}, + at::device(at::kCPU).dtype(dtype)); } // Build Vulkan SDPA graph @@ -519,7 +521,9 @@ void test_vulkan_sdpa( at::indexing::Slice(0, context_len)}); } - const bool output_correct = at::allclose(reference_out, vk_out); + const double rtol = dtype == at::kHalf ? 1e-2 : 1e-5; + const double atol = dtype == at::kHalf ? 1e-2 : 1e-8; + const bool output_correct = at::allclose(reference_out, vk_out, rtol, atol); if (!output_correct) { // Print only differing tensor elements side by side for easier comparison auto ref_flat = reference_out.flatten(); @@ -1125,41 +1129,43 @@ TEST(VulkanSDPATest, test_sdpa_op_unaligned_head_dim) { } // Decode within 256 tokens of context is served by the fused QK+softmax node, -// and beyond it by the separate attn-weights and softmax pair. These decode -// steps cross that cutoff, so one graph switches paths on resize. +// and beyond it by the separate attn-weights and softmax pair. A 250-token +// prefill is followed by decode steps that cross that cutoff, so one graph +// switches paths on resize. The steps start at position 0 because the +// update_cache path leaves earlier cache rows unwritten. const std::vector kDecodeAcrossFusedCutoff = - {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + {250, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff) { - test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 64, 8, 2, 1); + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 64, 8, 2, 1); } TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_fp16) { - test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 64, 8, 2, 1, at::kHalf); + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 64, 8, 2, 1, at::kHalf); } TEST(VulkanSDPATest, test_sdpa_op_decode_crosses_fused_cutoff_unaligned_dim) { - test_vulkan_sdpa(250, kDecodeAcrossFusedCutoff, 6, 4, 2, 1); + test_vulkan_sdpa(0, kDecodeAcrossFusedCutoff, 6, 4, 2, 1); } // Above a head_dim of 64 the fused node is not built, so the separate pair // serves every decode step, including a short context. -const std::vector kShortDecode = {1, 1, 1, 1}; +const std::vector kShortDecode = {10, 1, 1, 1, 1}; TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128) { - test_vulkan_sdpa(10, kShortDecode, 128, 8, 2, 1); + test_vulkan_sdpa(0, kShortDecode, 128, 8, 2, 1); } TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_128_fp16) { - test_vulkan_sdpa(10, kShortDecode, 128, 8, 2, 1, at::kHalf); + test_vulkan_sdpa(0, kShortDecode, 128, 8, 2, 1, at::kHalf); } TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256) { - test_vulkan_sdpa(10, kShortDecode, 256, 8, 1, 1); + test_vulkan_sdpa(0, kShortDecode, 256, 8, 1, 1); } TEST(VulkanSDPATest, test_sdpa_op_short_decode_head_dim_256_fp16) { - test_vulkan_sdpa(10, kShortDecode, 256, 8, 1, 1, at::kHalf); + test_vulkan_sdpa(0, kShortDecode, 256, 8, 1, 1, at::kHalf); } // q, k and v arrive with NaN in their head_dim padding, as when the ops that