From e65fd96fd17a86e881d6cb98fa94c18a77986d05 Mon Sep 17 00:00:00 2001 From: Mateusz Sluszniak Date: Wed, 7 Oct 2026 19:00:02 +0200 Subject: [PATCH 01/17] Vulkan: support attn_mask and scale in llama.custom_sdpa / sdpa_with_kv_cache The LLM SDPA path rejected both arguments at load. Sliding window attention (e.g. Gemma) needs them: an additive mask in place of the causal one, and a scale other than 1/sqrt(head_dim). As in the CPU op, the mask is a 2D [S, C] tensor over every key in the cache and cannot be combined with is_causal. The QK shaders get _mask variants that add it instead of applying the causal mask; softmax and AV are given C - S in place of input_pos so they attend to all C keys, which needs no shader change. --- .../glsl/sdpa_compute_attn_weights_coop.glsl | 16 ++ .../glsl/sdpa_compute_attn_weights_coop.yaml | 3 + .../glsl/sdpa_compute_attn_weights_tiled.glsl | 17 +- .../glsl/sdpa_compute_attn_weights_tiled.yaml | 3 + .../glsl/sdpa_fp_attn_weight_tile_store.glslh | 36 ++++ .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 90 ++++++-- backends/vulkan/test/op_tests/sdpa_test.cpp | 192 ++++++++++++++++++ 7 files changed, 341 insertions(+), 16 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 b7f14f435fa..c88332dd998 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 @@ -18,6 +18,8 @@ $if IO_STORAGE == "buffer": #define ATTN_WEIGHTS_BUFFER $if K_CACHE_STORAGE == "buffer": #define K_CACHE_BUFFER +$if HAS_MASK: + #define HAS_MASK #define Q_LAYOUT DHSB #define K_LAYOUT DHSB @@ -40,10 +42,14 @@ layout(std430) buffer; ${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)} +$if HAS_MASK: + ${layout_declare_tensor(B, "r", "t_mask", DTYPE, IO_STORAGE, is_scalar_array=True)} ${layout_declare_ubo(B, "ivec4", "q_sizes")} ${layout_declare_ubo(B, "ivec4", "k_sizes")} ${layout_declare_ubo(B, "int", "input_pos")} +$if HAS_MASK: + ${layout_declare_ubo(B, "ivec4", "mask_sizes")} layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; @@ -118,7 +124,12 @@ void main() { // 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. +#ifdef HAS_MASK + // The additive attn_mask replaces the causal mask, so no tile can be skipped. + const bool tile_in_mask_region = false; +#else bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); +#endif 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); @@ -171,6 +182,10 @@ void main() { out_tile = partial_sums[0]; // Apply scale and mask if the tile was not entirely in the mask region if (!tile_in_mask_region) { +#ifdef HAS_MASK + apply_scale(out_tile, inv_scale); + apply_attn_mask(out_tile, c, s); +#else VEC4_T inv_scale_vec = VEC4_T(inv_scale); apply_scale_and_mask( out_tile, @@ -178,6 +193,7 @@ void main() { input_pos, c, s); +#endif } store_attn_weight_tile_with_checks( 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..4c45ba0855a 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 + HAS_MASK: 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_mask + HAS_MASK: true diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl index 662d5edde68..f82d4c84a05 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl @@ -36,6 +36,8 @@ $else: $if HAS_BIAS: #define HAS_BIAS +$if HAS_MASK: + #define HAS_MASK #define TILE_M4 ${TILE_M4} #define TILE_K4 ${TILE_K4} @@ -56,6 +58,8 @@ ${layout_declare_tensor(B, "r", "t_q", IN_DTYPE, IO_STORAGE, is_scalar_array=Fal ${layout_declare_tensor(B, "r", "t_k", IN_DTYPE, K_CACHE_STORAGE, is_scalar_array=False)} $if HAS_BIAS: ${layout_declare_tensor(B, "r", "t_bias", IN_DTYPE, IO_STORAGE, is_scalar_array=False)} +$if HAS_MASK: + ${layout_declare_tensor(B, "r", "t_mask", IN_DTYPE, IO_STORAGE, is_scalar_array=True)} ${layout_declare_ubo(B, "ivec4", "q_sizes")} ${layout_declare_ubo(B, "ivec4", "k_sizes")} @@ -63,6 +67,8 @@ $if MODE == "llm": ${layout_declare_ubo(B, "int", "input_pos")} $if HAS_BIAS: ${layout_declare_ubo(B, "ivec4", "bias_sizes")} +$if HAS_MASK: + ${layout_declare_ubo(B, "ivec4", "mask_sizes")} layout(local_size_x_id = 0, local_size_y_id = 1, local_size_z_id = 2) in; @@ -82,6 +88,9 @@ ${layout_declare_spec_const(C, "float", "inv_scale", "1.0")} * attn_weights: [B, H_q, S, context_len] in input dtype * current context_len = input_pos + S * Applies combined scale + causal mask. + * With HAS_MASK the causal mask is replaced by an additive attn_mask + * [S, context_len]; the caller passes input_pos = C - S so that every key + * in k is attended, as in the CPU op. * * Fused SDPA: * q: [B, H, S, D] (DSHB layout) @@ -164,7 +173,7 @@ void main() { const int attn_S = S; #endif -#ifdef HAS_INPUT_POS +#if defined(HAS_INPUT_POS) && !defined(HAS_MASK) // 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. @@ -200,7 +209,11 @@ void main() { fp_accumulate_with_fp_weight(out_tile, q_tile, w_tile); } -#ifdef HAS_INPUT_POS +#if defined(HAS_INPUT_POS) && defined(HAS_MASK) + // LLM: scale + additive attn_mask + apply_scale(out_tile, inv_scale); + apply_attn_mask(out_tile, c, s); +#elif defined(HAS_INPUT_POS) // LLM: combined scale + causal mask VEC4_T inv_scale_vec = VEC4_T(inv_scale); apply_scale_and_mask( diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.yaml index 24494b408fa..ddad963f600 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.yaml +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.yaml @@ -12,6 +12,7 @@ sdpa_compute_attn_weights_tiled: K_CACHE_STORAGE: texture3d MODE: llm HAS_BIAS: false + HAS_MASK: false TILE_M4: 1 TILE_K4: 1 TILE_N4: 1 @@ -31,6 +32,8 @@ sdpa_compute_attn_weights_tiled: suffix: half shader_variants: - NAME: sdpa_compute_attn_weights_tiled + - NAME: sdpa_compute_attn_weights_tiled_mask + HAS_MASK: true - NAME: fused_sdpa_qk_tiled MODE: fused OUT_DTYPE: float diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh index 83d81ddf812..38aafbe8be5 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh @@ -151,6 +151,42 @@ void apply_bias( } #endif // HAS_BIAS +#ifdef HAS_MASK +/* + * Adds the LLM SDPA additive attn_mask, a 2D [S, C] tensor shared by every + * head, to the tile. Requires t_mask and mask_sizes. The mask is read element + * by element: a buffer-backed mask is not padded along its width, so its rows + * cannot be addressed in texels unless C is a multiple of 4. + */ +void apply_attn_mask( + inout FPOutTile tile, + const int c_idx_start, + const int s_idx_start) { + const int mask_C = mask_sizes.x; + const int mask_S = mask_sizes.y; + [[unroll]] for (int s = 0; s < TILE_M; ++s) { + const int s_idx = s_idx_start + s; + if (s_idx >= mask_S) { + continue; + } + [[unroll]] for (int c4 = 0; c4 < TILE_N4; ++c4) { + [[unroll]] for (int c4i = 0; c4i < 4; ++c4i) { + const int c_idx = c_idx_start + mul_4(c4) + c4i; + if (c_idx < mask_C) { +#ifdef INPUT_BUFFER + const float mask_val = float(t_mask[s_idx * mask_C + c_idx]); +#else + const float mask_val = float(texelFetch( + t_mask, ivec3(div_4(c_idx), s_idx, 0), 0)[mod_4(c_idx)]); +#endif + tile.data[s][c4][c4i] += T(mask_val); + } + } + } + } +} +#endif // HAS_MASK + void set_out_tile_to_vec(out FPOutTile tile, const LINEAR_FP_OUTPUT_TILE_VEC4_T vec) { [[unroll]] for (int s = 0; s < TILE_M; ++s) { [[unroll]] for (int c4 = 0; c4 < TILE_N4; ++c4) { tile.data[s][c4] = vec; } diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 39854b23d02..5931568af1b 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -243,9 +243,14 @@ vkapi::ShaderInfo pick_sdpa_qk_shader( const ValueRef q_projected = args.at(1).refs.at(0); const ValueRef k_cache = args.at(1).refs.at(1); const bool is_gemv = is_single_token(graph, q_projected); + // An additive attn_mask is bound as a third input: q, k, attn_mask. + const bool has_mask = args.at(1).refs.size() >= 3; std::string shader_name = "sdpa_compute_attn_weights"; shader_name += is_gemv ? "_coop" : "_tiled"; + if (has_mask) { + shader_name += "_mask"; + } add_storage_type_suffix(shader_name, graph->storage_type_of(q_projected)); add_storage_type_suffix(shader_name, graph->storage_type_of(k_cache)); add_dtype_suffix(shader_name, graph->dtype_of(q_projected)); @@ -481,11 +486,12 @@ void add_sdpa_kv_cache_update_node( } // Unified QK node (attn_weights = scale * Q @ K^T [+ bias]). -// LLM: pass input_pos_symint (real symint), attn_mask = kDummyValueRef. +// LLM: pass input_pos_symint (real symint), and attn_mask = a 2D [S, C] +// additive mask that replaces the causal mask, or kDummyValueRef. // FUSED: pass input_pos_symint = kDummyValueRef, attn_mask = valid ref or // 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. +// a spec const; both modes default it to 1/sqrt(head_dim) and use the +// caller-supplied scale when there is one. void add_sdpa_compute_attn_weights_node( ComputeGraph& graph, const ValueRef q, @@ -503,7 +509,8 @@ void add_sdpa_compute_attn_weights_node( if (mode == SDPAMode::LLM) { param_ubos.append(graph.get_or_create_int_param_buffer(input_pos_symint)); - } else if (is_valid(attn_mask)) { + } + if (is_valid(attn_mask)) { param_ubos.append(graph.sizes_ubo(attn_mask)); read_inputs.push_back(attn_mask); } @@ -640,6 +647,33 @@ void add_sdpa_compute_out_node( resize_sdpa_out_node)); } +// For a masked LLM SDPA, sets out_symint = C - S (the number of keys in k +// minus the number of queries), which the SDPA shaders read in place of +// input_pos so that they attend to every key. +void resize_attn_mask_input_pos_node( + ComputeGraph* graph, + const std::vector& args, + const std::vector& resize_args) { + (void)args; + const ValueRef q = resize_args.at(0); + const ValueRef k = resize_args.at(1); + const ValueRef out_symint = resize_args.at(2); + graph->set_symint( + out_symint, + graph->size_at(-3, k) - graph->size_at(-3, q)); +} + +ValueRef add_attn_mask_input_pos_node( + ComputeGraph& graph, + const ValueRef q, + const ValueRef k) { + const ValueRef out_symint = graph.add_symint( + graph.size_at(-3, k) - graph.size_at(-3, q)); + graph.execute_nodes().emplace_back( + new ExecuteNode(resize_attn_mask_input_pos_node, {q, k, out_symint})); + return out_symint; +} + // // High level operator impl // @@ -696,11 +730,30 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { VK_CHECK_COND( graph.val_is_none(dropout_p) || graph.extract_scalar(dropout_p) == 0); - VK_CHECK_COND(graph.val_is_none(scale)); - // is_causal is assumed to be true in the current implementation. - VK_CHECK_COND( - graph.val_is_none(is_causal) || graph.extract_scalar(is_causal)); - VK_CHECK_COND(graph.val_is_none(attn_mask)); + + // As in the CPU op, an attn_mask replaces the causal mask: it is a 2D + // [S, C] additive mask over every key in k_cache, and cannot be combined + // with is_causal. Without one, the attention is assumed to be causal. + const bool has_mask = graph.val_is_not_none(attn_mask); + if (has_mask) { + VK_CHECK_COND( + graph.val_is_none(is_causal) || !graph.extract_scalar(is_causal), + "attn_mask and is_causal cannot both be set"); + VK_CHECK_COND(graph.dim_of(attn_mask) == 2); + VK_CHECK_COND( + graph.size_at(-2, attn_mask) == + graph.size_at(-3, q_projected)); + VK_CHECK_COND( + graph.size_at(-1, attn_mask) == + graph.size_at(-3, k_cache)); + VK_CHECK_COND(graph.dtype_of(attn_mask) == graph.dtype_of(q_projected)); + VK_CHECK_COND( + graph.storage_type_of(attn_mask) == graph.storage_type_of(q_projected)); + VK_CHECK_COND(graph.packed_dim_of(attn_mask) == WHCN::kWidthDim); + } else { + VK_CHECK_COND( + graph.val_is_none(is_causal) || graph.extract_scalar(is_causal)); + } const int64_t num_q_heads = graph.size_at(-2, q_projected); int64_t max_seq_len = graph.size_at(-3, q_projected); @@ -763,14 +816,23 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { utils::kWidthPacked); 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)); + const float scale_val = graph.val_is_none(scale) + ? 1.0f / std::sqrt(static_cast(head_dim_size)) + : graph.extract_scalar(scale); + + // The SDPA shaders attend to the first input_pos + S keys. A masked + // attention attends to all C keys in k_cache, so give them C - S in place of + // input_pos. + const ValueRef attn_input_pos = has_mask + ? add_attn_mask_input_pos_node(graph, q_projected, k_cache) + : input_pos_symint; add_sdpa_compute_attn_weights_node( graph, q_projected, k_cache, - input_pos_symint, - /*attn_mask=*/kDummyValueRef, + attn_input_pos, + has_mask ? attn_mask : kDummyValueRef, scale_val, attn_weights, SDPAMode::LLM); @@ -780,7 +842,7 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { attn_weights, q_projected, k_cache, - input_pos_symint, + attn_input_pos, attn_weights_softmax, SDPAMode::LLM); @@ -790,7 +852,7 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { v_cache, q_projected, /*k=*/kDummyValueRef, - input_pos_symint, + attn_input_pos, out, SDPAMode::LLM); } diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index c1c252165eb..0558c4af396 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -892,3 +892,195 @@ TEST(VulkanSDPATest, test_sdpa_op_gqa_group4) { test_vulkan_sdpa( 0, {5, 1, 1, 1, 1, 3, 1}, head_dim, num_heads, num_kv_heads, 1); } + +// +// KV-cache SDPA with an additive attn_mask and an explicit scale, as used by +// sliding window attention. As in the CPU op, the mask replaces the causal mask +// and covers every key in the cache. +// + +void test_vulkan_sdpa_with_mask( + const std::vector& sequence_lens, + const int head_dim, + const int num_heads, + const int num_kv_heads, + const int max_context_len, + const int sliding_window, + const double scale, + vkcompute::utils::StorageType storage_type, + at::ScalarType dtype = at::kFloat) { + using namespace vkcompute; + + int max_seq_len = 0; + for (const int seq_len : sequence_lens) { + max_seq_len = std::max(max_seq_len, seq_len); + } + + // Reference caches are kept in fp32 + at::Tensor k_cache = at::zeros( + {1, max_context_len, num_kv_heads, head_dim}, + at::device(at::kCPU).dtype(at::kFloat)); + at::Tensor v_cache = at::zeros_like(k_cache); + at::Tensor k_cache_data = at::zeros_like(k_cache).to(dtype); + at::Tensor v_cache_data = at::zeros_like(v_cache).to(dtype); + + GraphConfig config; + ComputeGraph graph(config); + + const ValueRef r_k_cache_data = graph.add_tensorref( + k_cache_data.sizes().vec(), + from_at_scalartype(dtype), + k_cache_data.const_data_ptr()); + const ValueRef r_v_cache_data = graph.add_tensorref( + v_cache_data.sizes().vec(), + from_at_scalartype(dtype), + v_cache_data.const_data_ptr()); + + IOValueRef r_q = graph.add_input_tensor( + {1, max_seq_len, num_heads, head_dim}, + from_at_scalartype(dtype), + storage_type); + IOValueRef r_k = graph.add_input_tensor( + {1, max_seq_len, num_kv_heads, head_dim}, + from_at_scalartype(dtype), + storage_type); + IOValueRef r_v = graph.add_input_tensor( + {1, max_seq_len, num_kv_heads, head_dim}, + from_at_scalartype(dtype), + storage_type); + IOValueRef r_mask = graph.add_input_tensor( + {max_seq_len, max_context_len}, from_at_scalartype(dtype), storage_type); + + const ValueRef r_input_pos_symint = graph.add_symint(0); + const ValueRef r_out = graph.add_tensor( + {1, max_seq_len, num_heads, head_dim}, + from_at_scalartype(dtype), + storage_type); + + VK_GET_OP_FN("sdpa_with_kv_cache.default") + (graph, + { + r_q.value, + r_k.value, + r_v.value, + r_k_cache_data, + r_v_cache_data, + r_input_pos_symint, + kDummyValueRef, // sequence_len + r_mask.value, + kDummyValueRef, // dropout_p + graph.add_scalar(false), // is_causal + graph.add_scalar(scale), + r_out, + }); + + ValueRef staging_out = graph.set_output_tensor(r_out); + + graph.prepare(); + graph.prepack(); + + torch::manual_seed(0); + + int input_pos = 0; + for (const int seq_len : sequence_lens) { + const at::Tensor q = + (at::rand({1, seq_len, num_heads, head_dim}) * 2 - 1).to(dtype); + const at::Tensor k = + (at::rand({1, seq_len, num_kv_heads, head_dim}) * 2 - 1).to(dtype); + const at::Tensor v = + (at::rand({1, seq_len, num_kv_heads, head_dim}) * 2 - 1).to(dtype); + + // Query i (at position input_pos + i) sees the last sliding_window keys up + // to and including its own position. + const at::Tensor q_pos = at::arange(seq_len).unsqueeze(1) + input_pos; + const at::Tensor k_pos = at::arange(max_context_len).unsqueeze(0); + const at::Tensor visible = + at::logical_and(k_pos <= q_pos, k_pos > q_pos - sliding_window); + const at::Tensor mask = + at::zeros({seq_len, max_context_len}) + .masked_fill(at::logical_not(visible), -INFINITY) + .to(dtype); + + // Reference, in fp32 from the dtype-rounded inputs + k_cache.slice(1, input_pos, input_pos + seq_len).copy_(k.to(at::kFloat)); + v_cache.slice(1, input_pos, input_pos + seq_len).copy_(v.to(at::kFloat)); + const int num_repeats = num_heads / num_kv_heads; + const at::Tensor q_t = q.to(at::kFloat).transpose(1, 2); + const at::Tensor k_t = + at::repeat_interleave(k_cache, num_repeats, 2).transpose(1, 2); + const at::Tensor v_t = + at::repeat_interleave(v_cache, num_repeats, 2).transpose(1, 2); + const at::Tensor attn = + at::matmul(q_t, k_t.transpose(-2, -1)) * scale + mask.to(at::kFloat); + const at::Tensor reference_out = + at::matmul(at::softmax(attn, -1), v_t).transpose(1, 2); + + graph.set_symint(r_input_pos_symint, input_pos); + graph.resize_input(0, q.sizes().vec()); + graph.resize_input(1, k.sizes().vec()); + graph.resize_input(2, v.sizes().vec()); + graph.resize_input(3, mask.sizes().vec()); + graph.propagate_resize(); + + graph.maybe_cast_and_copy_into_staging( + r_q.staging, q.const_data_ptr(), q.numel(), from_at_scalartype(dtype)); + graph.maybe_cast_and_copy_into_staging( + r_k.staging, k.const_data_ptr(), k.numel(), from_at_scalartype(dtype)); + graph.maybe_cast_and_copy_into_staging( + r_v.staging, v.const_data_ptr(), v.numel(), from_at_scalartype(dtype)); + graph.maybe_cast_and_copy_into_staging( + r_mask.staging, + mask.const_data_ptr(), + mask.numel(), + from_at_scalartype(dtype)); + + graph.execute(); + + at::Tensor vk_out = at::zeros_like(q).contiguous(); + graph.maybe_cast_and_copy_from_staging( + staging_out, + vk_out.mutable_data_ptr(), + vk_out.numel(), + from_at_scalartype(dtype)); + vk_out = vk_out.to(at::kFloat); + + const double atol = dtype == at::kHalf ? 1e-2 : 1e-4; + const double rtol = dtype == at::kHalf ? 1e-2 : 1e-5; + const bool output_correct = at::allclose(reference_out, vk_out, rtol, atol); + if (!output_correct) { + std::cout << "Masked SDPA failed at input_pos " << input_pos + << " with seq_len " << seq_len << " (" << storage_type + << " storage, dtype " << dtype << "), max diff " + << at::max(at::abs(reference_out - vk_out)).item() << std::endl; + } + ASSERT_TRUE(output_correct); + + input_pos += seq_len; + } +} + +TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask) { + for (const auto storage_type : + {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { + test_vulkan_sdpa_with_mask( + {7, 1, 1, 1, 5, 1, 1}, 64, 8, 2, 32, 4, 1.0, storage_type); + } +} + +// A cache length that is not a multiple of 4 leaves the buffer-backed mask's +// rows unaligned to texels. +TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask_unaligned_context) { + for (const auto storage_type : + {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { + test_vulkan_sdpa_with_mask( + {6, 1, 1, 3, 1}, 32, 6, 2, 30, 5, 0.25, storage_type); + } +} + +TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask_fp16) { + for (const auto storage_type : + {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { + test_vulkan_sdpa_with_mask( + {7, 1, 1, 1, 5, 1, 1}, 64, 8, 2, 32, 4, 1.0, storage_type, at::kHalf); + } +} From e865d462b44fb049734daeb8f4390f02a39ee721 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 13:27:48 +0200 Subject: [PATCH 02/17] Vulkan SDPA: fix QK node comments and honor scale in the attn weight test op The QK node comment claimed both modes use the caller-supplied scale, but the compute_attn_weight_with_kv_cache test op ignored it, and the LLM input_pos note did not cover the masked C - S case. The test op now uses scale and rejects an attn_mask it would otherwise silently drop. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 5931568af1b..47fa7187a06 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -486,12 +486,13 @@ void add_sdpa_kv_cache_update_node( } // Unified QK node (attn_weights = scale * Q @ K^T [+ bias]). -// LLM: pass input_pos_symint (real symint), and attn_mask = a 2D [S, C] -// additive mask that replaces the causal mask, or kDummyValueRef. +// LLM: pass input_pos_symint, and attn_mask = a 2D [S, C] additive mask that +// replaces the causal mask, or kDummyValueRef. With a mask, sdpa_impl +// passes a C - S symint in place of the real input_pos. // FUSED: pass input_pos_symint = kDummyValueRef, attn_mask = valid ref or -// kDummyValueRef to indicate no bias. scale_val is always passed as -// a spec const; both modes default it to 1/sqrt(head_dim) and use the -// caller-supplied scale when there is one. +// kDummyValueRef to indicate no bias. +// scale_val is always passed as a spec const; callers default it to +// 1/sqrt(head_dim) and use the op's scale argument when there is one. void add_sdpa_compute_attn_weights_node( ComputeGraph& graph, const ValueRef q, @@ -912,13 +913,15 @@ void compute_attn_weight_with_kv_cache_impl( const ValueRef input_pos_symint = args[arg_idx++]; const ValueRef sequence_len = args[arg_idx++]; const ValueRef attn_mask = args[arg_idx++]; - (void)attn_mask; const ValueRef dropout_p = args[arg_idx++]; (void)dropout_p; const ValueRef is_causal = args[arg_idx++]; (void)is_causal; const ValueRef scale = args[arg_idx++]; - (void)scale; + + VK_CHECK_COND( + graph.val_is_none(attn_mask), + "attn_mask is not supported by compute_attn_weight_with_kv_cache"); // Output tensors const ValueRef out = args[arg_idx++]; @@ -935,7 +938,9 @@ void compute_attn_weight_with_kv_cache_impl( update_cache_impl(graph, {v_projected, v_cache, input_pos_symint, -1}); 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)); + const float scale_val = graph.val_is_none(scale) + ? 1.0f / std::sqrt(static_cast(head_dim_size)) + : graph.extract_scalar(scale); add_sdpa_compute_attn_weights_node( graph, From bd9b349fa636c2eeb918f58c43f1f4b95726795b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 13:27:59 +0200 Subject: [PATCH 03/17] Vulkan SDPA: prepack a constant attn_mask and validate it at load and resize A constant mask reaches the fused sdpa_with_kv_cache as a TensorRef, since the op handles its own prepacking, and was then used as a tensor. Prepack it with q's storage and width packing. Also check that the mask is contiguous (buffer) or uses the standard axis map (texture), as the shaders assume, that it stays [S, C] after a resize, and give the mask checks messages. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 78 ++++++++++++++----- 1 file changed, 60 insertions(+), 18 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 47fa7187a06..74bc341358e 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -648,9 +648,31 @@ void add_sdpa_compute_out_node( resize_sdpa_out_node)); } +void check_attn_mask_sizes( + ComputeGraph& graph, + const ValueRef attn_mask, + const ValueRef q, + const ValueRef k) { + VK_CHECK_COND( + graph.size_at(-2, attn_mask) == graph.size_at(-3, q) && + graph.size_at(-1, attn_mask) == + graph.size_at(-3, k), + "attn_mask must have shape [S, C] = [", + graph.size_at(-3, q), + ", ", + graph.size_at(-3, k), + "], got [", + graph.size_at(-2, attn_mask), + ", ", + graph.size_at(-1, attn_mask), + "]"); +} + // For a masked LLM SDPA, sets out_symint = C - S (the number of keys in k // minus the number of queries), which the SDPA shaders read in place of -// input_pos so that they attend to every key. +// input_pos so that they attend to every key. Also checks that the mask still +// has shape [S, C] after a resize, since the shaders would otherwise silently +// skip its missing rows or columns. void resize_attn_mask_input_pos_node( ComputeGraph* graph, const std::vector& args, @@ -658,7 +680,9 @@ void resize_attn_mask_input_pos_node( (void)args; const ValueRef q = resize_args.at(0); const ValueRef k = resize_args.at(1); - const ValueRef out_symint = resize_args.at(2); + const ValueRef attn_mask = resize_args.at(2); + const ValueRef out_symint = resize_args.at(3); + check_attn_mask_sizes(*graph, attn_mask, q, k); graph->set_symint( out_symint, graph->size_at(-3, k) - graph->size_at(-3, q)); @@ -667,11 +691,12 @@ void resize_attn_mask_input_pos_node( ValueRef add_attn_mask_input_pos_node( ComputeGraph& graph, const ValueRef q, - const ValueRef k) { + const ValueRef k, + const ValueRef attn_mask) { const ValueRef out_symint = graph.add_symint( graph.size_at(-3, k) - graph.size_at(-3, q)); - graph.execute_nodes().emplace_back( - new ExecuteNode(resize_attn_mask_input_pos_node, {q, k, out_symint})); + graph.execute_nodes().emplace_back(new ExecuteNode( + resize_attn_mask_input_pos_node, {q, k, attn_mask, out_symint})); return out_symint; } @@ -734,26 +759,42 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { // As in the CPU op, an attn_mask replaces the causal mask: it is a 2D // [S, C] additive mask over every key in k_cache, and cannot be combined - // with is_causal. Without one, the attention is assumed to be causal. + // with is_causal. Without one, the attention is assumed to be causal. The + // partitioner (op_registry.py) keeps other configurations on CPU. const bool has_mask = graph.val_is_not_none(attn_mask); + ValueRef mask = kDummyValueRef; if (has_mask) { VK_CHECK_COND( graph.val_is_none(is_causal) || !graph.extract_scalar(is_causal), "attn_mask and is_causal cannot both be set"); - VK_CHECK_COND(graph.dim_of(attn_mask) == 2); + VK_CHECK_COND(graph.dim_of(attn_mask) == 2, "attn_mask must be 2D"); VK_CHECK_COND( - graph.size_at(-2, attn_mask) == - graph.size_at(-3, q_projected)); + graph.dtype_of(attn_mask) == graph.dtype_of(q_projected), + "attn_mask must have the same dtype as q"); + // A constant mask arrives as a TensorRef, since the fused op handles its + // own prepacking. + mask = graph.val_is_tref(attn_mask) + ? prepack_standard( + graph, + attn_mask, + graph.storage_type_of(q_projected), + utils::kWidthPacked) + : attn_mask; + check_attn_mask_sizes(graph, mask, q_projected, k_cache); VK_CHECK_COND( - graph.size_at(-1, attn_mask) == - graph.size_at(-3, k_cache)); - VK_CHECK_COND(graph.dtype_of(attn_mask) == graph.dtype_of(q_projected)); + graph.storage_type_of(mask) == graph.storage_type_of(q_projected), + "attn_mask must have the same storage type as q"); + // The shaders index a buffer mask as contiguous [S, C] rows, and a + // texture mask with the standard axis map. VK_CHECK_COND( - graph.storage_type_of(attn_mask) == graph.storage_type_of(q_projected)); - VK_CHECK_COND(graph.packed_dim_of(attn_mask) == WHCN::kWidthDim); + graph.storage_type_of(mask) == utils::kBuffer + ? graph.is_contiguous_buffer_tensor(mask) + : graph.is_contiguous_texture_tensor(mask), + "attn_mask must be contiguous and width packed"); } else { VK_CHECK_COND( - graph.val_is_none(is_causal) || graph.extract_scalar(is_causal)); + graph.val_is_none(is_causal) || graph.extract_scalar(is_causal), + "attention without an attn_mask must be causal"); } const int64_t num_q_heads = graph.size_at(-2, q_projected); @@ -823,9 +864,10 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { // The SDPA shaders attend to the first input_pos + S keys. A masked // attention attends to all C keys in k_cache, so give them C - S in place of - // input_pos. + // input_pos. No key tile can be skipped, so with a mask every step costs + // O(C) rather than O(input_pos + S). const ValueRef attn_input_pos = has_mask - ? add_attn_mask_input_pos_node(graph, q_projected, k_cache) + ? add_attn_mask_input_pos_node(graph, q_projected, k_cache, mask) : input_pos_symint; add_sdpa_compute_attn_weights_node( @@ -833,7 +875,7 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { q_projected, k_cache, attn_input_pos, - has_mask ? attn_mask : kDummyValueRef, + mask, scale_val, attn_weights, SDPAMode::LLM); From 71ef295dd7889fc3f0410eea8ba089b276d03a7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 13:27:59 +0200 Subject: [PATCH 04/17] Vulkan: keep unsupported custom_sdpa mask configurations on CPU The runtime rejects an attn_mask combined with is_causal, a mask that is not 2D [S, C] or not of q's dtype (e.g. the fp32 mask the CPU op requires next to an fp16 query), and non-causal attention without a mask. These were still delegated and aborted at load. Check them in the partitioner, and in the causal_sdpa pattern detector, since a matched node skips the per-op checks. The update_cache nodes that write the cache of a rejected custom_sdpa stay on CPU with it; splitting them fails at lowering. --- backends/vulkan/op_registry.py | 93 ++++++++++++++++++++++ backends/vulkan/patterns/sdpa.py | 7 ++ backends/vulkan/test/test_vulkan_passes.py | 86 ++++++++++++++++++++ 3 files changed, 186 insertions(+) diff --git a/backends/vulkan/op_registry.py b/backends/vulkan/op_registry.py index 758e4aa9a5f..4cb8c309d40 100644 --- a/backends/vulkan/op_registry.py +++ b/backends/vulkan/op_registry.py @@ -1129,6 +1129,97 @@ def register_q8ta_linear_gemv(): # ============================================================================= +# Positions of (query, key_cache, attn_mask, is_causal) in the op's args. +_LLM_SDPA_ARG_IDX = { + "llama::custom_sdpa": (0, 1, 4, 6), + "llama::sdpa_with_kv_cache": (0, 3, 7, 9), +} + + +def _is_update_cache_node(node: torch.fx.Node) -> bool: + if node.target in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ): + op = node.args[0] + return hasattr(op, "name") and op.name() == "llama::update_cache" + return utils.node_has_target(node, "llama::update_cache") + + +def _check_update_cache_node(node: torch.fx.Node) -> bool: + # custom_sdpa reads either the mutated cache directly, or the cache returned + # by the auto_functionalized update_cache. + readers = set(node.users) + for user in node.users: + readers.update(user.users) + if utils.node_has_target(node, "llama::update_cache") and isinstance( + node.args[1], torch.fx.Node + ): + readers.update(node.args[1].users) + return all( + check_llm_sdpa_node(reader) + for reader in readers + if utils.node_has_target(reader, "llama::custom_sdpa") + ) + + +def _check_llm_sdpa_mask( + attn_mask: torch.fx.Node, q: torch.fx.Node, cache: torch.fx.Node +) -> bool: + mask_val = attn_mask.meta.get("val", None) + q_val = q.meta.get("val", None) + cache_val = cache.meta.get("val", None) + if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val, cache_val)): + return False + if mask_val.dim() != 2 or mask_val.dtype != q_val.dtype: + return False + # The mask must be [S, C]. Only reject sizes that are known to mismatch. + return all( + not (isinstance(size, int) and isinstance(expected, int)) or size == expected + for size, expected in ( + (mask_val.shape[0], q_val.shape[1]), + (mask_val.shape[1], cache_val.shape[1]), + ) + ) + + +def check_llm_sdpa_node(node: torch.fx.Node) -> bool: + """ + The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D + [S, C] additive attn_mask (with is_causal unset) of the same dtype as the + query. Other configurations stay on CPU instead of failing at load time. + An update_cache stays on CPU with the custom_sdpa that reads its cache, so + that both see the same cache. + """ + if _is_update_cache_node(node): + return _check_update_cache_node(node) + + arg_idx = next( + ( + idx + for target, idx in _LLM_SDPA_ARG_IDX.items() + if utils.node_has_target(node, target) + ), + None, + ) + if arg_idx is None: + return True + q_idx, cache_idx, mask_idx, is_causal_idx = arg_idx + + def get_arg(idx: int, name: str, default: Any) -> Any: + if idx < len(node.args): + return node.args[idx] + return node.kwargs.get(name, default) + + attn_mask = get_arg(mask_idx, "attn_mask", None) + is_causal = get_arg(is_causal_idx, "is_causal", False) + if attn_mask is None: + return bool(is_causal) + if is_causal or not isinstance(attn_mask, torch.fx.Node): + return False + return _check_llm_sdpa_mask(attn_mask, node.args[q_idx], node.args[cache_idx]) + + @update_features("llama::sdpa_with_kv_cache") def register_sdpa_with_kv_cache(): return OpFeatures( @@ -1136,6 +1227,7 @@ def register_sdpa_with_kv_cache(): inputs_dtypes=utils.FP_T, supports_resize=True, supports_prepacking=True, + are_node_inputs_supported_fn=check_llm_sdpa_node, ) @@ -1150,6 +1242,7 @@ def register_sdpa_cpp_ops(): inputs_storage=utils.CONTIGUOUS_ANY, inputs_dtypes=utils.FP_T, supports_resize=True, + are_node_inputs_supported_fn=check_llm_sdpa_node, ) diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index f67799f9b76..2b3ac526179 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -10,6 +10,8 @@ import torch +from executorch.backends.vulkan.op_registry import check_llm_sdpa_node + from executorch.backends.vulkan.patterns.pattern_registry import ( PatternMatch, register_pattern_detector, @@ -89,6 +91,11 @@ def find_causal_sdpa_patterns( if not is_custom_sdpa_node(node): return None + # A matched node is delegated without the partitioner's per-op checks, so + # leave unsupported mask configurations unmatched to keep them on CPU. + if not check_llm_sdpa_node(node): + return None + matched_pattern = CausalSDPAMatch(node) if matched_pattern.match_found: return matched_pattern diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index dda8fa1023e..84c0e1ffb87 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -1052,3 +1052,89 @@ def forward(self, x): before = op_node_count(ep.graph_module, "view_copy.default") RemoveRedundantOpsTransform().call(ep.graph_module) self.assertEqual(op_node_count(ep.graph_module, "view_copy.default"), before) + + +class _NamedOpStub: + """Stands in for a llama custom op, which may not be registered here.""" + + def __init__(self, name: str) -> None: + self._name = name + self.__name__ = name.replace("::", "_") + + def name(self) -> str: + return self._name + + def __call__(self, *args): + raise NotImplementedError + + +class TestLLMSDPAPartitionerCheck(unittest.TestCase): + """ + check_llm_sdpa_node keeps llama::custom_sdpa / update_cache configurations + that the Vulkan SDPA cannot run on CPU, instead of failing at load time. The + causal_sdpa pattern must not match them either, since a matched node is + delegated without the per-op checks. + """ + + S, C, H, D = 4, 16, 2, 8 + + def _build( + self, + mask_shape=None, + mask_dtype=torch.float32, + q_dtype=torch.float32, + is_causal=False, + ): + from executorch.backends.vulkan.op_registry import check_llm_sdpa_node + from executorch.backends.vulkan.patterns.sdpa import find_causal_sdpa_patterns + from torch._subclasses.fake_tensor import FakeTensorMode + + fake_mode = FakeTensorMode() + graph = torch.fx.Graph() + + def placeholder(name, shape, dtype): + node = graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor(torch.empty(shape, dtype=dtype)) + return node + + q = placeholder("q", (1, self.S, self.H, self.D), q_dtype) + k = placeholder("k", (1, self.S, self.H, self.D), q_dtype) + k_cache = placeholder("k_cache", (1, self.C, self.H, self.D), q_dtype) + v_cache = placeholder("v_cache", (1, self.C, self.H, self.D), q_dtype) + mask = None + if mask_shape is not None: + mask = placeholder("mask", mask_shape, mask_dtype) + + update_cache = graph.call_function( + _NamedOpStub("llama::update_cache"), (k, k_cache, 0) + ) + custom_sdpa = graph.call_function( + _NamedOpStub("llama::custom_sdpa"), + (q, k_cache, v_cache, 0, mask, 0.0, is_causal), + ) + supported = check_llm_sdpa_node(custom_sdpa) + self.assertEqual(check_llm_sdpa_node(update_cache), supported) + self.assertEqual(find_causal_sdpa_patterns(custom_sdpa) is not None, supported) + return supported + + def test_causal_without_mask_is_supported(self): + self.assertTrue(self._build(is_causal=True)) + + def test_non_causal_without_mask_is_rejected(self): + self.assertFalse(self._build(is_causal=False)) + + def test_mask_is_supported(self): + self.assertTrue(self._build(mask_shape=(self.S, self.C))) + + def test_mask_with_is_causal_is_rejected(self): + self.assertFalse(self._build(mask_shape=(self.S, self.C), is_causal=True)) + + def test_mask_dtype_mismatch_is_rejected(self): + # The CPU op requires an fp32 mask, also for an fp16 query. + self.assertFalse( + self._build(mask_shape=(self.S, self.C), q_dtype=torch.float16) + ) + + def test_mask_shape_mismatch_is_rejected(self): + self.assertFalse(self._build(mask_shape=(1, self.S, self.C))) + self.assertFalse(self._build(mask_shape=(self.S, self.C - 1))) From 3ceb7857dca67c1962dc79b1c0bf9f468c8f31e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 13:27:59 +0200 Subject: [PATCH 05/17] Vulkan SDPA: fetch each texture attn_mask texel once apply_attn_mask fetched a texture mask texel once per element. Texture rows are padded to texels, so fetch once per 4 columns; the buffer path still reads element by element since its rows are not texel aligned. --- .../glsl/sdpa_fp_attn_weight_tile_store.glslh | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh index 38aafbe8be5..cf085d02542 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh @@ -154,9 +154,10 @@ void apply_bias( #ifdef HAS_MASK /* * Adds the LLM SDPA additive attn_mask, a 2D [S, C] tensor shared by every - * head, to the tile. Requires t_mask and mask_sizes. The mask is read element - * by element: a buffer-backed mask is not padded along its width, so its rows - * cannot be addressed in texels unless C is a multiple of 4. + * head, to the tile. Requires t_mask and mask_sizes, and a c_idx_start that is + * a multiple of 4. A texture mask is read one texel per 4 columns. A buffer + * mask is read element by element: its rows are not padded, so they cannot be + * addressed in texels unless C is a multiple of 4. */ void apply_attn_mask( inout FPOutTile tile, @@ -170,14 +171,21 @@ void apply_attn_mask( continue; } [[unroll]] for (int c4 = 0; c4 < TILE_N4; ++c4) { + const int c_idx_base = c_idx_start + mul_4(c4); + if (c_idx_base >= mask_C) { + continue; + } +#ifndef INPUT_BUFFER + const vec4 mask_texel = + vec4(texelFetch(t_mask, ivec3(div_4(c_idx_base), s_idx, 0), 0)); +#endif [[unroll]] for (int c4i = 0; c4i < 4; ++c4i) { - const int c_idx = c_idx_start + mul_4(c4) + c4i; + const int c_idx = c_idx_base + c4i; if (c_idx < mask_C) { #ifdef INPUT_BUFFER const float mask_val = float(t_mask[s_idx * mask_C + c_idx]); #else - const float mask_val = float(texelFetch( - t_mask, ivec3(div_4(c_idx), s_idx, 0), 0)[mod_4(c_idx)]); + const float mask_val = mask_texel[c4i]; #endif tile.data[s][c4][c4i] += T(mask_val); } From 6b399fe375e46dfbe064823d82a300c1f0c970a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 8 Oct 2026 13:27:59 +0200 Subject: [PATCH 06/17] Vulkan SDPA: test masked attention over the full cache and more configs A sliding window mask is -inf after each query's position, so it cannot tell whether the shaders attend to all C keys or only to input_pos + S. Add a random finite mask test where the cache is filled first and input_pos is then rewound, which only passes if every key is attended. Also cover MHA, a mask without a scale, an explicit scale on the causal path, and the unfused update_cache + llama.custom_sdpa entry point. --- backends/vulkan/test/op_tests/sdpa_test.cpp | 330 +++++++++++++++----- 1 file changed, 260 insertions(+), 70 deletions(-) diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 0558c4af396..0d180df3000 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -20,8 +20,10 @@ #include "test_utils.h" +#include #include #include +#include // // SDPA Mode Enum @@ -894,26 +896,56 @@ TEST(VulkanSDPATest, test_sdpa_op_gqa_group4) { } // -// KV-cache SDPA with an additive attn_mask and an explicit scale, as used by -// sliding window attention. As in the CPU op, the mask replaces the causal mask -// and covers every key in the cache. +// KV-cache SDPA with an optional additive attn_mask and an optional scale. As +// in the CPU op, a mask replaces the causal mask and covers every key in the +// cache. // -void test_vulkan_sdpa_with_mask( - const std::vector& sequence_lens, +enum class LLMSDPAMask { + // No mask, is_causal = true + CAUSAL, + // Each query sees the last sliding_window keys up to its own position + SLIDING_WINDOW, + // Random finite values over every key in the cache, so keys after + // input_pos + S contribute to the output + RANDOM, +}; + +struct LLMSDPAStep { + int input_pos; + int seq_len; +}; + +std::vector consecutive_steps(const std::vector& seq_lens) { + std::vector steps; + int input_pos = 0; + for (const int seq_len : seq_lens) { + steps.push_back({input_pos, seq_len}); + input_pos += seq_len; + } + return steps; +} + +void test_vulkan_llm_sdpa( + const std::vector& steps, const int head_dim, const int num_heads, const int num_kv_heads, const int max_context_len, + const LLMSDPAMask mask_kind, const int sliding_window, - const double scale, + const std::optional scale, vkcompute::utils::StorageType storage_type, - at::ScalarType dtype = at::kFloat) { + at::ScalarType dtype = at::kFloat, + const bool use_custom_sdpa = false) { using namespace vkcompute; + const bool has_mask = mask_kind != LLMSDPAMask::CAUSAL; + int max_seq_len = 0; - for (const int seq_len : sequence_lens) { - max_seq_len = std::max(max_seq_len, seq_len); + for (const LLMSDPAStep& step : steps) { + ASSERT_LE(step.input_pos + step.seq_len, max_context_len); + max_seq_len = std::max(max_seq_len, step.seq_len); } // Reference caches are kept in fp32 @@ -927,15 +959,6 @@ void test_vulkan_sdpa_with_mask( GraphConfig config; ComputeGraph graph(config); - const ValueRef r_k_cache_data = graph.add_tensorref( - k_cache_data.sizes().vec(), - from_at_scalartype(dtype), - k_cache_data.const_data_ptr()); - const ValueRef r_v_cache_data = graph.add_tensorref( - v_cache_data.sizes().vec(), - from_at_scalartype(dtype), - v_cache_data.const_data_ptr()); - IOValueRef r_q = graph.add_input_tensor( {1, max_seq_len, num_heads, head_dim}, from_at_scalartype(dtype), @@ -948,31 +971,74 @@ void test_vulkan_sdpa_with_mask( {1, max_seq_len, num_kv_heads, head_dim}, from_at_scalartype(dtype), storage_type); - IOValueRef r_mask = graph.add_input_tensor( - {max_seq_len, max_context_len}, from_at_scalartype(dtype), storage_type); + IOValueRef r_mask = {kDummyValueRef, kDummyValueRef}; + if (has_mask) { + r_mask = graph.add_input_tensor( + {max_seq_len, max_context_len}, + from_at_scalartype(dtype), + storage_type); + } const ValueRef r_input_pos_symint = graph.add_symint(0); const ValueRef r_out = graph.add_tensor( {1, max_seq_len, num_heads, head_dim}, from_at_scalartype(dtype), storage_type); - - VK_GET_OP_FN("sdpa_with_kv_cache.default") - (graph, - { - r_q.value, - r_k.value, - r_v.value, - r_k_cache_data, - r_v_cache_data, - r_input_pos_symint, - kDummyValueRef, // sequence_len - r_mask.value, - kDummyValueRef, // dropout_p - graph.add_scalar(false), // is_causal - graph.add_scalar(scale), - r_out, - }); + const ValueRef r_is_causal = graph.add_scalar(!has_mask); + const ValueRef r_scale = scale.has_value() + ? graph.add_scalar(scale.value()) + : kDummyValueRef; + + if (use_custom_sdpa) { + const ValueRef r_k_cache = graph.add_tensor( + k_cache_data.sizes().vec(), from_at_scalartype(dtype), storage_type); + const ValueRef r_v_cache = graph.add_tensor( + v_cache_data.sizes().vec(), from_at_scalartype(dtype), storage_type); + const ValueRef r_dummy_out = + graph.add_tensor({1}, from_at_scalartype(dtype), utils::kBuffer); + VK_GET_OP_FN("update_cache.default") + (graph, {r_k.value, r_k_cache, r_input_pos_symint, r_dummy_out}); + VK_GET_OP_FN("update_cache.default") + (graph, {r_v.value, r_v_cache, r_input_pos_symint, r_dummy_out}); + VK_GET_OP_FN("llama.custom_sdpa.default") + (graph, + { + r_q.value, + r_k_cache, + r_v_cache, + r_input_pos_symint, + r_mask.value, + kDummyValueRef, // dropout_p + r_is_causal, + r_scale, + r_out, + }); + } else { + const ValueRef r_k_cache_data = graph.add_tensorref( + k_cache_data.sizes().vec(), + from_at_scalartype(dtype), + k_cache_data.const_data_ptr()); + const ValueRef r_v_cache_data = graph.add_tensorref( + v_cache_data.sizes().vec(), + from_at_scalartype(dtype), + v_cache_data.const_data_ptr()); + VK_GET_OP_FN("sdpa_with_kv_cache.default") + (graph, + { + r_q.value, + r_k.value, + r_v.value, + r_k_cache_data, + r_v_cache_data, + r_input_pos_symint, + kDummyValueRef, // sequence_len + r_mask.value, + kDummyValueRef, // dropout_p + r_is_causal, + r_scale, + r_out, + }); + } ValueRef staging_out = graph.set_output_tensor(r_out); @@ -981,8 +1047,13 @@ void test_vulkan_sdpa_with_mask( torch::manual_seed(0); - int input_pos = 0; - for (const int seq_len : sequence_lens) { + const double scale_val = + scale.has_value() ? scale.value() : 1.0 / std::sqrt(head_dim); + + for (const LLMSDPAStep& step : steps) { + const int input_pos = step.input_pos; + const int seq_len = step.seq_len; + const at::Tensor q = (at::rand({1, seq_len, num_heads, head_dim}) * 2 - 1).to(dtype); const at::Tensor k = @@ -990,16 +1061,18 @@ void test_vulkan_sdpa_with_mask( const at::Tensor v = (at::rand({1, seq_len, num_kv_heads, head_dim}) * 2 - 1).to(dtype); - // Query i (at position input_pos + i) sees the last sliding_window keys up - // to and including its own position. + // Query i is at position input_pos + i const at::Tensor q_pos = at::arange(seq_len).unsqueeze(1) + input_pos; const at::Tensor k_pos = at::arange(max_context_len).unsqueeze(0); - const at::Tensor visible = - at::logical_and(k_pos <= q_pos, k_pos > q_pos - sliding_window); - const at::Tensor mask = - at::zeros({seq_len, max_context_len}) - .masked_fill(at::logical_not(visible), -INFINITY) - .to(dtype); + at::Tensor visible = k_pos <= q_pos; + if (mask_kind == LLMSDPAMask::SLIDING_WINDOW) { + visible = at::logical_and(visible, k_pos > q_pos - sliding_window); + } + at::Tensor mask = mask_kind == LLMSDPAMask::RANDOM + ? at::randn({seq_len, max_context_len}) * 2 + : at::zeros({seq_len, max_context_len}) + .masked_fill(at::logical_not(visible), -INFINITY); + mask = mask.to(dtype); // Reference, in fp32 from the dtype-rounded inputs k_cache.slice(1, input_pos, input_pos + seq_len).copy_(k.to(at::kFloat)); @@ -1010,8 +1083,8 @@ void test_vulkan_sdpa_with_mask( at::repeat_interleave(k_cache, num_repeats, 2).transpose(1, 2); const at::Tensor v_t = at::repeat_interleave(v_cache, num_repeats, 2).transpose(1, 2); - const at::Tensor attn = - at::matmul(q_t, k_t.transpose(-2, -1)) * scale + mask.to(at::kFloat); + const at::Tensor attn = at::matmul(q_t, k_t.transpose(-2, -1)) * scale_val + + mask.to(at::kFloat); const at::Tensor reference_out = at::matmul(at::softmax(attn, -1), v_t).transpose(1, 2); @@ -1019,7 +1092,9 @@ void test_vulkan_sdpa_with_mask( graph.resize_input(0, q.sizes().vec()); graph.resize_input(1, k.sizes().vec()); graph.resize_input(2, v.sizes().vec()); - graph.resize_input(3, mask.sizes().vec()); + if (has_mask) { + graph.resize_input(3, mask.sizes().vec()); + } graph.propagate_resize(); graph.maybe_cast_and_copy_into_staging( @@ -1028,11 +1103,13 @@ void test_vulkan_sdpa_with_mask( r_k.staging, k.const_data_ptr(), k.numel(), from_at_scalartype(dtype)); graph.maybe_cast_and_copy_into_staging( r_v.staging, v.const_data_ptr(), v.numel(), from_at_scalartype(dtype)); - graph.maybe_cast_and_copy_into_staging( - r_mask.staging, - mask.const_data_ptr(), - mask.numel(), - from_at_scalartype(dtype)); + if (has_mask) { + graph.maybe_cast_and_copy_into_staging( + r_mask.staging, + mask.const_data_ptr(), + mask.numel(), + from_at_scalartype(dtype)); + } graph.execute(); @@ -1048,39 +1125,152 @@ void test_vulkan_sdpa_with_mask( const double rtol = dtype == at::kHalf ? 1e-2 : 1e-5; const bool output_correct = at::allclose(reference_out, vk_out, rtol, atol); if (!output_correct) { - std::cout << "Masked SDPA failed at input_pos " << input_pos + std::cout << "LLM SDPA failed at input_pos " << input_pos << " with seq_len " << seq_len << " (" << storage_type << " storage, dtype " << dtype << "), max diff " << at::max(at::abs(reference_out - vk_out)).item() << std::endl; } ASSERT_TRUE(output_correct); - - input_pos += seq_len; } } +constexpr std::array kLLMSDPAStorageTypes = { + vkcompute::utils::kTexture3D, + vkcompute::utils::kBuffer}; + TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask) { - for (const auto storage_type : - {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { - test_vulkan_sdpa_with_mask( - {7, 1, 1, 1, 5, 1, 1}, 64, 8, 2, 32, 4, 1.0, storage_type); + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + consecutive_steps({7, 1, 1, 1, 5, 1, 1}), + 64, + 8, + 2, + 32, + LLMSDPAMask::SLIDING_WINDOW, + 4, + 1.0, + storage_type); } } // A cache length that is not a multiple of 4 leaves the buffer-backed mask's // rows unaligned to texels. TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask_unaligned_context) { - for (const auto storage_type : - {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { - test_vulkan_sdpa_with_mask( - {6, 1, 1, 3, 1}, 32, 6, 2, 30, 5, 0.25, storage_type); + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + consecutive_steps({6, 1, 1, 3, 1}), + 32, + 6, + 2, + 30, + LLMSDPAMask::SLIDING_WINDOW, + 5, + 0.25, + storage_type); } } TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask_fp16) { - for (const auto storage_type : - {vkcompute::utils::kTexture3D, vkcompute::utils::kBuffer}) { - test_vulkan_sdpa_with_mask( - {7, 1, 1, 1, 5, 1, 1}, 64, 8, 2, 32, 4, 1.0, storage_type, at::kHalf); + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + consecutive_steps({7, 1, 1, 1, 5, 1, 1}), + 64, + 8, + 2, + 32, + LLMSDPAMask::SLIDING_WINDOW, + 4, + 1.0, + storage_type, + at::kHalf); + } +} + +// Without a scale argument the mask path uses 1/sqrt(head_dim). MHA (no GQA) +// takes a different decode AV shader than the GQA cases above. +TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask_mha_default_scale) { + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + consecutive_steps({5, 1, 1, 2, 1}), + 32, + 4, + 4, + 24, + LLMSDPAMask::SLIDING_WINDOW, + 6, + std::nullopt, + storage_type); + } +} + +// After a first step fills the whole cache, the later steps rewind input_pos so +// that keys after input_pos + S hold real values, and the random mask gives +// them a finite weight. The output only matches the reference if every key in +// the cache is attended, i.e. if the shaders are given C - S as input_pos. +TEST(VulkanSDPATest, test_sdpa_op_random_mask_attends_full_cache) { + const std::vector steps = { + {0, 30}, {5, 1}, {12, 3}, {20, 1}, {3, 6}, {29, 1}}; + for (const auto storage_type : kLLMSDPAStorageTypes) { + for (const auto dtype : {at::kFloat, at::kHalf}) { + // GQA + test_vulkan_llm_sdpa( + steps, + 32, + 6, + 2, + 30, + LLMSDPAMask::RANDOM, + 0, + 0.25, + storage_type, + dtype); + // MHA + test_vulkan_llm_sdpa( + steps, + 32, + 4, + 4, + 30, + LLMSDPAMask::RANDOM, + 0, + 0.25, + storage_type, + dtype); + } + } +} + +// The same through the unfused update_cache + llama.custom_sdpa entry point. +TEST(VulkanSDPATest, test_sdpa_op_custom_sdpa_random_mask) { + const std::vector steps = {{0, 30}, {5, 1}, {12, 3}, {29, 1}}; + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + steps, + 32, + 6, + 2, + 30, + LLMSDPAMask::RANDOM, + 0, + 0.25, + storage_type, + at::kFloat, + /*use_custom_sdpa=*/true); + } +} + +// An explicit scale on the causal (unmasked) path. +TEST(VulkanSDPATest, test_sdpa_op_causal_explicit_scale) { + for (const auto storage_type : kLLMSDPAStorageTypes) { + test_vulkan_llm_sdpa( + consecutive_steps({7, 1, 1, 3, 1}), + 64, + 8, + 2, + 32, + LLMSDPAMask::CAUSAL, + 0, + 0.3, + storage_type); } } From 05bf67f600464b846721ce82774830bb9c034a75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Mon, 12 Oct 2026 15:11:19 +0200 Subject: [PATCH 07/17] Vulkan: move check_llm_sdpa_node into patterns/sdpa.py Breaks the op_registry -> custom_ops_lib -> patterns -> op_registry import cycle; op_registry now imports the check from patterns. --- backends/vulkan/op_registry.py | 92 +-------------------- backends/vulkan/patterns/sdpa.py | 93 +++++++++++++++++++++- backends/vulkan/targets.bzl | 1 + backends/vulkan/test/test_vulkan_passes.py | 6 +- 4 files changed, 97 insertions(+), 95 deletions(-) diff --git a/backends/vulkan/op_registry.py b/backends/vulkan/op_registry.py index 4cb8c309d40..ca3ea57ff87 100644 --- a/backends/vulkan/op_registry.py +++ b/backends/vulkan/op_registry.py @@ -13,6 +13,7 @@ import executorch.backends.vulkan.custom_ops_lib # noqa import executorch.backends.vulkan.utils as utils import torch +from executorch.backends.vulkan.patterns.sdpa import check_llm_sdpa_node from executorch.exir.dialects._ops import ops as exir_ops from executorch.exir.dialects.edge._ops import EdgeOpOverload @@ -1129,97 +1130,6 @@ def register_q8ta_linear_gemv(): # ============================================================================= -# Positions of (query, key_cache, attn_mask, is_causal) in the op's args. -_LLM_SDPA_ARG_IDX = { - "llama::custom_sdpa": (0, 1, 4, 6), - "llama::sdpa_with_kv_cache": (0, 3, 7, 9), -} - - -def _is_update_cache_node(node: torch.fx.Node) -> bool: - if node.target in ( - torch.ops.higher_order.auto_functionalized, - torch.ops.higher_order.auto_functionalized_v2, - ): - op = node.args[0] - return hasattr(op, "name") and op.name() == "llama::update_cache" - return utils.node_has_target(node, "llama::update_cache") - - -def _check_update_cache_node(node: torch.fx.Node) -> bool: - # custom_sdpa reads either the mutated cache directly, or the cache returned - # by the auto_functionalized update_cache. - readers = set(node.users) - for user in node.users: - readers.update(user.users) - if utils.node_has_target(node, "llama::update_cache") and isinstance( - node.args[1], torch.fx.Node - ): - readers.update(node.args[1].users) - return all( - check_llm_sdpa_node(reader) - for reader in readers - if utils.node_has_target(reader, "llama::custom_sdpa") - ) - - -def _check_llm_sdpa_mask( - attn_mask: torch.fx.Node, q: torch.fx.Node, cache: torch.fx.Node -) -> bool: - mask_val = attn_mask.meta.get("val", None) - q_val = q.meta.get("val", None) - cache_val = cache.meta.get("val", None) - if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val, cache_val)): - return False - if mask_val.dim() != 2 or mask_val.dtype != q_val.dtype: - return False - # The mask must be [S, C]. Only reject sizes that are known to mismatch. - return all( - not (isinstance(size, int) and isinstance(expected, int)) or size == expected - for size, expected in ( - (mask_val.shape[0], q_val.shape[1]), - (mask_val.shape[1], cache_val.shape[1]), - ) - ) - - -def check_llm_sdpa_node(node: torch.fx.Node) -> bool: - """ - The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D - [S, C] additive attn_mask (with is_causal unset) of the same dtype as the - query. Other configurations stay on CPU instead of failing at load time. - An update_cache stays on CPU with the custom_sdpa that reads its cache, so - that both see the same cache. - """ - if _is_update_cache_node(node): - return _check_update_cache_node(node) - - arg_idx = next( - ( - idx - for target, idx in _LLM_SDPA_ARG_IDX.items() - if utils.node_has_target(node, target) - ), - None, - ) - if arg_idx is None: - return True - q_idx, cache_idx, mask_idx, is_causal_idx = arg_idx - - def get_arg(idx: int, name: str, default: Any) -> Any: - if idx < len(node.args): - return node.args[idx] - return node.kwargs.get(name, default) - - attn_mask = get_arg(mask_idx, "attn_mask", None) - is_causal = get_arg(is_causal_idx, "is_causal", False) - if attn_mask is None: - return bool(is_causal) - if is_causal or not isinstance(attn_mask, torch.fx.Node): - return False - return _check_llm_sdpa_mask(attn_mask, node.args[q_idx], node.args[cache_idx]) - - @update_features("llama::sdpa_with_kv_cache") def register_sdpa_with_kv_cache(): return OpFeatures( diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 2b3ac526179..4a71e906b63 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -10,8 +10,6 @@ import torch -from executorch.backends.vulkan.op_registry import check_llm_sdpa_node - from executorch.backends.vulkan.patterns.pattern_registry import ( PatternMatch, register_pattern_detector, @@ -33,6 +31,97 @@ def is_sdpa_with_kv_cache_node(node: Any) -> bool: return utils.node_has_target(node, "llama::sdpa_with_kv_cache") +# Positions of (query, key_cache, attn_mask, is_causal) in the op's args. +_LLM_SDPA_ARG_IDX = { + "llama::custom_sdpa": (0, 1, 4, 6), + "llama::sdpa_with_kv_cache": (0, 3, 7, 9), +} + + +def _is_update_cache_node(node: torch.fx.Node) -> bool: + if node.target in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ): + op = node.args[0] + return hasattr(op, "name") and op.name() == "llama::update_cache" + return utils.node_has_target(node, "llama::update_cache") + + +def _check_update_cache_node(node: torch.fx.Node) -> bool: + # custom_sdpa reads either the mutated cache directly, or the cache returned + # by the auto_functionalized update_cache. + readers = set(node.users) + for user in node.users: + readers.update(user.users) + if utils.node_has_target(node, "llama::update_cache") and isinstance( + node.args[1], torch.fx.Node + ): + readers.update(node.args[1].users) + return all( + check_llm_sdpa_node(reader) + for reader in readers + if utils.node_has_target(reader, "llama::custom_sdpa") + ) + + +def _check_llm_sdpa_mask( + attn_mask: torch.fx.Node, q: torch.fx.Node, cache: torch.fx.Node +) -> bool: + mask_val = attn_mask.meta.get("val", None) + q_val = q.meta.get("val", None) + cache_val = cache.meta.get("val", None) + if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val, cache_val)): + return False + if mask_val.dim() != 2 or mask_val.dtype != q_val.dtype: + return False + # The mask must be [S, C]. Only reject sizes that are known to mismatch. + return all( + not (isinstance(size, int) and isinstance(expected, int)) or size == expected + for size, expected in ( + (mask_val.shape[0], q_val.shape[1]), + (mask_val.shape[1], cache_val.shape[1]), + ) + ) + + +def check_llm_sdpa_node(node: torch.fx.Node) -> bool: + """ + The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D + [S, C] additive attn_mask (with is_causal unset) of the same dtype as the + query. Other configurations stay on CPU instead of failing at load time. + An update_cache stays on CPU with the custom_sdpa that reads its cache, so + that both see the same cache. + """ + if _is_update_cache_node(node): + return _check_update_cache_node(node) + + arg_idx = next( + ( + idx + for target, idx in _LLM_SDPA_ARG_IDX.items() + if utils.node_has_target(node, target) + ), + None, + ) + if arg_idx is None: + return True + q_idx, cache_idx, mask_idx, is_causal_idx = arg_idx + + def get_arg(idx: int, name: str, default: Any) -> Any: + if idx < len(node.args): + return node.args[idx] + return node.kwargs.get(name, default) + + attn_mask = get_arg(mask_idx, "attn_mask", None) + is_causal = get_arg(is_causal_idx, "is_causal", False) + if attn_mask is None: + return bool(is_causal) + if is_causal or not isinstance(attn_mask, torch.fx.Node): + return False + return _check_llm_sdpa_mask(attn_mask, node.args[q_idx], node.args[cache_idx]) + + class CausalSDPAMatch(PatternMatch): def __init__(self, custom_sdpa_node: torch.fx.Node) -> None: self.anchor_node = custom_sdpa_node diff --git a/backends/vulkan/targets.bzl b/backends/vulkan/targets.bzl index d2dee601399..dfba31b6cad 100644 --- a/backends/vulkan/targets.bzl +++ b/backends/vulkan/targets.bzl @@ -377,6 +377,7 @@ def define_common_targets(is_fbcode = False): ":utils_lib", "//caffe2:torch", "//executorch/exir/dialects:lib", + "//executorch/backends/vulkan/patterns:vulkan_patterns", "//executorch/backends/vulkan/serialization:lib", ] ) diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 84c0e1ffb87..39510344f0e 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -1085,8 +1085,10 @@ def _build( q_dtype=torch.float32, is_causal=False, ): - from executorch.backends.vulkan.op_registry import check_llm_sdpa_node - from executorch.backends.vulkan.patterns.sdpa import find_causal_sdpa_patterns + from executorch.backends.vulkan.patterns.sdpa import ( + check_llm_sdpa_node, + find_causal_sdpa_patterns, + ) from torch._subclasses.fake_tensor import FakeTensorMode fake_mode = FakeTensorMode() From 6928724b5cffb84581e3ec606659e33c701844a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 20 Oct 2026 14:39:07 +0200 Subject: [PATCH 08/17] Vulkan SDPA: compare a constant attn_mask's dtype after prepacking On a device without full fp16 buffer support a Half q falls back to Float, and prepacking the mask TensorRef applies the same fallback, so the serialized Half dtype must not be compared before it. Add an op test for a constant mask through both entry points. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 9 +-- backends/vulkan/test/op_tests/sdpa_test.cpp | 56 +++++++++++++++++-- 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 74bc341358e..b6e85077e01 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -768,11 +768,9 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { graph.val_is_none(is_causal) || !graph.extract_scalar(is_causal), "attn_mask and is_causal cannot both be set"); VK_CHECK_COND(graph.dim_of(attn_mask) == 2, "attn_mask must be 2D"); - VK_CHECK_COND( - graph.dtype_of(attn_mask) == graph.dtype_of(q_projected), - "attn_mask must have the same dtype as q"); // A constant mask arrives as a TensorRef, since the fused op handles its - // own prepacking. + // own prepacking. Its dtype is compared after prepacking, which applies + // the same Half -> Float fallback as q on devices without fp16 buffers. mask = graph.val_is_tref(attn_mask) ? prepack_standard( graph, @@ -780,6 +778,9 @@ void sdpa_impl(ComputeGraph& graph, const std::vector& args) { graph.storage_type_of(q_projected), utils::kWidthPacked) : attn_mask; + VK_CHECK_COND( + graph.dtype_of(mask) == graph.dtype_of(q_projected), + "attn_mask must have the same dtype as q"); check_attn_mask_sizes(graph, mask, q_projected, k_cache); VK_CHECK_COND( graph.storage_type_of(mask) == graph.storage_type_of(q_projected), diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 0d180df3000..898160212c7 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -937,16 +937,30 @@ void test_vulkan_llm_sdpa( const std::optional scale, vkcompute::utils::StorageType storage_type, at::ScalarType dtype = at::kFloat, - const bool use_custom_sdpa = false) { + const bool use_custom_sdpa = false, + const bool constant_mask = false) { using namespace vkcompute; const bool has_mask = mask_kind != LLMSDPAMask::CAUSAL; + // A constant mask is a TensorRef that the op prepacks. It cannot be resized, + // so every step must use the full seq_len. + const bool has_input_mask = has_mask && !constant_mask; int max_seq_len = 0; for (const LLMSDPAStep& step : steps) { ASSERT_LE(step.input_pos + step.seq_len, max_context_len); max_seq_len = std::max(max_seq_len, step.seq_len); } + if (constant_mask) { + ASSERT_EQ(mask_kind, LLMSDPAMask::RANDOM); + for (const LLMSDPAStep& step : steps) { + ASSERT_EQ(step.seq_len, max_seq_len); + } + } + // Kept alive until prepack, which reads the TensorRef's data + const at::Tensor constant_mask_data = constant_mask + ? (at::randn({max_seq_len, max_context_len}) * 2).to(dtype).contiguous() + : at::Tensor(); // Reference caches are kept in fp32 at::Tensor k_cache = at::zeros( @@ -972,7 +986,12 @@ void test_vulkan_llm_sdpa( from_at_scalartype(dtype), storage_type); IOValueRef r_mask = {kDummyValueRef, kDummyValueRef}; - if (has_mask) { + if (constant_mask) { + r_mask.value = graph.add_tensorref( + constant_mask_data.sizes().vec(), + from_at_scalartype(dtype), + constant_mask_data.const_data_ptr()); + } else if (has_mask) { r_mask = graph.add_input_tensor( {max_seq_len, max_context_len}, from_at_scalartype(dtype), @@ -1068,7 +1087,8 @@ void test_vulkan_llm_sdpa( if (mask_kind == LLMSDPAMask::SLIDING_WINDOW) { visible = at::logical_and(visible, k_pos > q_pos - sliding_window); } - at::Tensor mask = mask_kind == LLMSDPAMask::RANDOM + at::Tensor mask = constant_mask ? constant_mask_data + : mask_kind == LLMSDPAMask::RANDOM ? at::randn({seq_len, max_context_len}) * 2 : at::zeros({seq_len, max_context_len}) .masked_fill(at::logical_not(visible), -INFINITY); @@ -1092,7 +1112,7 @@ void test_vulkan_llm_sdpa( graph.resize_input(0, q.sizes().vec()); graph.resize_input(1, k.sizes().vec()); graph.resize_input(2, v.sizes().vec()); - if (has_mask) { + if (has_input_mask) { graph.resize_input(3, mask.sizes().vec()); } graph.propagate_resize(); @@ -1103,7 +1123,7 @@ void test_vulkan_llm_sdpa( r_k.staging, k.const_data_ptr(), k.numel(), from_at_scalartype(dtype)); graph.maybe_cast_and_copy_into_staging( r_v.staging, v.const_data_ptr(), v.numel(), from_at_scalartype(dtype)); - if (has_mask) { + if (has_input_mask) { graph.maybe_cast_and_copy_into_staging( r_mask.staging, mask.const_data_ptr(), @@ -1259,6 +1279,32 @@ TEST(VulkanSDPATest, test_sdpa_op_custom_sdpa_random_mask) { } } +// A constant mask arrives as a TensorRef that the op prepacks with q's storage +// type. In fp16 on a device without full fp16 buffer support, q falls back to +// fp32 and so does the prepacked mask. +TEST(VulkanSDPATest, test_sdpa_op_constant_mask) { + const std::vector steps = {{0, 4}, {2, 4}, {4, 4}}; + for (const auto storage_type : kLLMSDPAStorageTypes) { + for (const auto dtype : {at::kFloat, at::kHalf}) { + for (const bool use_custom_sdpa : {false, true}) { + test_vulkan_llm_sdpa( + steps, + 8, + 2, + 1, + 8, + LLMSDPAMask::RANDOM, + 0, + std::nullopt, + storage_type, + dtype, + use_custom_sdpa, + /*constant_mask=*/true); + } + } + } +} + // An explicit scale on the causal (unmasked) path. TEST(VulkanSDPATest, test_sdpa_op_causal_explicit_scale) { for (const auto storage_type : kLLMSDPAStorageTypes) { From cbd09cf31407047b5a3f432e0ea168f983767c52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 20 Oct 2026 14:39:35 +0200 Subject: [PATCH 09/17] Vulkan: check auto_functionalized sdpa_with_kv_cache mask configurations The partitioner passes the auto_functionalized wrapper to check_llm_sdpa_node, which then saw no LLM SDPA target and admitted every mask configuration. Resolve the wrapped op and read its schema kwargs, including the key_cache base and view of auto_functionalized_v2. --- backends/vulkan/patterns/sdpa.py | 133 ++++++++++++++++----- backends/vulkan/test/test_vulkan_passes.py | 69 +++++++++++ 2 files changed, 170 insertions(+), 32 deletions(-) diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 4a71e906b63..78167f4fe65 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -31,18 +31,93 @@ def is_sdpa_with_kv_cache_node(node: Any) -> bool: return utils.node_has_target(node, "llama::sdpa_with_kv_cache") -# Positions of (query, key_cache, attn_mask, is_causal) in the op's args. -_LLM_SDPA_ARG_IDX = { - "llama::custom_sdpa": (0, 1, 4, 6), - "llama::sdpa_with_kv_cache": (0, 3, 7, 9), +# Names and positions of (query, key_cache, attn_mask, is_causal) in each op's +# schema. +_LLM_SDPA_ARGS = { + "llama::custom_sdpa": ( + ("query", 0), + ("key", 1), + ("attn_mask", 4), + ("is_causal", 6), + ), + "llama::sdpa_with_kv_cache": ( + ("query", 0), + ("key_cache", 3), + ("attn_mask", 7), + ("is_causal", 9), + ), } +_AUTO_FUNCTIONALIZED = ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, +) + + +def _llm_sdpa_target(node: torch.fx.Node) -> Optional[str]: + """The LLM SDPA op called by node, directly or through auto_functionalized.""" + if node.target in _AUTO_FUNCTIONALIZED: + op = node.args[0] + name = op.name() if hasattr(op, "name") else None + return name if name in _LLM_SDPA_ARGS else None + return next( + (target for target in _LLM_SDPA_ARGS if utils.node_has_target(node, target)), + None, + ) + + +def _get_llm_sdpa_arg(node: torch.fx.Node, name: str, idx: int, default: Any) -> Any: + # auto_functionalized passes every schema argument as a kwarg, except that + # v2 replaces a mutable argument with metadata about its base. + if node.target not in _AUTO_FUNCTIONALIZED and idx < len(node.args): + return node.args[idx] + return node.kwargs.get(name, default) + + +def _get_v2_mutable_arg_shape(node: torch.fx.Node, name: str) -> Optional[list]: + """ + The shape of a mutable argument of an auto_functionalized_v2 node, which is + either one of _all_bases or a view of one. Unknown sizes are None. + """ + prefix = f"_{name}" + base_index = node.kwargs.get(f"{prefix}_base_index", None) + bases = node.kwargs.get("_all_bases", None) + if not isinstance(base_index, int) or not bases or base_index >= len(bases): + return None + base = bases[base_index] + base_val = base.meta.get("val", None) if isinstance(base, torch.fx.Node) else None + if not isinstance(base_val, torch.Tensor): + return None + if f"{prefix}_size" in node.kwargs: + # A view regenerated with as_strided + return list(node.kwargs[f"{prefix}_size"]) + shape = list(base_val.shape) + if f"{prefix}_slice_dim" in node.kwargs: + dim = node.kwargs[f"{prefix}_slice_dim"] + start = node.kwargs.get(f"{prefix}_slice_start", None) + end = node.kwargs.get(f"{prefix}_slice_end", None) + if all(isinstance(v, (int, type(None))) for v in (shape[dim], start, end)): + shape[dim] = len(range(*slice(start, end).indices(shape[dim]))) + else: + shape[dim] = None + # Otherwise the argument is the base itself, or an alias of it + return shape + + +def _get_llm_sdpa_cache_shape( + node: torch.fx.Node, name: str, idx: int +) -> Optional[list]: + cache = _get_llm_sdpa_arg(node, name, idx, None) + if cache is None and node.target == torch.ops.higher_order.auto_functionalized_v2: + return _get_v2_mutable_arg_shape(node, name) + cache_val = ( + cache.meta.get("val", None) if isinstance(cache, torch.fx.Node) else None + ) + return list(cache_val.shape) if isinstance(cache_val, torch.Tensor) else None + def _is_update_cache_node(node: torch.fx.Node) -> bool: - if node.target in ( - torch.ops.higher_order.auto_functionalized, - torch.ops.higher_order.auto_functionalized_v2, - ): + if node.target in _AUTO_FUNCTIONALIZED: op = node.args[0] return hasattr(op, "name") and op.name() == "llama::update_cache" return utils.node_has_target(node, "llama::update_cache") @@ -66,12 +141,13 @@ def _check_update_cache_node(node: torch.fx.Node) -> bool: def _check_llm_sdpa_mask( - attn_mask: torch.fx.Node, q: torch.fx.Node, cache: torch.fx.Node + attn_mask: torch.fx.Node, q: Any, cache_shape: Optional[list] ) -> bool: mask_val = attn_mask.meta.get("val", None) - q_val = q.meta.get("val", None) - cache_val = cache.meta.get("val", None) - if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val, cache_val)): + q_val = q.meta.get("val", None) if isinstance(q, torch.fx.Node) else None + if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val)): + return False + if cache_shape is None or len(cache_shape) < 2: return False if mask_val.dim() != 2 or mask_val.dtype != q_val.dtype: return False @@ -80,7 +156,7 @@ def _check_llm_sdpa_mask( not (isinstance(size, int) and isinstance(expected, int)) or size == expected for size, expected in ( (mask_val.shape[0], q_val.shape[1]), - (mask_val.shape[1], cache_val.shape[1]), + (mask_val.shape[1], cache_shape[1]), ) ) @@ -90,36 +166,29 @@ def check_llm_sdpa_node(node: torch.fx.Node) -> bool: The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D [S, C] additive attn_mask (with is_causal unset) of the same dtype as the query. Other configurations stay on CPU instead of failing at load time. - An update_cache stays on CPU with the custom_sdpa that reads its cache, so + The node may call the op directly or through auto_functionalized. An + update_cache stays on CPU with the custom_sdpa that reads its cache, so that both see the same cache. """ if _is_update_cache_node(node): return _check_update_cache_node(node) - arg_idx = next( - ( - idx - for target, idx in _LLM_SDPA_ARG_IDX.items() - if utils.node_has_target(node, target) - ), - None, - ) - if arg_idx is None: + target = _llm_sdpa_target(node) + if target is None: return True - q_idx, cache_idx, mask_idx, is_causal_idx = arg_idx + q_arg, cache_arg, mask_arg, is_causal_arg = _LLM_SDPA_ARGS[target] - def get_arg(idx: int, name: str, default: Any) -> Any: - if idx < len(node.args): - return node.args[idx] - return node.kwargs.get(name, default) - - attn_mask = get_arg(mask_idx, "attn_mask", None) - is_causal = get_arg(is_causal_idx, "is_causal", False) + attn_mask = _get_llm_sdpa_arg(node, *mask_arg, None) + is_causal = _get_llm_sdpa_arg(node, *is_causal_arg, False) if attn_mask is None: return bool(is_causal) if is_causal or not isinstance(attn_mask, torch.fx.Node): return False - return _check_llm_sdpa_mask(attn_mask, node.args[q_idx], node.args[cache_idx]) + return _check_llm_sdpa_mask( + attn_mask, + _get_llm_sdpa_arg(node, *q_arg, None), + _get_llm_sdpa_cache_shape(node, *cache_arg), + ) class CausalSDPAMatch(PatternMatch): diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 39510344f0e..6266bdf2be5 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -1140,3 +1140,72 @@ def test_mask_dtype_mismatch_is_rejected(self): def test_mask_shape_mismatch_is_rejected(self): self.assertFalse(self._build(mask_shape=(1, self.S, self.C))) self.assertFalse(self._build(mask_shape=(self.S, self.C - 1))) + + def _build_wrapped_sdpa_with_kv_cache( + self, wrapper, q_dtype=torch.float32, cache_slice=None + ): + from executorch.backends.vulkan.patterns.sdpa import check_llm_sdpa_node + from torch._subclasses.fake_tensor import FakeTensorMode + + fake_mode = FakeTensorMode() + graph = torch.fx.Graph() + + def placeholder(name, shape, dtype): + node = graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor(torch.empty(shape, dtype=dtype)) + return node + + q = placeholder("q", (1, self.S, self.H, self.D), q_dtype) + k_cache = placeholder("k_cache", (1, self.C, self.H, self.D), q_dtype) + v_cache = placeholder("v_cache", (1, self.C, self.H, self.D), q_dtype) + mask = placeholder("mask", (self.S, self.C), torch.float32) + kwargs = { + "query": q, + "key": q, + "value": q, + "start_pos": 0, + "seq_len": self.S, + "attn_mask": mask, + "drpout_p": 0.0, + "is_causal": False, + "scale": None, + } + if wrapper == torch.ops.higher_order.auto_functionalized: + kwargs.update(key_cache=k_cache, value_cache=v_cache) + else: + kwargs.update( + _all_bases=[k_cache, v_cache], + _key_cache_base_index=0, + _value_cache_base_index=1, + ) + if cache_slice is not None: + start, end = cache_slice + kwargs.update( + _key_cache_slice_dim=1, + _key_cache_slice_start=start, + _key_cache_slice_end=end, + ) + node = graph.call_function( + wrapper, (_NamedOpStub("llama::sdpa_with_kv_cache"),), kwargs + ) + return check_llm_sdpa_node(node) + + def test_auto_functionalized_sdpa_with_kv_cache(self): + # The partitioner passes the wrapper node, whose op args are kwargs. + for wrapper in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ): + self.assertTrue(self._build_wrapped_sdpa_with_kv_cache(wrapper)) + self.assertFalse( + self._build_wrapped_sdpa_with_kv_cache(wrapper, q_dtype=torch.float16) + ) + + def test_auto_functionalized_v2_cache_view(self): + wrapper = torch.ops.higher_order.auto_functionalized_v2 + self.assertTrue( + self._build_wrapped_sdpa_with_kv_cache(wrapper, cache_slice=(0, None)) + ) + self.assertFalse( + self._build_wrapped_sdpa_with_kv_cache(wrapper, cache_slice=(0, self.C - 1)) + ) From c793edc124610133b2e94b8b04afb27df0202678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 20 Oct 2026 14:39:36 +0200 Subject: [PATCH 10/17] Vulkan: read custom_sdpa's default args in the causal_sdpa pattern torch.export drops trailing arguments that equal their defaults, so a masked custom_sdpa with is_causal=False and no scale has five args and CausalSDPAMatch raised IndexError during partitioning. --- backends/vulkan/patterns/sdpa.py | 12 +++++------- backends/vulkan/test/test_vulkan_passes.py | 20 +++++++++++++++----- 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 78167f4fe65..3e66d5bea89 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -206,13 +206,11 @@ def __init__(self, custom_sdpa_node: torch.fx.Node) -> None: self.key_cache_node = custom_sdpa_node.args[1] self.value_cache_node = custom_sdpa_node.args[2] self.start_pos_node = custom_sdpa_node.args[3] - self.attn_mask_node = custom_sdpa_node.args[4] - self.dropout_p_node = custom_sdpa_node.args[5] - self.is_causal_node = custom_sdpa_node.args[6] - if len(custom_sdpa_node.args) > 7: - self.scale_node = custom_sdpa_node.args[7] - else: - self.scale_node = None + # torch.export drops trailing arguments that equal their defaults + self.attn_mask_node = _get_llm_sdpa_arg(custom_sdpa_node, "attn_mask", 4, None) + self.dropout_p_node = _get_llm_sdpa_arg(custom_sdpa_node, "drpout_p", 5, 0.0) + self.is_causal_node = _get_llm_sdpa_arg(custom_sdpa_node, "is_causal", 6, False) + self.scale_node = _get_llm_sdpa_arg(custom_sdpa_node, "scale", 7, None) # try to find update key cache node self.update_key_cache_node = None diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 6266bdf2be5..7f83305ad9d 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -1084,6 +1084,7 @@ def _build( mask_dtype=torch.float32, q_dtype=torch.float32, is_causal=False, + trim_defaults=False, ): from executorch.backends.vulkan.patterns.sdpa import ( check_llm_sdpa_node, @@ -1110,13 +1111,19 @@ def placeholder(name, shape, dtype): update_cache = graph.call_function( _NamedOpStub("llama::update_cache"), (k, k_cache, 0) ) - custom_sdpa = graph.call_function( - _NamedOpStub("llama::custom_sdpa"), - (q, k_cache, v_cache, 0, mask, 0.0, is_causal), - ) + args = (q, k_cache, v_cache, 0, mask, 0.0, is_causal) + if trim_defaults: + # torch.export drops trailing arguments that equal their defaults + assert not is_causal + args = args[:5] + custom_sdpa = graph.call_function(_NamedOpStub("llama::custom_sdpa"), args) supported = check_llm_sdpa_node(custom_sdpa) self.assertEqual(check_llm_sdpa_node(update_cache), supported) - self.assertEqual(find_causal_sdpa_patterns(custom_sdpa) is not None, supported) + match = find_causal_sdpa_patterns(custom_sdpa) + self.assertEqual(match is not None, supported) + if match is not None: + self.assertIs(match.attn_mask_node, mask) + self.assertEqual(match.is_causal_node, is_causal) return supported def test_causal_without_mask_is_supported(self): @@ -1128,6 +1135,9 @@ def test_non_causal_without_mask_is_rejected(self): def test_mask_is_supported(self): self.assertTrue(self._build(mask_shape=(self.S, self.C))) + def test_mask_with_trimmed_default_args_is_supported(self): + self.assertTrue(self._build(mask_shape=(self.S, self.C), trim_defaults=True)) + def test_mask_with_is_causal_is_rejected(self): self.assertFalse(self._build(mask_shape=(self.S, self.C), is_causal=True)) From 823ad760c080077dac8935c5495c59bc6f296498 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:44:58 +0100 Subject: [PATCH 11/17] Vulkan SDPA: read a buffer attn_mask in padded texel rows Since buffer tensors pad their packed dim to four, a width packed [S, C] buffer mask has a row stride of align_up_4(C) texels, not C elements. Bind the mask as a vec4 array and read one texel per 4 columns in both storages. The padding lanes only reach attention weights past C, which softmax ignores. Also guard the coop shader's causal tile skip with HAS_MASK instead of a constant false. --- .../glsl/sdpa_compute_attn_weights_coop.glsl | 27 +++++++------- .../glsl/sdpa_compute_attn_weights_tiled.glsl | 2 +- .../glsl/sdpa_fp_attn_weight_tile_store.glslh | 37 +++++++------------ 3 files changed, 27 insertions(+), 39 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 270cc873351..388a3269da8 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 @@ -43,7 +43,7 @@ ${layout_declare_tensor(B, "w", "t_attn_weights", DTYPE, IO_STORAGE, is_scalar_a ${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)} $if HAS_MASK: - ${layout_declare_tensor(B, "r", "t_mask", DTYPE, IO_STORAGE, is_scalar_array=True)} + ${layout_declare_tensor(B, "r", "t_mask", DTYPE, IO_STORAGE, is_scalar_array=False)} ${layout_declare_ubo(B, "ivec4", "q_sizes")} ${layout_declare_ubo(B, "ivec4", "k_sizes")} @@ -121,21 +121,20 @@ void main() { FPInputTile q_tile; FPWeightTile w_tile; +#ifndef HAS_MASK // 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. -#ifdef HAS_MASK - // The additive attn_mask replaces the causal mask, so no tile can be skipped. - const bool tile_in_mask_region = false; -#else - bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); -#endif + // negative infinity. An additive attn_mask replaces the causal mask, so with + // HAS_MASK no tile can be skipped. + 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); } // Otherwise, need to actually compute output tile - else { + else +#endif + { for (int d4 = worker_id; d4 < D4; d4 += NUM_WORKERS_PER_OUT) { load_q_projected_tile_with_checks( q_tile, @@ -185,12 +184,12 @@ void main() { // Only the first thread will write out the result if (worker_id == 0) { out_tile = partial_sums[0]; - // Apply scale and mask if the tile was not entirely in the mask region - if (!tile_in_mask_region) { #ifdef HAS_MASK - apply_scale(out_tile, inv_scale); - apply_attn_mask(out_tile, c, s); + apply_scale(out_tile, inv_scale); + apply_attn_mask(out_tile, c, s); #else + // Apply scale and mask if the tile was not entirely in the mask region + if (!tile_in_mask_region) { VEC4_T inv_scale_vec = VEC4_T(inv_scale); apply_scale_and_mask( out_tile, @@ -198,8 +197,8 @@ void main() { input_pos, c, s); -#endif } +#endif store_attn_weight_tile_with_checks( out_tile, diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl index 3facbfebdcd..addcb606ef6 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_tiled.glsl @@ -58,7 +58,7 @@ ${layout_declare_tensor(B, "r", "t_k", IN_DTYPE, K_CACHE_STORAGE, is_scalar_arra $if HAS_BIAS: ${layout_declare_tensor(B, "r", "t_bias", IN_DTYPE, IO_STORAGE, is_scalar_array=False)} $if HAS_MASK: - ${layout_declare_tensor(B, "r", "t_mask", IN_DTYPE, IO_STORAGE, is_scalar_array=True)} + ${layout_declare_tensor(B, "r", "t_mask", IN_DTYPE, IO_STORAGE, is_scalar_array=False)} ${layout_declare_ubo(B, "ivec4", "q_sizes")} ${layout_declare_ubo(B, "ivec4", "k_sizes")} diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh index a9db09f5ab8..ed70e294e8c 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_fp_attn_weight_tile_store.glslh @@ -15,9 +15,9 @@ * Tile precision is controlled by the caller via LINEAR_FP_OUTPUT_TILE_VEC4_T * (fused SDPA sets it to vec4 for fp32 accumulation; LLM SDPA leaves it as * VEC4_T for input-dtype accumulation). All helper functions below are - * available at all times and compile correctly in both modes. The only - * gated helper is apply_bias, which requires t_bias/bias_sizes and is - * therefore guarded by HAS_BIAS. + * available at all times and compile correctly in both modes, except + * apply_bias and apply_attn_mask, which require t_bias/bias_sizes and + * t_mask/mask_sizes and are therefore guarded by HAS_BIAS and HAS_MASK. * * Required macros/variables: * t_attn_weights — output buffer/texture @@ -155,41 +155,30 @@ void apply_bias( /* * Adds the LLM SDPA additive attn_mask, a 2D [S, C] tensor shared by every * head, to the tile. Requires t_mask and mask_sizes, and a c_idx_start that is - * a multiple of 4. A texture mask is read one texel per 4 columns. A buffer - * mask is read element by element: its rows are not padded, so they cannot be - * addressed in texels unless C is a multiple of 4. + * a multiple of 4. The mask is read one texel per 4 columns; buffer rows are + * padded to whole texels like texture rows. Padding lanes past C only reach + * attention weight lanes that softmax ignores. */ void apply_attn_mask( inout FPOutTile tile, const int c_idx_start, const int s_idx_start) { - const int mask_C = mask_sizes.x; + const int mask_C4 = div_up_4(mask_sizes.x); const int mask_S = mask_sizes.y; [[unroll]] for (int s = 0; s < TILE_M; ++s) { const int s_idx = s_idx_start + s; - if (s_idx >= mask_S) { - continue; - } [[unroll]] for (int c4 = 0; c4 < TILE_N4; ++c4) { - const int c_idx_base = c_idx_start + mul_4(c4); - if (c_idx_base >= mask_C) { + const int c4_idx = div_4(c_idx_start) + c4; + if (s_idx >= mask_S || c4_idx >= mask_C4) { continue; } -#ifndef INPUT_BUFFER - const vec4 mask_texel = - vec4(texelFetch(t_mask, ivec3(div_4(c_idx_base), s_idx, 0), 0)); -#endif - [[unroll]] for (int c4i = 0; c4i < 4; ++c4i) { - const int c_idx = c_idx_base + c4i; - if (c_idx < mask_C) { #ifdef INPUT_BUFFER - const float mask_val = float(t_mask[s_idx * mask_C + c_idx]); + const vec4 mask_texel = vec4(t_mask[s_idx * mask_C4 + c4_idx]); #else - const float mask_val = mask_texel[c4i]; + const vec4 mask_texel = + vec4(texelFetch(t_mask, ivec3(c4_idx, s_idx, 0), 0)); #endif - tile.data[s][c4][c4i] += T(mask_val); - } - } + tile.data[s][c4] += LINEAR_FP_OUTPUT_TILE_VEC4_T(mask_texel); } } } From 0cd1f70c1fb3d2611caf4edf072b59604e243485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:44:58 +0100 Subject: [PATCH 12/17] Vulkan SDPA: write only the S new rows in the kv-cache update Threads past S in the last work group wrote zeros to the cache rows after input_pos + S. The causal path never reads them, but a masked attention reads every row, so it saw zeros instead of the previous contents, depending on the local work group size. CPU update_cache also writes only S rows. --- .../runtime/graph/ops/glsl/sdpa_kv_cache_update.glsl | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_kv_cache_update.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_kv_cache_update.glsl index a7d94d5309c..dfb498535a0 100644 --- a/backends/vulkan/runtime/graph/ops/glsl/sdpa_kv_cache_update.glsl +++ b/backends/vulkan/runtime/graph/ops/glsl/sdpa_kv_cache_update.glsl @@ -83,14 +83,11 @@ void main() { const int c = s + input_pos; // idx along max_context_len dim const int C = cache_sizes.z; - if (d4 >= D4 || c >= C || h >= H) { + // Only the S rows starting at input_pos are written. The rows after them + // keep their contents, which a masked attention may still read. + if (d4 >= D4 || s >= S || c >= C || h >= H) { return; } - IN_VEC4_T in_texel = IN_VEC4_T(0.0); - if (s < S) { - in_texel = read_projected_d4(d4, h, s, D4, H, S); - } - - write_cache_d4(in_texel, d4, c, h, D4, C, H); + write_cache_d4(read_projected_d4(d4, h, s, D4, H, S), d4, c, h, D4, C, H); } From 7a0a0128d9e653ef772a066532e6aee5d43c4de0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:45:10 +0100 Subject: [PATCH 13/17] Vulkan SDPA: prepack the custom_sdpa op test caches With use_custom_sdpa the caches were uninitialized tensors, and a random or constant mask gives every cache row a finite weight, so rows not yet written held garbage while the reference held zeros. Prepack them from the zero caches, as in a delegated model. --- backends/vulkan/test/op_tests/sdpa_test.cpp | 25 +++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index d6e73627abd..ce6938d6700 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -1232,10 +1233,26 @@ void test_vulkan_llm_sdpa( : kDummyValueRef; if (use_custom_sdpa) { - const ValueRef r_k_cache = graph.add_tensor( - k_cache_data.sizes().vec(), from_at_scalartype(dtype), storage_type); - const ValueRef r_v_cache = graph.add_tensor( - v_cache_data.sizes().vec(), from_at_scalartype(dtype), storage_type); + // Prepacked from the zero caches, as in a delegated model, so that cache + // rows a mask attends before they are written match the reference. + const ValueRef r_k_cache = prepack_standard( + graph, + graph.add_tensorref( + k_cache_data.sizes().vec(), + from_at_scalartype(dtype), + k_cache_data.const_data_ptr()), + storage_type, + utils::kWidthPacked, + /*passthrough=*/true); + const ValueRef r_v_cache = prepack_standard( + graph, + graph.add_tensorref( + v_cache_data.sizes().vec(), + from_at_scalartype(dtype), + v_cache_data.const_data_ptr()), + storage_type, + utils::kWidthPacked, + /*passthrough=*/true); const ValueRef r_dummy_out = graph.add_tensor({1}, from_at_scalartype(dtype), utils::kBuffer); VK_GET_OP_FN("update_cache.default") From b1605c877a80be2116850b9a6e57d0524cb5f43f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:45:24 +0100 Subject: [PATCH 14/17] Vulkan SDPA: accept a Float attn_mask with a Half query in textures The CPU custom_sdpa requires a Float mask, so an fp16 model always has a Float mask with a Half query. Texture shaders sample the mask as floats whatever its dtype, as et_vk.sdpa already relies on. Factor the mask storage, layout and dtype checks shared by sdpa_impl and fused_sdpa_impl into check_sdpa_attn_mask, and add an op test for the mixed dtypes. --- .../vulkan/runtime/graph/ops/impl/SDPA.cpp | 76 ++++++++++--------- backends/vulkan/test/op_tests/sdpa_test.cpp | 52 +++++++++++-- 2 files changed, 87 insertions(+), 41 deletions(-) diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index 6fc0227d8cb..06a2ea37e50 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -658,6 +658,35 @@ void add_sdpa_compute_out_node( resize_sdpa_out_node)); } +// Checks that an additive attn_mask can be bound by the SDPA QK shaders, which +// read it in q's storage type. A buffer mask is read as contiguous rows in q's +// dtype. A texture mask is sampled as floats, so it may be Float or Half +// whatever q's dtype is. +void check_sdpa_attn_mask( + ComputeGraph& graph, + const ValueRef attn_mask, + const ValueRef q) { + VK_CHECK_COND( + graph.storage_type_of(attn_mask) == graph.storage_type_of(q), + "SDPA requires the attn_mask in the query's storage"); + if (graph.is_buffer_storage(attn_mask)) { + VK_CHECK_COND( + graph.is_contiguous_buffer_tensor(attn_mask), + "SDPA requires a contiguous buffer attn_mask"); + VK_CHECK_COND( + graph.dtype_of(attn_mask) == graph.dtype_of(q), + "SDPA requires a buffer attn_mask of the query's dtype"); + } else { + VK_CHECK_COND( + graph.is_contiguous_texture_tensor(attn_mask), + "SDPA requires a width packed attn_mask texture"); + VK_CHECK_COND( + graph.dtype_of(attn_mask) == vkapi::kFloat || + graph.dtype_of(attn_mask) == vkapi::kHalf, + "SDPA requires a Float or Half attn_mask texture"); + } +} + void check_attn_mask_sizes( ComputeGraph& graph, const ValueRef attn_mask, @@ -773,7 +802,7 @@ void sdpa_impl_with_shader_override( // As in the CPU op, an attn_mask replaces the causal mask: it is a 2D // [S, C] additive mask over every key in k_cache, and cannot be combined // with is_causal. Without one, the attention is assumed to be causal. The - // partitioner (op_registry.py) keeps other configurations on CPU. + // partitioner keeps other configurations on CPU. const bool has_mask = graph.val_is_not_none(attn_mask); ValueRef mask = kDummyValueRef; if (has_mask) { @@ -782,7 +811,7 @@ void sdpa_impl_with_shader_override( "attn_mask and is_causal cannot both be set"); VK_CHECK_COND(graph.dim_of(attn_mask) == 2, "attn_mask must be 2D"); // A constant mask arrives as a TensorRef, since the fused op handles its - // own prepacking. Its dtype is compared after prepacking, which applies + // own prepacking. Its dtype is checked after prepacking, which applies // the same Half -> Float fallback as q on devices without fp16 buffers. mask = graph.val_is_tref(attn_mask) ? prepack_standard( @@ -791,20 +820,8 @@ void sdpa_impl_with_shader_override( graph.storage_type_of(q_projected), utils::kWidthPacked) : attn_mask; - VK_CHECK_COND( - graph.dtype_of(mask) == graph.dtype_of(q_projected), - "attn_mask must have the same dtype as q"); + check_sdpa_attn_mask(graph, mask, q_projected); check_attn_mask_sizes(graph, mask, q_projected, k_cache); - VK_CHECK_COND( - graph.storage_type_of(mask) == graph.storage_type_of(q_projected), - "attn_mask must have the same storage type as q"); - // The shaders index a buffer mask as contiguous [S, C] rows, and a - // texture mask with the standard axis map. - VK_CHECK_COND( - graph.storage_type_of(mask) == utils::kBuffer - ? graph.is_contiguous_buffer_tensor(mask) - : graph.is_contiguous_texture_tensor(mask), - "attn_mask must be contiguous and width packed"); } else { VK_CHECK_COND( graph.val_is_none(is_causal) || graph.extract_scalar(is_causal), @@ -1059,30 +1076,19 @@ void fused_sdpa_impl(ComputeGraph& graph, const std::vector& args) { VK_CHECK_COND(graph.packed_dim_of(k) == WHCN::kWidthDim); VK_CHECK_COND(graph.packed_dim_of(v) == WHCN::kWidthDim); // The buffer shaders index every tensor as contiguous rows. - for (const ValueRef t : {q, k, v, attn_mask, out}) { + for (const ValueRef t : {q, k, v, out}) { VK_CHECK_COND( - graph.val_is_none(t) || !graph.val_is_tensor(t) || - !graph.is_buffer_storage(t) || graph.is_contiguous_buffer_tensor(t), + !graph.is_buffer_storage(t) || graph.is_contiguous_buffer_tensor(t), "fused SDPA requires contiguous buffer tensors"); } - // The QK shader binds the mask and attention weights in the query's storage, - // and the attention weights take the output's. - for (const ValueRef t : {attn_mask, out}) { - VK_CHECK_COND( - graph.val_is_none(t) || - graph.storage_type_of(t) == graph.storage_type_of(q), - "fused SDPA requires the attn_mask and output in the query's storage"); - } - // Buffer shaders read the mask in the query's dtype; texture shaders sample - // it as floats. + // The attention weights take the output's storage, and the QK shader binds + // them in the query's. VK_CHECK_COND( - graph.val_is_none(attn_mask) || - (graph.is_buffer_storage(q) - ? graph.dtype_of(attn_mask) == graph.dtype_of(q) - : graph.dtype_of(attn_mask) == vkapi::kFloat || - graph.dtype_of(attn_mask) == vkapi::kHalf), - "fused SDPA requires an attn_mask of the query's dtype, or a float one " - "in textures"); + graph.storage_type_of(out) == graph.storage_type_of(q), + "fused SDPA requires the output in the query's storage"); + if (graph.val_is_not_none(attn_mask)) { + check_sdpa_attn_mask(graph, attn_mask, q); + } // Compute scale const int32_t head_dim = graph.size_at(-1, q); diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index ce6938d6700..5a4cfe186dd 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -1162,9 +1162,12 @@ void test_vulkan_llm_sdpa( vkcompute::utils::StorageType storage_type, at::ScalarType dtype = at::kFloat, const bool use_custom_sdpa = false, - const bool constant_mask = false) { + const bool constant_mask = false, + const std::optional mask_dtype_override = std::nullopt) { using namespace vkcompute; + // The CPU op takes an fp32 mask, also for an fp16 query + const at::ScalarType mask_dtype = mask_dtype_override.value_or(dtype); const bool has_mask = mask_kind != LLMSDPAMask::CAUSAL; // A constant mask is a TensorRef that the op prepacks. It cannot be resized, // so every step must use the full seq_len. @@ -1183,7 +1186,9 @@ void test_vulkan_llm_sdpa( } // Kept alive until prepack, which reads the TensorRef's data const at::Tensor constant_mask_data = constant_mask - ? (at::randn({max_seq_len, max_context_len}) * 2).to(dtype).contiguous() + ? (at::randn({max_seq_len, max_context_len}) * 2) + .to(mask_dtype) + .contiguous() : at::Tensor(); // Reference caches are kept in fp32 @@ -1213,12 +1218,12 @@ void test_vulkan_llm_sdpa( if (constant_mask) { r_mask.value = graph.add_tensorref( constant_mask_data.sizes().vec(), - from_at_scalartype(dtype), + from_at_scalartype(mask_dtype), constant_mask_data.const_data_ptr()); } else if (has_mask) { r_mask = graph.add_input_tensor( {max_seq_len, max_context_len}, - from_at_scalartype(dtype), + from_at_scalartype(mask_dtype), storage_type); } @@ -1332,7 +1337,7 @@ void test_vulkan_llm_sdpa( ? at::randn({seq_len, max_context_len}) * 2 : at::zeros({seq_len, max_context_len}) .masked_fill(at::logical_not(visible), -INFINITY); - mask = mask.to(dtype); + mask = mask.to(mask_dtype); // Reference, in fp32 from the dtype-rounded inputs k_cache.slice(1, input_pos, input_pos + seq_len).copy_(k.to(at::kFloat)); @@ -1368,7 +1373,7 @@ void test_vulkan_llm_sdpa( r_mask.staging, mask.const_data_ptr(), mask.numel(), - from_at_scalartype(dtype)); + from_at_scalartype(mask_dtype)); } graph.execute(); @@ -1545,6 +1550,41 @@ TEST(VulkanSDPATest, test_sdpa_op_constant_mask) { } } +// The CPU op takes an fp32 mask, so an fp16 model has an fp32 mask. Texture +// shaders sample the mask as floats whatever q's dtype is. +TEST(VulkanSDPATest, test_sdpa_op_fp32_mask_fp16_query) { + for (const bool use_custom_sdpa : {false, true}) { + test_vulkan_llm_sdpa( + consecutive_steps({7, 1, 1, 1, 5, 1, 1}), + 64, + 8, + 2, + 32, + LLMSDPAMask::SLIDING_WINDOW, + 4, + 1.0, + vkcompute::utils::kTexture3D, + at::kHalf, + use_custom_sdpa, + /*constant_mask=*/false, + at::kFloat); + test_vulkan_llm_sdpa( + {{0, 4}, {2, 4}, {4, 4}}, + 8, + 2, + 1, + 8, + LLMSDPAMask::RANDOM, + 0, + std::nullopt, + vkcompute::utils::kTexture3D, + at::kHalf, + use_custom_sdpa, + /*constant_mask=*/true, + at::kFloat); + } +} + // An explicit scale on the causal (unmasked) path. TEST(VulkanSDPATest, test_sdpa_op_causal_explicit_scale) { for (const auto storage_type : kLLMSDPAStorageTypes) { From 3c5e027c6e40a6e32003cefa08bc354850e2093f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:45:24 +0100 Subject: [PATCH 15/17] Vulkan: simplify the LLM SDPA mask predicate Read the llama op's arguments once by schema name, directly or through auto_functionalized, and drop the auto_functionalized_v2 view shape reconstruction: a cache length that is not known AOT is checked by the runtime [S, C] resize check. Admit a Float mask with a Half query and force textures for it, like et_vk.sdpa. Match a masked custom_sdpa with a separate masked_sdpa pattern, so that a backend without mask support can skip its fusion. The predicate tests now use the real llama ops, and a lowering test exports a masked update_cache + custom_sdpa model. --- backends/vulkan/op_registry.py | 17 +- backends/vulkan/patterns/sdpa.py | 235 ++++++++---------- backends/vulkan/test/test_vulkan_passes.py | 264 +++++++++++++-------- 3 files changed, 288 insertions(+), 228 deletions(-) diff --git a/backends/vulkan/op_registry.py b/backends/vulkan/op_registry.py index dae6a748346..b80ea32d3e9 100644 --- a/backends/vulkan/op_registry.py +++ b/backends/vulkan/op_registry.py @@ -13,7 +13,10 @@ import executorch.backends.vulkan.custom_ops_lib # noqa import executorch.backends.vulkan.utils as utils import torch -from executorch.backends.vulkan.patterns.sdpa import check_llm_sdpa_node +from executorch.backends.vulkan.patterns.sdpa import ( + check_llm_sdpa_node, + llm_sdpa_mask_needs_texture, +) from executorch.exir.dialects._ops import ops as exir_ops from executorch.exir.dialects.edge._ops import EdgeOpOverload @@ -1190,6 +1193,16 @@ def register_q8ta_linear_gemv(): # ============================================================================= +def pick_llm_sdpa_storage( + node: torch.fx.Node, +) -> Tuple[utils.TensorRepSet, utils.TensorRepSet]: + # Buffer shaders read attn_mask in the query's dtype; texture shaders + # sample it as floats. + if llm_sdpa_mask_needs_texture(node): + return utils.WIDTH_PACKED_TEXTURE, utils.WIDTH_PACKED_TEXTURE + return utils.CONTIGUOUS_ANY, utils.CONTIGUOUS_ANY + + @update_features("llama::sdpa_with_kv_cache") def register_sdpa_with_kv_cache(): return OpFeatures( @@ -1198,6 +1211,7 @@ def register_sdpa_with_kv_cache(): supports_resize=True, supports_prepacking=True, are_node_inputs_supported_fn=check_llm_sdpa_node, + pick_io_storage_fn=pick_llm_sdpa_storage, ) @@ -1213,6 +1227,7 @@ def register_sdpa_cpp_ops(): inputs_dtypes=utils.FP_T, supports_resize=True, are_node_inputs_supported_fn=check_llm_sdpa_node, + pick_io_storage_fn=pick_llm_sdpa_storage, ) diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 8871a02d199..4cd9895374c 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -4,7 +4,7 @@ # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. -from typing import Any, Optional +from typing import Any, Dict, List, Optional, Tuple import executorch.backends.vulkan.utils as utils @@ -45,163 +45,115 @@ def find_cache_update( return None -# Names and positions of (query, key_cache, attn_mask, is_causal) in each op's -# schema. -_LLM_SDPA_ARGS = { - "llama::custom_sdpa": ( - ("query", 0), - ("key", 1), - ("attn_mask", 4), - ("is_causal", 6), - ), - "llama::sdpa_with_kv_cache": ( - ("query", 0), - ("key_cache", 3), - ("attn_mask", 7), - ("is_causal", 9), - ), -} - _AUTO_FUNCTIONALIZED = ( torch.ops.higher_order.auto_functionalized, torch.ops.higher_order.auto_functionalized_v2, ) - -def _llm_sdpa_target(node: torch.fx.Node) -> Optional[str]: - """The LLM SDPA op called by node, directly or through auto_functionalized.""" - if node.target in _AUTO_FUNCTIONALIZED: - op = node.args[0] - name = op.name() if hasattr(op, "name") else None - return name if name in _LLM_SDPA_ARGS else None - return next( - (target for target in _LLM_SDPA_ARGS if utils.node_has_target(node, target)), - None, - ) - - -def _get_llm_sdpa_arg(node: torch.fx.Node, name: str, idx: int, default: Any) -> Any: - # auto_functionalized passes every schema argument as a kwarg, except that - # v2 replaces a mutable argument with metadata about its base. - if node.target not in _AUTO_FUNCTIONALIZED and idx < len(node.args): - return node.args[idx] - return node.kwargs.get(name, default) +# The key cache argument of each LLM SDPA op, whose dim 1 is the cache length. +_LLM_SDPA_KEY_CACHE_ARG = { + "llama::custom_sdpa": "key", + "llama::sdpa_with_kv_cache": "key_cache", +} -def _get_v2_mutable_arg_shape(node: torch.fx.Node, name: str) -> Optional[list]: +def get_llama_op_args(node: torch.fx.Node) -> Tuple[Optional[str], Dict[str, Any]]: """ - The shape of a mutable argument of an auto_functionalized_v2 node, which is - either one of _all_bases or a view of one. Unknown sizes are None. + The llama op called by node, directly or through auto_functionalized, and + its arguments by schema name, with defaults for trimmed trailing args. + auto_functionalized_v2 passes a mutable argument as metadata about its + base instead, so that argument is missing. """ - prefix = f"_{name}" - base_index = node.kwargs.get(f"{prefix}_base_index", None) - bases = node.kwargs.get("_all_bases", None) - if not isinstance(base_index, int) or not bases or base_index >= len(bases): - return None - base = bases[base_index] - base_val = base.meta.get("val", None) if isinstance(base, torch.fx.Node) else None - if not isinstance(base_val, torch.Tensor): - return None - if f"{prefix}_size" in node.kwargs: - # A view regenerated with as_strided - return list(node.kwargs[f"{prefix}_size"]) - shape = list(base_val.shape) - if f"{prefix}_slice_dim" in node.kwargs: - dim = node.kwargs[f"{prefix}_slice_dim"] - start = node.kwargs.get(f"{prefix}_slice_start", None) - end = node.kwargs.get(f"{prefix}_slice_end", None) - if all(isinstance(v, (int, type(None))) for v in (shape[dim], start, end)): - shape[dim] = len(range(*slice(start, end).indices(shape[dim]))) - else: - shape[dim] = None - # Otherwise the argument is the base itself, or an alias of it - return shape - - -def _get_llm_sdpa_cache_shape( - node: torch.fx.Node, name: str, idx: int -) -> Optional[list]: - cache = _get_llm_sdpa_arg(node, name, idx, None) - if cache is None and node.target == torch.ops.higher_order.auto_functionalized_v2: - return _get_v2_mutable_arg_shape(node, name) - cache_val = ( - cache.meta.get("val", None) if isinstance(cache, torch.fx.Node) else None - ) - return list(cache_val.shape) if isinstance(cache_val, torch.Tensor) else None - - -def _is_update_cache_node(node: torch.fx.Node) -> bool: + if node.op != "call_function": + return None, {} if node.target in _AUTO_FUNCTIONALIZED: op = node.args[0] - return hasattr(op, "name") and op.name() == "llama::update_cache" - return utils.node_has_target(node, "llama::update_cache") + return (op.name() if hasattr(op, "name") else None), dict(node.kwargs) + schema = getattr(node.target, "_schema", None) + if schema is None or not schema.name.startswith("llama::"): + return None, {} + args = {} + for i, arg in enumerate(schema.arguments): + if i < len(node.args): + args[arg.name] = node.args[i] + else: + args[arg.name] = node.kwargs.get(arg.name, arg.default_value) + return schema.name, args -def _check_update_cache_node(node: torch.fx.Node) -> bool: +def get_update_cache_readers(node: torch.fx.Node) -> List[torch.fx.Node]: + """The custom_sdpa nodes that read the cache an update_cache writes.""" # custom_sdpa reads either the mutated cache directly, or the cache returned # by the auto_functionalized update_cache. readers = set(node.users) for user in node.users: readers.update(user.users) - if utils.node_has_target(node, "llama::update_cache") and isinstance( - node.args[1], torch.fx.Node - ): - readers.update(node.args[1].users) - return all( - check_llm_sdpa_node(reader) - for reader in readers - if utils.node_has_target(reader, "llama::custom_sdpa") - ) + _, args = get_llama_op_args(node) + if isinstance(args.get("cache"), torch.fx.Node): + readers.update(args["cache"].users) + return [r for r in readers if get_llama_op_args(r)[0] == "llama::custom_sdpa"] -def _check_llm_sdpa_mask( - attn_mask: torch.fx.Node, q: Any, cache_shape: Optional[list] -) -> bool: - mask_val = attn_mask.meta.get("val", None) - q_val = q.meta.get("val", None) if isinstance(q, torch.fx.Node) else None - if not all(isinstance(v, torch.Tensor) for v in (mask_val, q_val)): - return False - if cache_shape is None or len(cache_shape) < 2: - return False - if mask_val.dim() != 2 or mask_val.dtype != q_val.dtype: - return False - # The mask must be [S, C]. Only reject sizes that are known to mismatch. - return all( - not (isinstance(size, int) and isinstance(expected, int)) or size == expected - for size, expected in ( - (mask_val.shape[0], q_val.shape[1]), - (mask_val.shape[1], cache_shape[1]), +def _node_val(arg: Any) -> Optional[torch.Tensor]: + val = arg.meta.get("val", None) if isinstance(arg, torch.fx.Node) else None + return val if isinstance(val, torch.Tensor) else None + + +def llm_sdpa_mask_needs_texture(node: torch.fx.Node) -> bool: + """ + Whether an LLM SDPA node (or an update_cache whose cache it reads) has an + attn_mask in a different dtype than the query. Only the texture shaders, + which sample the mask as floats, can read it. + """ + name, args = get_llama_op_args(node) + if name == "llama::update_cache": + return any( + llm_sdpa_mask_needs_texture(r) for r in get_update_cache_readers(node) ) - ) + mask_val = _node_val(args.get("attn_mask")) + q_val = _node_val(args.get("query")) + return mask_val is not None and q_val is not None and mask_val.dtype != q_val.dtype + + +def llm_sdpa_has_attn_mask(node: torch.fx.Node) -> bool: + """Whether an LLM SDPA node, or a custom_sdpa reading an update_cache's + cache, has an attn_mask.""" + name, args = get_llama_op_args(node) + if name == "llama::update_cache": + return any(llm_sdpa_has_attn_mask(r) for r in get_update_cache_readers(node)) + return args.get("attn_mask") is not None def check_llm_sdpa_node(node: torch.fx.Node) -> bool: """ The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D - [S, C] additive attn_mask (with is_causal unset) of the same dtype as the - query. Other configurations stay on CPU instead of failing at load time. - The node may call the op directly or through auto_functionalized. An + [S, C] fp32 or fp16 additive attn_mask with is_causal unset. Other + configurations stay on CPU instead of failing at load time. An update_cache stays on CPU with the custom_sdpa that reads its cache, so that both see the same cache. """ - if _is_update_cache_node(node): - return _check_update_cache_node(node) - - target = _llm_sdpa_target(node) - if target is None: + name, args = get_llama_op_args(node) + if name == "llama::update_cache": + return all(check_llm_sdpa_node(r) for r in get_update_cache_readers(node)) + if name not in _LLM_SDPA_KEY_CACHE_ARG: return True - q_arg, cache_arg, mask_arg, is_causal_arg = _LLM_SDPA_ARGS[target] - attn_mask = _get_llm_sdpa_arg(node, *mask_arg, None) - is_causal = _get_llm_sdpa_arg(node, *is_causal_arg, False) + attn_mask = args.get("attn_mask") if attn_mask is None: - return bool(is_causal) - if is_causal or not isinstance(attn_mask, torch.fx.Node): + return bool(args.get("is_causal")) + mask_val = _node_val(attn_mask) + q_val = _node_val(args.get("query")) + if args.get("is_causal") or mask_val is None or q_val is None: + return False + if mask_val.dim() != 2 or not {mask_val.dtype, q_val.dtype} <= utils.FP_T: return False - return _check_llm_sdpa_mask( - attn_mask, - _get_llm_sdpa_arg(node, *q_arg, None), - _get_llm_sdpa_cache_shape(node, *cache_arg), + # The mask must be [S, C]. Sizes that are symbolic, or a cache that + # auto_functionalized_v2 passes as a base, are checked at runtime. + cache_val = _node_val(args.get(_LLM_SDPA_KEY_CACHE_ARG[name])) + expected = [q_val.shape[1], None if cache_val is None else cache_val.shape[1]] + return all( + not isinstance(size, int) or not isinstance(exp, int) or size == exp + for size, exp in zip(mask_val.shape, expected) ) @@ -221,10 +173,11 @@ def __init__(self, custom_sdpa_node: torch.fx.Node) -> None: self.value_cache_node = custom_sdpa_node.args[2] self.start_pos_node = custom_sdpa_node.args[3] # torch.export drops trailing arguments that equal their defaults - self.attn_mask_node = _get_llm_sdpa_arg(custom_sdpa_node, "attn_mask", 4, None) - self.dropout_p_node = _get_llm_sdpa_arg(custom_sdpa_node, "drpout_p", 5, 0.0) - self.is_causal_node = _get_llm_sdpa_arg(custom_sdpa_node, "is_causal", 6, False) - self.scale_node = _get_llm_sdpa_arg(custom_sdpa_node, "scale", 7, None) + _, args = get_llama_op_args(custom_sdpa_node) + self.attn_mask_node = args.get("attn_mask") + self.dropout_p_node = args.get("drpout_p", 0.0) + self.is_causal_node = args.get("is_causal", False) + self.scale_node = args.get("scale") nodes_before_attention = set() for node in custom_sdpa_node.graph.nodes: @@ -266,11 +219,10 @@ def __init__(self, custom_sdpa_node: torch.fx.Node) -> None: ) -@register_pattern_detector("causal_sdpa") -def find_causal_sdpa_patterns( - node: torch.fx.Node, +def _find_llm_sdpa_pattern( + node: torch.fx.Node, with_attn_mask: bool ) -> Optional[CausalSDPAMatch]: - if not is_custom_sdpa_node(node): + if not is_custom_sdpa_node(node) or llm_sdpa_has_attn_mask(node) != with_attn_mask: return None # A matched node is delegated without the partitioner's per-op checks, so @@ -285,12 +237,29 @@ def find_causal_sdpa_patterns( return None +@register_pattern_detector("causal_sdpa") +def find_causal_sdpa_patterns( + node: torch.fx.Node, +) -> Optional[CausalSDPAMatch]: + return _find_llm_sdpa_pattern(node, with_attn_mask=False) + + +# The same fusion for a custom_sdpa with an additive attn_mask, as a separate +# pattern so that backends without mask support can skip it. +@register_pattern_detector("masked_sdpa") +def find_masked_sdpa_patterns( + node: torch.fx.Node, +) -> Optional[CausalSDPAMatch]: + return _find_llm_sdpa_pattern(node, with_attn_mask=True) + + ## ## Pattern Replacement ## @register_pattern_replacement("causal_sdpa") +@register_pattern_replacement("masked_sdpa") def replace_custom_sdpa_with_causal_sdpa( ep: Optional[ExportedProgram], graph_module: torch.fx.GraphModule, diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 342fcfa0343..c910719917e 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -21,7 +21,10 @@ from executorch.backends.vulkan.partitioner.vulkan_partitioner import VulkanPartitioner from executorch.backends.vulkan.patterns.conv2d_with_epilogue import activation_of from executorch.backends.vulkan.patterns.swiglu import find_swiglu_pattern -from executorch.backends.vulkan.serialization.vulkan_graph_schema import VkDataType +from executorch.backends.vulkan.serialization.vulkan_graph_schema import ( + VkDataType, + VkStorageType, +) from executorch.backends.vulkan.serialization.vulkan_graph_serialize import ( extract_vk_flatbuffer, flatbuffer_to_vk_graph, @@ -2236,30 +2239,25 @@ def forward(self, x): replace_pass.call(ep.graph_module) -class _NamedOpStub: - """Stands in for a llama custom op, which may not be registered here.""" - - def __init__(self, name: str) -> None: - self._name = name - self.__name__ = name.replace("::", "_") - - def name(self) -> str: - return self._name - - def __call__(self, *args): - raise NotImplementedError - - class TestLLMSDPAPartitionerCheck(unittest.TestCase): """ check_llm_sdpa_node keeps llama::custom_sdpa / update_cache configurations that the Vulkan SDPA cannot run on CPU, instead of failing at load time. The - causal_sdpa pattern must not match them either, since a matched node is - delegated without the per-op checks. + causal_sdpa and masked_sdpa patterns must not match them either, since a + matched node is delegated without the per-op checks. """ S, C, H, D = 4, 16, 2, 8 + @classmethod + def setUpClass(cls) -> None: + from executorch.extension.llm.custom_ops import custom_ops # noqa: F401 + + def _placeholder(self, graph, fake_mode, name, shape, dtype): + node = graph.placeholder(name) + node.meta["val"] = fake_mode.from_tensor(torch.empty(shape, dtype=dtype)) + return node + def _build( self, mask_shape=None, @@ -2271,43 +2269,49 @@ def _build( from executorch.backends.vulkan.patterns.sdpa import ( check_llm_sdpa_node, find_causal_sdpa_patterns, + find_masked_sdpa_patterns, + llm_sdpa_mask_needs_texture, ) from torch._subclasses.fake_tensor import FakeTensorMode fake_mode = FakeTensorMode() graph = torch.fx.Graph() - - def placeholder(name, shape, dtype): - node = graph.placeholder(name) - node.meta["val"] = fake_mode.from_tensor(torch.empty(shape, dtype=dtype)) - return node - - q = placeholder("q", (1, self.S, self.H, self.D), q_dtype) - k = placeholder("k", (1, self.S, self.H, self.D), q_dtype) - v = placeholder("v", (1, self.S, self.H, self.D), q_dtype) - k_cache = placeholder("k_cache", (1, self.C, self.H, self.D), q_dtype) - v_cache = placeholder("v_cache", (1, self.C, self.H, self.D), q_dtype) + qkv_shape = (1, self.S, self.H, self.D) + cache_shape = (1, self.C, self.H, self.D) + q = self._placeholder(graph, fake_mode, "q", qkv_shape, q_dtype) + k = self._placeholder(graph, fake_mode, "k", qkv_shape, q_dtype) + v = self._placeholder(graph, fake_mode, "v", qkv_shape, q_dtype) + k_cache = self._placeholder(graph, fake_mode, "k_cache", cache_shape, q_dtype) + v_cache = self._placeholder(graph, fake_mode, "v_cache", cache_shape, q_dtype) mask = None if mask_shape is not None: - mask = placeholder("mask", mask_shape, mask_dtype) + mask = self._placeholder(graph, fake_mode, "mask", mask_shape, mask_dtype) update_cache = graph.call_function( - _NamedOpStub("llama::update_cache"), (k, k_cache, 0) + torch.ops.llama.update_cache.default, (k, k_cache, 0) ) - graph.call_function(_NamedOpStub("llama::update_cache"), (v, v_cache, 0)) + graph.call_function(torch.ops.llama.update_cache.default, (v, v_cache, 0)) args = (q, k_cache, v_cache, 0, mask, 0.0, is_causal) if trim_defaults: # torch.export drops trailing arguments that equal their defaults assert not is_causal args = args[:5] - custom_sdpa = graph.call_function(_NamedOpStub("llama::custom_sdpa"), args) + custom_sdpa = graph.call_function(torch.ops.llama.custom_sdpa.default, args) + graph.output(custom_sdpa) + supported = check_llm_sdpa_node(custom_sdpa) self.assertEqual(check_llm_sdpa_node(update_cache), supported) - match = find_causal_sdpa_patterns(custom_sdpa) - self.assertEqual(match is not None, supported) + causal_match = find_causal_sdpa_patterns(custom_sdpa) + masked_match = find_masked_sdpa_patterns(custom_sdpa) + self.assertEqual(causal_match is not None, supported and mask_shape is None) + self.assertEqual(masked_match is not None, supported and mask_shape is not None) + match = causal_match or masked_match if match is not None: self.assertIs(match.attn_mask_node, mask) self.assertEqual(match.is_causal_node, is_causal) + needs_texture = mask is not None and mask_dtype != q_dtype + self.assertEqual(llm_sdpa_mask_needs_texture(custom_sdpa), needs_texture) + self.assertEqual(llm_sdpa_mask_needs_texture(update_cache), needs_texture) return supported def test_causal_without_mask_is_supported(self): @@ -2325,81 +2329,153 @@ def test_mask_with_trimmed_default_args_is_supported(self): def test_mask_with_is_causal_is_rejected(self): self.assertFalse(self._build(mask_shape=(self.S, self.C), is_causal=True)) - def test_mask_dtype_mismatch_is_rejected(self): + def test_fp32_mask_with_fp16_query_needs_texture(self): # The CPU op requires an fp32 mask, also for an fp16 query. + self.assertTrue(self._build(mask_shape=(self.S, self.C), q_dtype=torch.float16)) + + def test_non_float_mask_is_rejected(self): self.assertFalse( - self._build(mask_shape=(self.S, self.C), q_dtype=torch.float16) + self._build(mask_shape=(self.S, self.C), mask_dtype=torch.bool) ) def test_mask_shape_mismatch_is_rejected(self): self.assertFalse(self._build(mask_shape=(1, self.S, self.C))) self.assertFalse(self._build(mask_shape=(self.S, self.C - 1))) - def _build_wrapped_sdpa_with_kv_cache( - self, wrapper, q_dtype=torch.float32, cache_slice=None - ): + def test_auto_functionalized_sdpa_with_kv_cache(self): from executorch.backends.vulkan.patterns.sdpa import check_llm_sdpa_node from torch._subclasses.fake_tensor import FakeTensorMode - fake_mode = FakeTensorMode() - graph = torch.fx.Graph() - - def placeholder(name, shape, dtype): - node = graph.placeholder(name) - node.meta["val"] = fake_mode.from_tensor(torch.empty(shape, dtype=dtype)) - return node - - q = placeholder("q", (1, self.S, self.H, self.D), q_dtype) - k_cache = placeholder("k_cache", (1, self.C, self.H, self.D), q_dtype) - v_cache = placeholder("v_cache", (1, self.C, self.H, self.D), q_dtype) - mask = placeholder("mask", (self.S, self.C), torch.float32) - kwargs = { - "query": q, - "key": q, - "value": q, - "start_pos": 0, - "seq_len": self.S, - "attn_mask": mask, - "drpout_p": 0.0, - "is_causal": False, - "scale": None, - } - if wrapper == torch.ops.higher_order.auto_functionalized: - kwargs.update(key_cache=k_cache, value_cache=v_cache) - else: - kwargs.update( - _all_bases=[k_cache, v_cache], - _key_cache_base_index=0, - _value_cache_base_index=1, + # The partitioner passes the wrapper node, whose op args are kwargs. v2 + # passes the caches as bases, so their length is checked at runtime. + for wrapper, mask_len in product( + ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ), + (self.C, self.C - 1), + ): + fake_mode = FakeTensorMode() + graph = torch.fx.Graph() + q_shape = (1, self.S, self.H, self.D) + cache_shape = (1, self.C, self.H, self.D) + q = self._placeholder(graph, fake_mode, "q", q_shape, torch.float32) + k_cache = self._placeholder( + graph, fake_mode, "k_cache", cache_shape, torch.float32 + ) + v_cache = self._placeholder( + graph, fake_mode, "v_cache", cache_shape, torch.float32 + ) + mask = self._placeholder( + graph, fake_mode, "mask", (self.S, mask_len), torch.float32 ) - if cache_slice is not None: - start, end = cache_slice + kwargs = { + "query": q, + "key": q, + "value": q, + "start_pos": 0, + "seq_len": self.S, + "attn_mask": mask, + "drpout_p": 0.0, + "is_causal": False, + "scale": None, + } + if wrapper == torch.ops.higher_order.auto_functionalized: + kwargs.update(key_cache=k_cache, value_cache=v_cache) + else: kwargs.update( - _key_cache_slice_dim=1, - _key_cache_slice_start=start, - _key_cache_slice_end=end, + _all_bases=[k_cache, v_cache], + _key_cache_base_index=0, + _value_cache_base_index=1, ) - node = graph.call_function( - wrapper, (_NamedOpStub("llama::sdpa_with_kv_cache"),), kwargs + node = graph.call_function( + wrapper, (torch.ops.llama.sdpa_with_kv_cache.default,), kwargs + ) + self.assertEqual( + check_llm_sdpa_node(node), + mask_len == self.C + or wrapper == torch.ops.higher_order.auto_functionalized_v2, + ) + + +class _LLMSDPAModule(torch.nn.Module): + S, C, H, D = 4, 16, 2, 8 + + def __init__(self, dtype: torch.dtype) -> None: + super().__init__() + cache_shape = (1, self.C, self.H, self.D) + self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype)) + self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=dtype)) + + def forward(self, q, k, v, mask, input_pos): + pos = input_pos.item() + torch._check(pos >= 0) + torch._check(pos + self.S <= self.C) + torch.ops.llama.update_cache(k, self.k_cache, pos) + torch.ops.llama.update_cache(v, self.v_cache, pos) + out = torch.ops.llama.custom_sdpa( + q, self.k_cache, self.v_cache, pos, mask, 0.0, False + ) + return out * 2.0 + + @classmethod + def example_inputs(cls, dtype: torch.dtype, mask_dtype: torch.dtype): + qkv_shape = (1, cls.S, cls.H, cls.D) + return ( + torch.randn(qkv_shape, dtype=dtype), + torch.randn(qkv_shape, dtype=dtype), + torch.randn(qkv_shape, dtype=dtype), + torch.randn(cls.S, cls.C, dtype=mask_dtype), + torch.tensor([0]), + ) + + +class TestLLMSDPAMaskLowering(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + from executorch.extension.llm.custom_ops import custom_ops # noqa: F401 + + def _lower(self, dtype: torch.dtype, mask_dtype: torch.dtype): + from executorch.exir.backend.utils import get_non_lowered_nodes + from executorch.exir.lowered_backend_module import get_lowered_submodules + + ep = torch.export.export( + _LLMSDPAModule(dtype), + _LLMSDPAModule.example_inputs(dtype, mask_dtype), + strict=False, + ) + lowered = to_edge_transform_and_lower(ep, partitioner=[VulkanPartitioner()]) + graph_module = lowered.exported_program().graph_module + cpu_ops = { + node.target + for node in get_non_lowered_nodes(graph_module.graph) + if node.op == "call_function" + } + submodules = get_lowered_submodules(graph_module) + self.assertEqual(len(submodules), 1) + vk_graph = flatbuffer_to_vk_graph( + extract_vk_flatbuffer(submodules[0][1].processed_bytes) ) - return check_llm_sdpa_node(node) + return cpu_ops, vk_graph - def test_auto_functionalized_sdpa_with_kv_cache(self): - # The partitioner passes the wrapper node, whose op args are kwargs. - for wrapper in ( - torch.ops.higher_order.auto_functionalized, - torch.ops.higher_order.auto_functionalized_v2, - ): - self.assertTrue(self._build_wrapped_sdpa_with_kv_cache(wrapper)) + def test_masked_custom_sdpa_is_delegated(self): + for dtype in (torch.float32, torch.float16): + # The CPU op requires an fp32 mask, also for an fp16 query. + cpu_ops, vk_graph = self._lower(dtype, torch.float32) self.assertFalse( - self._build_wrapped_sdpa_with_kv_cache(wrapper, q_dtype=torch.float16) + [ + op + for op in cpu_ops + if "llama" in str(op) or "auto_functionalized" in str(op) + ] ) - - def test_auto_functionalized_v2_cache_view(self): - wrapper = torch.ops.higher_order.auto_functionalized_v2 - self.assertTrue( - self._build_wrapped_sdpa_with_kv_cache(wrapper, cache_slice=(0, None)) - ) - self.assertFalse( - self._build_wrapped_sdpa_with_kv_cache(wrapper, cache_slice=(0, self.C - 1)) - ) + masks = [ + value.value + for value in vk_graph.values + if hasattr(value.value, "dims") + and list(value.value.dims) == [_LLMSDPAModule.S, _LLMSDPAModule.C] + ] + self.assertEqual(len(masks), 1) + if dtype != torch.float32: + # Only the texture shaders can read a mask of another dtype. + self.assertEqual(masks[0].storage_type, VkStorageType.TEXTURE_3D) From 3fcd951be313f3c820147fbdb7b511f9bc43b57d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Tue, 17 Nov 2026 13:45:24 +0100 Subject: [PATCH 16/17] WebGPU: keep masked LLM SDPA on CPU The WebGPU sdpa_with_kv_cache rejects attn_mask at init. Skip the masked_sdpa fusion and reject a masked custom_sdpa, sdpa_with_kv_cache and the update_cache it reads. Op feature overrides now also match a custom op by its registered name. --- .../vulkan/partitioner/vulkan_partitioner.py | 3 + backends/webgpu/partitioner/BUCK | 1 + backends/webgpu/partitioner/partitioner.py | 19 +++++- backends/webgpu/test/BUCK | 5 ++ .../webgpu/test/test_webgpu_partitioner.py | 64 +++++++++++++++++++ 5 files changed, 91 insertions(+), 1 deletion(-) diff --git a/backends/vulkan/partitioner/vulkan_partitioner.py b/backends/vulkan/partitioner/vulkan_partitioner.py index 3fe5070aded..ab8e349a461 100644 --- a/backends/vulkan/partitioner/vulkan_partitioner.py +++ b/backends/vulkan/partitioner/vulkan_partitioner.py @@ -329,6 +329,9 @@ def _check_node_support(self, node: torch.fx.Node) -> bool: # noqa: C901 return False features = self.op_features_overrides.get(target) + if features is None and hasattr(target, "name"): + # Custom ops may be overridden by name, as they are registered. + features = self.op_features_overrides.get(target.name()) if features is None: if target in vulkan_supported_ops: features = vulkan_supported_ops[target] diff --git a/backends/webgpu/partitioner/BUCK b/backends/webgpu/partitioner/BUCK index 2332290dce0..434ae70fabb 100644 --- a/backends/webgpu/partitioner/BUCK +++ b/backends/webgpu/partitioner/BUCK @@ -21,6 +21,7 @@ fbcode_target( "//caffe2:torch", "//executorch/backends/vulkan:op_registry", "//executorch/backends/vulkan/partitioner:vulkan_partitioner", + "//executorch/backends/vulkan/patterns:vulkan_patterns", "//executorch/exir/backend:partitioner", ], typing = True, diff --git a/backends/webgpu/partitioner/partitioner.py b/backends/webgpu/partitioner/partitioner.py index 3f77f59cd70..01c28fd2b3c 100644 --- a/backends/webgpu/partitioner/partitioner.py +++ b/backends/webgpu/partitioner/partitioner.py @@ -20,6 +20,7 @@ VulkanPartitioner, VulkanSupportedOperators, ) +from executorch.backends.vulkan.patterns.sdpa import llm_sdpa_has_attn_mask from executorch.exir.backend.partitioner import Partitioner, PartitionResult from executorch.exir.dialects._ops import ops as exir_ops from torch.export import ExportedProgram @@ -89,6 +90,14 @@ def _convolution_check( return vulkan_check(node) +def _llm_sdpa_check( + node: torch.fx.Node, vulkan_check: Callable[[torch.fx.Node], bool] +) -> bool: + # The WebGPU SDPA has no attn_mask. Masked attention, and the cache updates + # it reads, stay on CPU. + return not llm_sdpa_has_attn_mask(node) and vulkan_check(node) + + def _fp32_unary_features() -> OpFeatures: return OpFeatures( inputs_storage=vk_utils.ANY_STORAGE, @@ -120,6 +129,14 @@ def _fp32_unary_features() -> OpFeatures: lambda node, vulkan_check: vulkan_check(node), dtypes={torch.float32}, ), + **{ + target: _webgpu_features(target, _llm_sdpa_check) + for target in ( + "llama::sdpa_with_kv_cache", + "llama::custom_sdpa", + "llama::update_cache", + ) + }, exir_ops.edge.aten.elu.default: _fp32_unary_features(), exir_ops.edge.aten.erf.default: _fp32_unary_features(), exir_ops.edge.aten.silu.default: _fp32_unary_features(), @@ -127,7 +144,7 @@ def _fp32_unary_features() -> OpFeatures: # Vulkan fusion patterns whose fused ops the WebGPU runtime does not implement. -_WEBGPU_SKIP_FUSION_PATTERNS = {"conv2d_with_epilogue"} +_WEBGPU_SKIP_FUSION_PATTERNS = {"conv2d_with_epilogue", "masked_sdpa"} _MUL_TARGETS = (torch.ops.aten.mul.Tensor, exir_ops.edge.aten.mul.Tensor) diff --git a/backends/webgpu/test/BUCK b/backends/webgpu/test/BUCK index c2f72f32644..2bca1ce5cd7 100644 --- a/backends/webgpu/test/BUCK +++ b/backends/webgpu/test/BUCK @@ -43,6 +43,10 @@ fbcode_target( "ops/test_mul.py", "test_webgpu_partitioner.py", ], + preload_deps = [ + "//executorch/extension/llm/custom_ops:custom_ops_aot_lib", + "//executorch/extension/llm/custom_ops:custom_ops_aot_py", + ], deps = [ "//caffe2:torch", "//executorch/backends/vulkan/partitioner:vulkan_partitioner", @@ -54,6 +58,7 @@ fbcode_target( "//executorch/exir/backend:partitioner", "//executorch/exir/backend:utils", "//executorch/exir:lowered_backend_module", + "//executorch/extension/llm/custom_ops:custom_ops_aot_py", ], ) diff --git a/backends/webgpu/test/test_webgpu_partitioner.py b/backends/webgpu/test/test_webgpu_partitioner.py index f41ba37b878..6335ea8e8b5 100644 --- a/backends/webgpu/test/test_webgpu_partitioner.py +++ b/backends/webgpu/test/test_webgpu_partitioner.py @@ -71,6 +71,50 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: return x + torch.arange(0, x.shape[0], 1, dtype=torch.float32) +class LLMSDPAModule(torch.nn.Module): + S, C, H, D = 4, 16, 2, 8 + + def __init__(self, masked: bool) -> None: + super().__init__() + self.masked = masked + self.register_buffer("k_cache", torch.zeros(1, self.C, self.H, self.D)) + self.register_buffer("v_cache", torch.zeros(1, self.C, self.H, self.D)) + + def forward( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + mask: torch.Tensor, + input_pos: torch.Tensor, + ) -> torch.Tensor: + pos = input_pos.item() + torch._check(pos >= 0) + torch._check(pos + self.S <= self.C) + torch.ops.llama.update_cache(k, self.k_cache, pos) + torch.ops.llama.update_cache(v, self.v_cache, pos) + out = torch.ops.llama.custom_sdpa( + q, + self.k_cache, + self.v_cache, + pos, + mask if self.masked else None, + 0.0, + not self.masked, + ) + return out * 2.0 + + @classmethod + def example_inputs(cls) -> Tuple[torch.Tensor, ...]: + return ( + torch.randn(1, cls.S, cls.H, cls.D), + torch.randn(1, cls.S, cls.H, cls.D), + torch.randn(1, cls.S, cls.H, cls.D), + torch.randn(cls.S, cls.C), + torch.tensor([0]), + ) + + class TestWebGPUPartitioner(unittest.TestCase): def _export_add(self) -> ExportedProgram: return torch.export.export( @@ -313,6 +357,26 @@ def _lower_split( def _targets(self, nodes: List[torch.fx.Node]) -> List[object]: return [node.target for node in nodes] + def test_masked_llm_sdpa_stays_on_cpu(self) -> None: + # Vulkan fuses a masked custom_sdpa into sdpa_with_kv_cache; the WebGPU + # kernel has no attn_mask, so the attention and its cache updates must + # stay on CPU rather than fail at delegate init. + from executorch.extension.llm.custom_ops import custom_ops # noqa: F401 + + custom_sdpa = exir_ops.edge.llama.custom_sdpa.default + for masked in (False, True): + for partitioner in (VulkanPartitioner(), WebGPUPartitioner()): + with self.subTest(masked=masked, partitioner=type(partitioner)): + non_lowered, _ = self._lower_split( + partitioner, + LLMSDPAModule(masked), + LLMSDPAModule.example_inputs(), + ) + on_cpu = custom_sdpa in self._targets(non_lowered) + self.assertEqual( + on_cpu, masked and isinstance(partitioner, WebGPUPartitioner) + ) + def test_layer_norm_over_last_dim_only(self) -> None: layer_norm = exir_ops.edge.aten.native_layer_norm.default cases = { From 2a93a40d36fbb0b90d32159762e3080978d29a67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20S=C5=82uszniak?= Date: Thu, 3 Dec 2026 10:28:14 +0100 Subject: [PATCH 17/17] Vulkan SDPA: match the reworded mask errors in sdpa_test, rely on the Meta kernel's mask checks The llama ops' Meta kernel already requires a 2D [S, C] fp32 mask with is_causal unset, so the partitioner only rejects a non-causal unmasked SDPA. Drop the shape/dtype checks and their unreachable tests. --- backends/vulkan/patterns/sdpa.py | 37 +++++---------------- backends/vulkan/test/op_tests/sdpa_test.cpp | 5 +-- backends/vulkan/test/test_vulkan_passes.py | 31 ++++------------- 3 files changed, 17 insertions(+), 56 deletions(-) diff --git a/backends/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 4cd9895374c..767e4559999 100644 --- a/backends/vulkan/patterns/sdpa.py +++ b/backends/vulkan/patterns/sdpa.py @@ -50,11 +50,7 @@ def find_cache_update( torch.ops.higher_order.auto_functionalized_v2, ) -# The key cache argument of each LLM SDPA op, whose dim 1 is the cache length. -_LLM_SDPA_KEY_CACHE_ARG = { - "llama::custom_sdpa": "key", - "llama::sdpa_with_kv_cache": "key_cache", -} +_LLM_SDPA_OPS = ("llama::custom_sdpa", "llama::sdpa_with_kv_cache") def get_llama_op_args(node: torch.fx.Node) -> Tuple[Optional[str], Dict[str, Any]]: @@ -126,35 +122,18 @@ def llm_sdpa_has_attn_mask(node: torch.fx.Node) -> bool: def check_llm_sdpa_node(node: torch.fx.Node) -> bool: """ - The Vulkan LLM SDPA is either causal without an attn_mask, or takes a 2D - [S, C] fp32 or fp16 additive attn_mask with is_causal unset. Other - configurations stay on CPU instead of failing at load time. An - update_cache stays on CPU with the custom_sdpa that reads its cache, so - that both see the same cache. + The Vulkan LLM SDPA is either causal without an attn_mask, or takes an + additive attn_mask. The ops' Meta kernels already require the mask to be + 2D [S, C] fp32 with is_causal unset, so only the non-causal unmasked case + stays on CPU. An update_cache stays on CPU with the custom_sdpa that reads + its cache, so that both see the same cache. """ name, args = get_llama_op_args(node) if name == "llama::update_cache": return all(check_llm_sdpa_node(r) for r in get_update_cache_readers(node)) - if name not in _LLM_SDPA_KEY_CACHE_ARG: + if name not in _LLM_SDPA_OPS: return True - - attn_mask = args.get("attn_mask") - if attn_mask is None: - return bool(args.get("is_causal")) - mask_val = _node_val(attn_mask) - q_val = _node_val(args.get("query")) - if args.get("is_causal") or mask_val is None or q_val is None: - return False - if mask_val.dim() != 2 or not {mask_val.dtype, q_val.dtype} <= utils.FP_T: - return False - # The mask must be [S, C]. Sizes that are symbolic, or a cache that - # auto_functionalized_v2 passes as a base, are checked at runtime. - cache_val = _node_val(args.get(_LLM_SDPA_KEY_CACHE_ARG[name])) - expected = [q_val.shape[1], None if cache_val is None else cache_val.shape[1]] - return all( - not isinstance(size, int) or not isinstance(exp, int) or size == exp - for size, exp in zip(mask_val.shape, expected) - ) + return args.get("attn_mask") is not None or bool(args.get("is_causal")) class CausalSDPAMatch(PatternMatch): diff --git a/backends/vulkan/test/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 5a4cfe186dd..dbdcc4269ff 100644 --- a/backends/vulkan/test/op_tests/sdpa_test.cpp +++ b/backends/vulkan/test/op_tests/sdpa_test.cpp @@ -1022,7 +1022,8 @@ TEST(VulkanGeneralSDPATest, test_general_sdpa_rejects_mask_of_another_dtype) { add({1, 1, 4, 4}, vkapi::kInt), kDummyValueRef, add(sizes, vkapi::kFloat)}, - "attn_mask of the query's dtype"); + storage == utils::kBuffer ? "attn_mask of the query's dtype" + : "Float or Half attn_mask texture"); } } @@ -1048,7 +1049,7 @@ TEST( add({1, 1, 4, 4}, mask_storage), kDummyValueRef, add(sizes, out_storage)}, - "attn_mask and output in the query's storage"); + "in the query's storage"); } } diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index c910719917e..4a96577725d 100644 --- a/backends/vulkan/test/test_vulkan_passes.py +++ b/backends/vulkan/test/test_vulkan_passes.py @@ -2326,34 +2326,19 @@ def test_mask_is_supported(self): def test_mask_with_trimmed_default_args_is_supported(self): self.assertTrue(self._build(mask_shape=(self.S, self.C), trim_defaults=True)) - def test_mask_with_is_causal_is_rejected(self): - self.assertFalse(self._build(mask_shape=(self.S, self.C), is_causal=True)) - def test_fp32_mask_with_fp16_query_needs_texture(self): # The CPU op requires an fp32 mask, also for an fp16 query. self.assertTrue(self._build(mask_shape=(self.S, self.C), q_dtype=torch.float16)) - def test_non_float_mask_is_rejected(self): - self.assertFalse( - self._build(mask_shape=(self.S, self.C), mask_dtype=torch.bool) - ) - - def test_mask_shape_mismatch_is_rejected(self): - self.assertFalse(self._build(mask_shape=(1, self.S, self.C))) - self.assertFalse(self._build(mask_shape=(self.S, self.C - 1))) - def test_auto_functionalized_sdpa_with_kv_cache(self): from executorch.backends.vulkan.patterns.sdpa import check_llm_sdpa_node from torch._subclasses.fake_tensor import FakeTensorMode # The partitioner passes the wrapper node, whose op args are kwargs. v2 - # passes the caches as bases, so their length is checked at runtime. - for wrapper, mask_len in product( - ( - torch.ops.higher_order.auto_functionalized, - torch.ops.higher_order.auto_functionalized_v2, - ), - (self.C, self.C - 1), + # passes the caches as bases instead. + for wrapper in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, ): fake_mode = FakeTensorMode() graph = torch.fx.Graph() @@ -2367,7 +2352,7 @@ def test_auto_functionalized_sdpa_with_kv_cache(self): graph, fake_mode, "v_cache", cache_shape, torch.float32 ) mask = self._placeholder( - graph, fake_mode, "mask", (self.S, mask_len), torch.float32 + graph, fake_mode, "mask", (self.S, self.C), torch.float32 ) kwargs = { "query": q, @@ -2391,11 +2376,7 @@ def test_auto_functionalized_sdpa_with_kv_cache(self): node = graph.call_function( wrapper, (torch.ops.llama.sdpa_with_kv_cache.default,), kwargs ) - self.assertEqual( - check_llm_sdpa_node(node), - mask_len == self.C - or wrapper == torch.ops.higher_order.auto_functionalized_v2, - ) + self.assertTrue(check_llm_sdpa_node(node)) class _LLMSDPAModule(torch.nn.Module):