diff --git a/backends/vulkan/op_registry.py b/backends/vulkan/op_registry.py index 3f9c550b779..b80ea32d3e9 100644 --- a/backends/vulkan/op_registry.py +++ b/backends/vulkan/op_registry.py @@ -13,6 +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, + llm_sdpa_mask_needs_texture, +) from executorch.exir.dialects._ops import ops as exir_ops from executorch.exir.dialects.edge._ops import EdgeOpOverload @@ -1189,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( @@ -1196,6 +1210,8 @@ 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, + pick_io_storage_fn=pick_llm_sdpa_storage, ) @@ -1210,6 +1226,8 @@ 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, + pick_io_storage_fn=pick_llm_sdpa_storage, ) 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/vulkan/patterns/sdpa.py b/backends/vulkan/patterns/sdpa.py index 0ca3a225bf1..767e4559999 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,6 +45,97 @@ def find_cache_update( return None +_AUTO_FUNCTIONALIZED = ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, +) + +_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]]: + """ + 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. + """ + if node.op != "call_function": + return None, {} + if node.target in _AUTO_FUNCTIONALIZED: + op = node.args[0] + 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 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) + _, 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 _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 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_OPS: + return True + return args.get("attn_mask") is not None or bool(args.get("is_causal")) + + class CausalSDPAMatch(PatternMatch): def __init__(self, custom_sdpa_node: torch.fx.Node) -> None: self.anchor_node = custom_sdpa_node @@ -60,13 +151,12 @@ 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 + _, 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: @@ -108,11 +198,15 @@ 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 + # leave unsupported mask configurations unmatched to keep them on CPU. + if not check_llm_sdpa_node(node): return None matched_pattern = CausalSDPAMatch(node) @@ -122,12 +216,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/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.glsl index fe9e262a79a..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 @@ -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=False)} ${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; @@ -115,16 +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. - bool tile_in_mask_region = c > (input_pos + s + (TILE_M - 1)); + // 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, @@ -174,6 +184,10 @@ void main() { // Only the first thread will write out the result if (worker_id == 0) { out_tile = partial_sums[0]; +#ifdef HAS_MASK + 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); @@ -184,6 +198,7 @@ void main() { c, s); } +#endif store_attn_weight_tile_with_checks( out_tile, diff --git a/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml b/backends/vulkan/runtime/graph/ops/glsl/sdpa_compute_attn_weights_coop.yaml index 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 f0846df7ab5..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 @@ -35,6 +35,8 @@ $else: $if HAS_BIAS: #define HAS_BIAS +$if HAS_MASK: + #define HAS_MASK #define TILE_M4 ${TILE_M4} #define TILE_K4 ${TILE_K4} @@ -55,6 +57,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=False)} ${layout_declare_ubo(B, "ivec4", "q_sizes")} ${layout_declare_ubo(B, "ivec4", "k_sizes")} @@ -62,6 +66,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; @@ -81,6 +87,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) @@ -163,7 +172,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. @@ -208,7 +217,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 78a7df1d4be..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 @@ -151,6 +151,39 @@ 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, and a c_idx_start that is + * 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_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; + [[unroll]] for (int c4 = 0; c4 < TILE_N4; ++c4) { + const int c4_idx = div_4(c_idx_start) + c4; + if (s_idx >= mask_S || c4_idx >= mask_C4) { + continue; + } +#ifdef INPUT_BUFFER + const vec4 mask_texel = vec4(t_mask[s_idx * mask_C4 + c4_idx]); +#else + const vec4 mask_texel = + vec4(texelFetch(t_mask, ivec3(c4_idx, s_idx, 0), 0)); +#endif + tile.data[s][c4] += LINEAR_FP_OUTPUT_TILE_VEC4_T(mask_texel); + } + } +} +#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/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); } diff --git a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp index ea0b2cea7b5..06a2ea37e50 100644 --- a/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp +++ b/backends/vulkan/runtime/graph/ops/impl/SDPA.cpp @@ -242,9 +242,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)); @@ -491,11 +496,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), attn_mask = 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; the LLM path computes it per head_dim and FUSED may -// inherit from the caller-supplied scale. +// 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, @@ -513,7 +520,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); } @@ -650,6 +658,87 @@ 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, + 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. 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, + const std::vector& resize_args) { + (void)args; + const ValueRef q = resize_args.at(0); + const ValueRef k = resize_args.at(1); + 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)); +} + +ValueRef add_attn_mask_input_pos_node( + ComputeGraph& graph, + const ValueRef q, + 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, attn_mask, out_symint})); + return out_symint; +} + // // High level operator impl // @@ -709,10 +798,35 @@ void sdpa_impl_with_shader_override( VK_CHECK_COND( graph.val_is_none(dropout_p) || graph.extract_scalar(dropout_p) == 0); - // 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. The + // partitioner 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, "attn_mask must be 2D"); + // A constant mask arrives as a TensorRef, since the fused op handles its + // 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( + graph, + attn_mask, + graph.storage_type_of(q_projected), + utils::kWidthPacked) + : attn_mask; + check_sdpa_attn_mask(graph, mask, q_projected); + check_attn_mask_sizes(graph, mask, q_projected, k_cache); + } else { + VK_CHECK_COND( + 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); int64_t max_seq_len = graph.size_at(-3, q_projected); @@ -779,12 +893,20 @@ void sdpa_impl_with_shader_override( ? 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. 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, mask) + : input_pos_symint; + add_sdpa_compute_attn_weights_node( graph, q_projected, k_cache, - input_pos_symint, - /*attn_mask=*/kDummyValueRef, + attn_input_pos, + mask, scale_val, attn_weights, SDPAMode::LLM); @@ -794,7 +916,7 @@ void sdpa_impl_with_shader_override( attn_weights, q_projected, k_cache, - input_pos_symint, + attn_input_pos, attn_weights_softmax, SDPAMode::LLM); @@ -804,7 +926,7 @@ void sdpa_impl_with_shader_override( v_cache, q_projected, /*k=*/kDummyValueRef, - input_pos_symint, + attn_input_pos, out, SDPAMode::LLM, shader_override); @@ -877,13 +999,16 @@ 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++]; + 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++]; @@ -951,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/targets.bzl b/backends/vulkan/targets.bzl index 5a4928e83d6..fd9e127c4a5 100644 --- a/backends/vulkan/targets.bzl +++ b/backends/vulkan/targets.bzl @@ -408,6 +408,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/op_tests/sdpa_test.cpp b/backends/vulkan/test/op_tests/sdpa_test.cpp index 0a1cd408ca1..dbdcc4269ff 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 @@ -20,10 +21,12 @@ #include "test_utils.h" +#include #include #include #include #include +#include #include // @@ -1019,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"); } } @@ -1045,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"); } } @@ -1116,6 +1120,488 @@ TEST(VulkanSDPATest, test_sdpa_op_gqa_group4) { 0, {5, 1, 1, 1, 1, 3, 1}, head_dim, num_heads, num_kv_heads, 1); } +// +// 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. +// + +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 std::optional scale, + vkcompute::utils::StorageType storage_type, + at::ScalarType dtype = at::kFloat, + const bool use_custom_sdpa = 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. + 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(mask_dtype) + .contiguous() + : at::Tensor(); + + // 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); + + 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 = {kDummyValueRef, kDummyValueRef}; + if (constant_mask) { + r_mask.value = graph.add_tensorref( + constant_mask_data.sizes().vec(), + 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(mask_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); + 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) { + // 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") + (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); + + graph.prepare(); + graph.prepack(); + + torch::manual_seed(0); + + 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 = + (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 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); + 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 = 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); + 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)); + 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_val + + 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()); + if (has_input_mask) { + 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)); + if (has_input_mask) { + graph.maybe_cast_and_copy_into_staging( + r_mask.staging, + mask.const_data_ptr(), + mask.numel(), + from_at_scalartype(mask_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 << "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); + } +} + +constexpr std::array kLLMSDPAStorageTypes = { + vkcompute::utils::kTexture3D, + vkcompute::utils::kBuffer}; + +TEST(VulkanSDPATest, test_sdpa_op_sliding_window_mask) { + 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 : 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 : 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); + } +} + +// 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); + } + } + } +} + +// 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) { + test_vulkan_llm_sdpa( + consecutive_steps({7, 1, 1, 3, 1}), + 64, + 8, + 2, + 32, + LLMSDPAMask::CAUSAL, + 0, + 0.3, + storage_type); + } +} + TEST(VulkanSDPATest, test_sdpa_op_unaligned_head_dim) { const int head_dim = 6; const int num_heads = 4; diff --git a/backends/vulkan/test/test_vulkan_passes.py b/backends/vulkan/test/test_vulkan_passes.py index 11e8872a8d2..4a96577725d 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, @@ -2234,3 +2237,226 @@ def forward(self, x): replace_pass._exported_program = ep with self.assertRaises(RuntimeError): replace_pass.call(ep.graph_module) + + +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 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, + 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, + 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() + 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 = self._placeholder(graph, fake_mode, "mask", mask_shape, mask_dtype) + + update_cache = graph.call_function( + torch.ops.llama.update_cache.default, (k, k_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(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) + 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): + 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_trimmed_default_args_is_supported(self): + self.assertTrue(self._build(mask_shape=(self.S, self.C), trim_defaults=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_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 instead. + for wrapper in ( + torch.ops.higher_order.auto_functionalized, + torch.ops.higher_order.auto_functionalized_v2, + ): + 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, 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, + ) + node = graph.call_function( + wrapper, (torch.ops.llama.sdpa_with_kv_cache.default,), kwargs + ) + self.assertTrue(check_llm_sdpa_node(node)) + + +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 cpu_ops, vk_graph + + 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( + [ + op + for op in cpu_ops + if "llama" in str(op) or "auto_functionalized" in str(op) + ] + ) + 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) 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 = {