Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e65fd96
Vulkan: support attn_mask and scale in llama.custom_sdpa / sdpa_with_…
msluszniak Oct 7, 2026
e865d46
Vulkan SDPA: fix QK node comments and honor scale in the attn weight …
msluszniak Oct 8, 2026
bd9b349
Vulkan SDPA: prepack a constant attn_mask and validate it at load and…
msluszniak Oct 8, 2026
71ef295
Vulkan: keep unsupported custom_sdpa mask configurations on CPU
msluszniak Oct 8, 2026
3ceb785
Vulkan SDPA: fetch each texture attn_mask texel once
msluszniak Oct 8, 2026
6b399fe
Vulkan SDPA: test masked attention over the full cache and more configs
msluszniak Oct 8, 2026
05bf67f
Vulkan: move check_llm_sdpa_node into patterns/sdpa.py
msluszniak Oct 12, 2026
6928724
Vulkan SDPA: compare a constant attn_mask's dtype after prepacking
msluszniak Oct 20, 2026
cbd09cf
Vulkan: check auto_functionalized sdpa_with_kv_cache mask configurations
msluszniak Oct 20, 2026
c793edc
Vulkan: read custom_sdpa's default args in the causal_sdpa pattern
msluszniak Oct 20, 2026
f2de1da
Merge remote-tracking branch 'up/main' into ms/vulkan-sdpa-attn-mask
msluszniak Oct 20, 2026
7b8218a
Merge remote-tracking branch 'upstream/main' into ms/vulkan-sdpa-attn…
msluszniak Oct 26, 2026
3a979f3
Merge upstream main into ms/vulkan-sdpa-attn-mask
msluszniak Oct 30, 2026
7ee190b
Merge upstream main into ms/vulkan-sdpa-attn-mask
msluszniak Nov 17, 2026
823ad76
Vulkan SDPA: read a buffer attn_mask in padded texel rows
msluszniak Nov 17, 2026
0cd1f70
Vulkan SDPA: write only the S new rows in the kv-cache update
msluszniak Nov 17, 2026
7a0a012
Vulkan SDPA: prepack the custom_sdpa op test caches
msluszniak Nov 17, 2026
b1605c8
Vulkan SDPA: accept a Float attn_mask with a Half query in textures
msluszniak Nov 17, 2026
3c5e027
Vulkan: simplify the LLM SDPA mask predicate
msluszniak Nov 17, 2026
3fcd951
WebGPU: keep masked LLM SDPA on CPU
msluszniak Nov 17, 2026
2a93a40
Vulkan SDPA: match the reworded mask errors in sdpa_test, rely on the…
msluszniak Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions backends/vulkan/op_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -1189,13 +1193,25 @@ 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(
inputs_storage=utils.CONTIGUOUS_ANY,
inputs_dtypes=utils.FP_T,
supports_resize=True,
supports_prepacking=True,
are_node_inputs_supported_fn=check_llm_sdpa_node,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A8 (Low): Fallback can still fail at partition time for small graphs

  • Where: partitioner behavior with check_llm_sdpa_node rejecting (fp16 q, fp32 mask).
  • Issue: observed in a minimal graph (input_pos.item(), update_cache x2, custom_sdpa with an fp32 mask and fp16 q). Rejecting the SDPA and cache ops leaves a Vulkan partition made only of ge/_assert_scalar nodes. to_edge_transform_and_lower then raises AssertionError: last_output_node is None instead of falling back cleanly. The root cause is an output-less symbolic-assert partition, a partitioner issue outside this PR. Real LLM graphs likely have other delegated ops around those asserts. Listed because the PR's stated behavior ("stay on CPU") is only covered by stubbed-graph unit tests.
  • Suggested fix: none required in this PR. Add one real-op export test (see coverage), or exclude output-less partitions in the Vulkan partitioner separately.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a real-op lowering test and a WebGPU partitioner test. The output-less partition case still fails for a tiny WebGPU graph; OK to leave that for a separate PR?

pick_io_storage_fn=pick_llm_sdpa_storage,
)


Expand All @@ -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,
)


Expand Down
3 changes: 3 additions & 0 deletions backends/vulkan/partitioner/vulkan_partitioner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
135 changes: 123 additions & 12 deletions backends/vulkan/patterns/sdpa.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A5 (Low): WebGPU now admits masked LLM SDPA that its runtime rejects

  • Where: backends/webgpu/partitioner/partitioner.py (_WEBGPU_OP_FEATURES); backends/webgpu/runtime/ops/sdpa/Sdpa.cpp:503 ("WebGPU sdpa: attn_mask is not supported").
  • Issue: WebGPUPartitioner wraps VulkanPartitioner. With this PR, check_llm_sdpa_node and the causal_sdpa detector accept masked custom_sdpa, so a WebGPU export fuses it to sdpa_with_kv_cache and fails at delegate init. On main the same export already crashed at export time (the trimmed-default-args IndexError) or at init. This is not a regression, but it contradicts the PR's "keep on CPU instead of failing at load" intent. Because the detector calls check_llm_sdpa_node directly, a WebGPU op_features_overrides entry alone cannot keep the fused node off.
  • Suggested fix: add causal_sdpa-mask gating for WebGPU, e.g. a compile option read by the detector, or reject masked llama::custom_sdpa / sdpa_with_kv_cache in _WEBGPU_OP_FEATURES and skip fusion for masked nodes when the partitioner disallows them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3c5e027 and 3fcd951: masked fusion is a separate pattern that WebGPU skips, and WebGPU keeps masked LLM SDPA and its update_cache on CPU.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI review] A2 (Low): Most of this check can't fire on an exported graph.

Since #25032, the llama ops' Meta kernel (_validate_params in custom_ops.py) already asserts at export time that the mask is 2D, fp32, not combined with is_causal, and has shape (q.size(1), key_cache.size(1)). In a traced graph, the dim, dtype, is_causal and [S, C] checks here therefore always pass. _LLM_SDPA_KEY_CACHE_ARG and the auto_functionalized_v2 handling exist only to feed the shape check. The rejection tests pass only because they build hand-made fx.Graphs that torch.export can't produce. For example, exporting with a bool mask fails earlier with Expected attn_mask to be float32 but got torch.bool.

Proposed fix: reduce the SDPA branch to return args.get("attn_mask") is not None or bool(args.get("is_causal")). Keep the update_cache reader propagation. Drop _LLM_SDPA_KEY_CACHE_ARG, the shape/dtype logic, and the stub tests for unreachable inputs. The runtime VK_CHECK_CONDs and the resize-time [S, C] check remain as the backstop.

"""
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
Expand All @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -184,6 +198,7 @@ void main() {
c,
s);
}
#endif

store_attn_weight_tile_with_checks(
out_tile,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -55,13 +57,17 @@ ${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")}
$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;

Expand All @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading