Repository navigation
Vulkan: support attn_mask and scale in llama.custom_sdpa / sdpa_with_kv_cache #23539
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
e65fd96
e865d46
bd9b349
71ef295
3ceb785
6b399fe
05bf67f
6928724
cbd09cf
c793edc
f2de1da
7b8218a
3a979f3
7ee190b
823ad76
0cd1f70
7a0a012
b1605c8
3c5e027
3fcd951
2a93a40
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A5 (Low): WebGPU now admits masked LLM SDPA that its runtime rejects
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ( Proposed fix: reduce the SDPA branch to |
||
| """ | ||
| 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, | ||
|
|
||
There was a problem hiding this comment.
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
check_llm_sdpa_noderejecting (fp16 q, fp32 mask).input_pos.item(),update_cachex2,custom_sdpawith an fp32 mask and fp16 q). Rejecting the SDPA and cache ops leaves a Vulkan partition made only ofge/_assert_scalarnodes.to_edge_transform_and_lowerthen raisesAssertionError: last_output_node is Noneinstead 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.There was a problem hiding this comment.
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?