Repository navigation
Cortex-M: fix quantized lowering for decomposed attention #22796
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
amacharla15
wants to merge
5
commits into
pytorch:main
Choose a base branch
from
amacharla15:issue-21943
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
5 commits
Select commit
Hold shift + click to select a range
60ae655
Cortex-M: fix quantized lowering for decomposed attention
amacharla15 e1171a6
Cortex-M: narrow decomposed attention lowering fixes
amacharla15 3bc33a4
Cortex-M: address decomposed attention review feedback
amacharla15 59d3be3
Cortex-M: add new passes to Buck targets
amacharla15 c09864c
Cortex-M: preserve quantized BMM dtype during retracing
amacharla15 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
There are no files selected for viewing
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
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
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,83 @@ | ||
| # 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 typing import Any | ||
|
|
||
| import torch | ||
|
|
||
| from executorch.exir.dialects._ops import ops as exir_ops | ||
| from executorch.exir.pass_base import ExportPass, NodeMetadata, ProxyValue | ||
| from torch.utils import _pytree as pytree | ||
|
|
||
|
|
||
| class CortexMQuantizedPass(ExportPass): | ||
| """Base pass for retracing folded Cortex-M quantized graphs. | ||
|
|
||
| Cortex-M's quantized linear kernel includes requantization and therefore | ||
| produces the dtype described by its output qparams, normally int8. | ||
|
|
||
| Once Q/DQ nodes have been folded, retracing ``aten.linear`` through the | ||
| regular PyTorch fake kernel would incorrectly recreate an int32 output. | ||
| Preserve the Cortex-M output dtype instead. | ||
| """ | ||
|
|
||
| @staticmethod | ||
| def _is_quantized_meta(meta: NodeMetadata) -> bool: | ||
| input_qparams = meta.data.get("input_qparams", {}) | ||
| output_qparams = meta.data.get("output_qparams", {}) | ||
| return bool(input_qparams) and bool(output_qparams) | ||
|
|
||
| def _call_quantized_op_without_fake_kernel( | ||
| self, | ||
| op, | ||
| args: tuple[ProxyValue, ...], | ||
| kwargs: dict[str, Any], | ||
| meta: NodeMetadata, | ||
| ) -> ProxyValue: | ||
| old_val = meta.data["val"] | ||
| output_qparams = meta.data.get("output_qparams", {}) | ||
| dtype = ( | ||
| next(iter(output_qparams.values())).dtype | ||
| if output_qparams | ||
| else old_val.dtype | ||
| ) | ||
|
|
||
| result_data = torch.empty_like(old_val, dtype=dtype) | ||
|
|
||
| args_proxy, kwargs_proxy = pytree.tree_map_only( | ||
| ProxyValue, | ||
| lambda value: value.proxy, | ||
| (args, kwargs), | ||
| ) | ||
|
|
||
| result_proxy = self.tracer.create_proxy( | ||
| "call_function", | ||
| op, | ||
| args_proxy, | ||
| kwargs_proxy, | ||
| ) | ||
| result_proxy.node.meta.update(meta.data) | ||
| self.tracer.set_metadata(result_proxy.node, result_data) | ||
|
|
||
| return ProxyValue(result_data, result_proxy) | ||
|
|
||
| def call_operator(self, op, args, kwargs, meta): | ||
| if ( | ||
| op | ||
| in { | ||
| exir_ops.edge.aten.linear.default, | ||
| exir_ops.edge.aten.bmm.default, | ||
| } | ||
| and isinstance(meta, NodeMetadata) | ||
| and self._is_quantized_meta(meta) | ||
| ): | ||
| return self._call_quantized_op_without_fake_kernel( | ||
| op, | ||
| args, | ||
| kwargs, | ||
| meta, | ||
| ) | ||
|
|
||
| return super().call_operator(op, args, kwargs, meta) |
82 changes: 82 additions & 0 deletions
82
backends/cortex_m/passes/materialize_mul_broadcast_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,82 @@ | ||
| # 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 torch | ||
| from executorch.backends.arm._passes.arm_pass_utils import get_first_fake_tensor | ||
| from executorch.backends.cortex_m.passes.passes_utils import ( | ||
| is_channel_broadcast, | ||
| is_channels_last, | ||
| ) | ||
| from executorch.exir.pass_base import ExportPass, PassResult | ||
| from torch.fx import GraphModule, Node | ||
|
|
||
|
|
||
| class MaterializeMulBroadcastPass(ExportPass): | ||
| """Materialize scalar MUL broadcasts unsupported by the Cortex-M kernel. | ||
|
|
||
| ``ReplaceScalarWithTensorArgPass`` represents scalar multiplication as a | ||
| rank-1 ``aten.full`` tensor. When that broadcast is unsupported by the | ||
| Cortex-M quantized MUL kernel, materialize the scalar constant directly at | ||
| the MUL output shape. Leave general tensor broadcasting unchanged so those | ||
| graphs keep their existing fallback behavior. | ||
| """ | ||
|
|
||
| @staticmethod | ||
| def _is_scalar_full(node: Node) -> bool: | ||
| if node.op != "call_function" or node.target != torch.ops.aten.full.default: | ||
| return False | ||
| return get_first_fake_tensor(node).numel() == 1 | ||
|
|
||
| def call(self, graph_module: GraphModule) -> PassResult: | ||
| modified = False | ||
|
|
||
| for node in list(graph_module.graph.nodes): | ||
| if node.op != "call_function" or node.target != torch.ops.aten.mul.Tensor: | ||
| continue | ||
|
|
||
| lhs, rhs = node.args[:2] | ||
| if not isinstance(lhs, Node) or not isinstance(rhs, Node): | ||
| continue | ||
|
|
||
| lhs_tensor = get_first_fake_tensor(lhs) | ||
| rhs_tensor = get_first_fake_tensor(rhs) | ||
| output_tensor = get_first_fake_tensor(node) | ||
|
|
||
| if lhs_tensor.shape == rhs_tensor.shape: | ||
| continue | ||
|
|
||
| if is_channel_broadcast(lhs_tensor, rhs_tensor) and is_channels_last( | ||
| lhs_tensor | ||
| ): | ||
| continue | ||
|
|
||
| output_shape = list(output_tensor.shape) | ||
| new_args = list(node.args) | ||
|
|
||
| for index, arg in enumerate((lhs, rhs)): | ||
| tensor = get_first_fake_tensor(arg) | ||
| if tensor.shape == output_tensor.shape or not self._is_scalar_full(arg): | ||
| continue | ||
|
|
||
| full_args = list(arg.args) | ||
| full_args[0] = output_shape | ||
|
amacharla15 marked this conversation as resolved.
|
||
| with graph_module.graph.inserting_before(node): | ||
| materialized = graph_module.graph.call_function( | ||
| torch.ops.aten.full.default, | ||
| args=tuple(full_args), | ||
| kwargs=dict(arg.kwargs), | ||
| ) | ||
|
|
||
| new_args[index] = materialized | ||
| modified = True | ||
|
|
||
| node.args = tuple(new_args) | ||
|
|
||
| if modified: | ||
| graph_module.graph.eliminate_dead_code() | ||
| graph_module.recompile() | ||
| graph_module = super().call(graph_module).graph_module | ||
|
|
||
| return PassResult(graph_module, modified) | ||
58 changes: 58 additions & 0 deletions
58
backends/cortex_m/passes/materialize_quantized_mul_constants_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,58 @@ | ||
| # 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 executorch.backends.arm._passes import ComputeConstantOpsAOTPass | ||
| from executorch.exir.dialects._ops import ops as exir_ops | ||
| from torch.fx import Node | ||
|
|
||
|
|
||
| class MaterializeQuantizedMulConstantsPass(ComputeConstantOpsAOTPass): | ||
| """Precompute only quantized scalar constants that feed Cortex-M MUL. | ||
|
|
||
| The generic constant-materialization pass also folds unrelated operators | ||
| such as ``arange``. Cortex-M only needs the ``aten.full`` constants created | ||
| for scalar MULs here, after qparams have been attached, so keep the scope | ||
| limited to those nodes. | ||
| """ | ||
|
|
||
| targeted_ops = [exir_ops.edge.aten.full.default] | ||
|
|
||
| _passthrough_ops = { | ||
| exir_ops.edge.aten.clone.default, | ||
| exir_ops.edge.dim_order_ops._clone_dim_order.default, | ||
| } | ||
|
|
||
| @classmethod | ||
| def _feeds_single_quantized_mul(cls, node: Node) -> bool: | ||
| current = node | ||
| visited: set[Node] = set() | ||
|
|
||
| while True: | ||
| users = list(current.users) | ||
| if len(users) != 1: | ||
| return False | ||
|
|
||
| user = users[0] | ||
| if user in visited: | ||
| return False | ||
| visited.add(user) | ||
|
|
||
| if user.target == exir_ops.edge.aten.mul.Tensor: | ||
| return bool(user.meta.get("input_qparams")) and bool( | ||
| user.meta.get("output_qparams") | ||
| ) | ||
|
|
||
| if user.target not in cls._passthrough_ops: | ||
| return False | ||
|
|
||
| current = user | ||
|
|
||
| def compute_node_aot(self, node: Node) -> bool: | ||
| output_qparams = node.meta.get("output_qparams", {}) | ||
| if set(output_qparams) != {0}: | ||
| return False | ||
| if not self._feeds_single_quantized_mul(node): | ||
| return False | ||
| return super().compute_node_aot(node) |
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
17 changes: 17 additions & 0 deletions
17
backends/cortex_m/passes/replace_scalar_with_tensor_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,17 @@ | ||
| # 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 executorch.backends.transforms.replace_scalar_with_tensor import ( | ||
| ReplaceScalarWithTensorArgPass, | ||
| ) | ||
|
|
||
| from .cortex_m_quantized_pass import CortexMQuantizedPass | ||
|
|
||
|
|
||
| class CortexMReplaceScalarWithTensorArgPass( | ||
| ReplaceScalarWithTensorArgPass, | ||
| CortexMQuantizedPass, | ||
| ): | ||
| """Scalar-to-tensor replacement with Cortex-M quantized retracing.""" |
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.