-
Notifications
You must be signed in to change notification settings - Fork 1k
XNNPACK: Lift constant mul scalars for partitioning #20515
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
Open
mansnils
wants to merge
2
commits into
pytorch:main
Choose a base branch
from
mansnils:ops
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
150 changes: 150 additions & 0 deletions
150
backends/xnnpack/_passes/lift_constant_scalar_operands_pass.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # Copyright 2026 Arm Limited and/or its affiliates. | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from numbers import Number | ||
| from typing import Dict, Optional, Union | ||
|
|
||
| import torch | ||
| from executorch.exir.dialects._ops import ops as exir_ops | ||
| from executorch.exir.dialects.edge._ops import EdgeOpOverload | ||
| from executorch.exir.pass_base import ExportPass, PassResult | ||
| from torch._ops import OpOverload | ||
|
|
||
|
|
||
| ScalarOp = Union[EdgeOpOverload, OpOverload] | ||
|
|
||
|
|
||
| class LiftConstantScalarOperandsPass(ExportPass): | ||
| """ | ||
| Lift scalar operands into tensor constants for selected binary ops. | ||
|
|
||
| XNNPACK already supports the tensor overloads for these binary operations. | ||
| This pass converts explicitly listed scalar overloads to their tensor | ||
| overloads by replacing constant scalar operands with small tensor constants. | ||
| The constants are registered as buffers so they do not become portable | ||
| ``full`` kernels. Keep the op map narrow until each new scalar overload is | ||
| covered by tests. | ||
| """ | ||
|
|
||
| default_scalar_to_tensor_ops: Dict[ScalarOp, ScalarOp] = { | ||
| exir_ops.edge.aten.mul.Scalar: exir_ops.edge.aten.mul.Tensor, | ||
| } | ||
| sdpa_passthrough_ops = { | ||
| exir_ops.edge.aten.expand_copy.default, | ||
| exir_ops.edge.aten.view_copy.default, | ||
| } | ||
|
|
||
| def __init__( | ||
| self, | ||
| scalar_to_tensor_ops: Optional[Dict[ScalarOp, ScalarOp]] = None, | ||
| ) -> None: | ||
| super().__init__() | ||
| self.scalar_to_tensor_ops = ( | ||
| scalar_to_tensor_ops | ||
| if scalar_to_tensor_ops is not None | ||
| else self.default_scalar_to_tensor_ops | ||
| ) | ||
|
|
||
| def _create_constant_node( | ||
| self, | ||
| graph_module: torch.fx.GraphModule, | ||
| node: torch.fx.Node, | ||
| value: Number, | ||
| ) -> torch.fx.Node: | ||
| input_node = node.args[0] | ||
| if not isinstance(input_node, torch.fx.Node): | ||
| raise RuntimeError("Expected scalar op input to be an FX node.") | ||
|
|
||
| input_value = input_node.meta["val"] | ||
| tensor = torch.tensor(value, dtype=input_value.dtype, device=input_value.device) | ||
| name = self._get_new_attr_name(graph_module) | ||
| # Keep constants as module attributes so the portable path can emit them | ||
| # without introducing aten.full, while XNNPACK can still read them as params. | ||
| graph_module.register_buffer(name, tensor) | ||
|
|
||
| fake_mode = node.meta["val"].fake_mode | ||
| with graph_module.graph.inserting_before(node): | ||
| constant_node = graph_module.graph.get_attr(name) | ||
| constant_node.meta["val"] = fake_mode.from_tensor( | ||
| tensor, static_shapes=True | ||
| ) | ||
| return constant_node | ||
|
|
||
| def _get_new_attr_name(self, graph_module: torch.fx.GraphModule) -> str: | ||
| prefix = "_tensor_constant_" | ||
| index = 0 | ||
| while hasattr(graph_module, f"{prefix}{index}"): | ||
| index += 1 | ||
| return f"{prefix}{index}" | ||
|
|
||
| def _feeds_sdpa_qk_bmm(self, node: torch.fx.Node) -> bool: | ||
| """ | ||
| Return true for the scale muls consumed by XNNPACK's SDPA pattern. | ||
|
|
||
| ConvertToSDPAPass recovers the user-specified attention scale from the | ||
| pre-QK^T ``aten.mul.Scalar`` nodes. Keep those scalar muls intact so | ||
| SDPA conversion can still find the scale before replacing the pattern. | ||
| """ | ||
| users_to_visit = list(node.users) | ||
| visited = set() | ||
| while users_to_visit: | ||
| user = users_to_visit.pop() | ||
| if user in visited: | ||
| continue | ||
| visited.add(user) | ||
|
|
||
| if ( | ||
| user.op == "call_function" | ||
| and user.target == exir_ops.edge.aten.bmm.default | ||
| ): | ||
| return True | ||
|
|
||
| if user.op == "call_function" and user.target in self.sdpa_passthrough_ops: | ||
| users_to_visit.extend(user.users) | ||
|
|
||
| return False | ||
|
|
||
| def call(self, graph_module: torch.fx.GraphModule) -> PassResult: | ||
| modified = False | ||
|
|
||
| for node in list(graph_module.graph.nodes): | ||
| if ( | ||
| node.op != "call_function" | ||
| or node.target not in self.scalar_to_tensor_ops | ||
| or len(node.args) != 2 | ||
| or not isinstance(node.args[0], torch.fx.Node) | ||
| or not isinstance(node.args[1], Number) | ||
| ): | ||
| continue | ||
|
|
||
| if ( | ||
| node.target == exir_ops.edge.aten.mul.Scalar | ||
| and self._feeds_sdpa_qk_bmm(node) | ||
| ): | ||
| continue | ||
|
|
||
| input_value = node.args[0].meta.get("val") | ||
| output_value = node.meta.get("val") | ||
| if ( | ||
| input_value is None | ||
| or output_value is None | ||
| or input_value.dtype != output_value.dtype | ||
| ): | ||
| continue | ||
|
|
||
| tensor_arg = self._create_constant_node(graph_module, node, node.args[1]) | ||
| node.args = (node.args[0], tensor_arg) | ||
| node.target = self.scalar_to_tensor_ops[node.target] | ||
| modified = True | ||
|
|
||
| graph_module.graph.eliminate_dead_code() | ||
| graph_module.graph.lint() | ||
| graph_module.recompile() | ||
|
|
||
| return PassResult(graph_module, modified) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
87 changes: 87 additions & 0 deletions
87
backends/xnnpack/test/passes/test_lift_constant_scalar_operands_pass.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # Copyright 2026 Arm Limited and/or its affiliates. | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| import unittest | ||
| from copy import deepcopy | ||
|
|
||
| import torch | ||
| from executorch.backends.xnnpack._passes.lift_constant_scalar_operands_pass import ( | ||
| LiftConstantScalarOperandsPass, | ||
| ) | ||
| from executorch.backends.xnnpack.partition.graphs import sdpa | ||
| from executorch.backends.xnnpack.utils.configs import get_xnnpack_edge_compile_config | ||
| from executorch.exir import to_edge | ||
| from executorch.exir.dialects._ops import ops as exir_ops | ||
| from executorch.exir.pass_manager import ExportedProgramPassManager | ||
|
|
||
|
|
||
| class TestLiftConstantScalarOperandsPass(unittest.TestCase): | ||
| def setUp(self): | ||
| torch._dynamo.reset() | ||
|
|
||
| class MulScalar(torch.nn.Module): | ||
| def forward(self, x): | ||
| return torch.ops.aten.mul.Scalar(x, 0.5) | ||
|
|
||
| class AddScalar(torch.nn.Module): | ||
| def forward(self, x): | ||
| return torch.ops.aten.add.Scalar(x, 0.5) | ||
|
|
||
| def _to_edge_program_manager(self, module): | ||
| return to_edge( | ||
| torch.export.export(module, (torch.randn(2, 3),), strict=True), | ||
| compile_config=get_xnnpack_edge_compile_config(skip_dim_order=True), | ||
| ) | ||
|
|
||
| def _to_edge_graph(self, module): | ||
| edge = self._to_edge_program_manager(module) | ||
| return ExportedProgramPassManager([LiftConstantScalarOperandsPass()])( | ||
| edge.exported_program() | ||
| ).exported_program | ||
|
|
||
| def test_lifts_mul_scalar_operand(self): | ||
| graph = self._to_edge_graph(self.MulScalar()).graph_module.graph | ||
|
|
||
| self.assertFalse( | ||
| any(node.target == exir_ops.edge.aten.mul.Scalar for node in graph.nodes) | ||
| ) | ||
| self.assertTrue( | ||
| any(node.target == exir_ops.edge.aten.mul.Tensor for node in graph.nodes) | ||
| ) | ||
| self.assertTrue(any(node.op == "get_attr" for node in graph.nodes)) | ||
|
|
||
| def test_lifted_mul_scalar_can_emit_without_delegation(self): | ||
| edge = self._to_edge_program_manager(self.MulScalar()).transform( | ||
| (LiftConstantScalarOperandsPass(),) | ||
| ) | ||
|
|
||
| self.assertIsNotNone(edge.to_executorch()) | ||
|
|
||
| def test_keeps_unmapped_scalar_op(self): | ||
| graph = self._to_edge_graph(self.AddScalar()).graph_module.graph | ||
|
|
||
| self.assertTrue( | ||
| any(node.target == exir_ops.edge.aten.add.Scalar for node in graph.nodes) | ||
| ) | ||
|
|
||
| def test_keeps_sdpa_scale_mul_scalar(self): | ||
| graph_module = deepcopy(sdpa.get_graphs()[0]) | ||
|
|
||
| LiftConstantScalarOperandsPass()(graph_module) | ||
|
|
||
| scale_mul_count = 0 | ||
| lifted_mul_count = 0 | ||
| for node in graph_module.graph.nodes: | ||
| if node.op != "call_function": | ||
| continue | ||
| if node.target == exir_ops.edge.aten.mul.Scalar: | ||
| scale_mul_count += 1 | ||
| if node.target == exir_ops.edge.aten.mul.Tensor: | ||
| lifted_mul_count += 1 | ||
|
|
||
| self.assertEqual(scale_mul_count, 2) | ||
| self.assertEqual(lifted_mul_count, 0) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.