-
Notifications
You must be signed in to change notification settings - Fork 1.1k
NXP backend: added support for scalar args of elementary ops #21011
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
novak-vaclav
wants to merge
1
commit into
pytorch:main
Choose a base branch
from
nxp-upstream:feature/EIEX-987-verify-and-fix-use-of-scalar-args
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.
+243
−0
Open
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| # Copyright 2026 NXP | ||
| # | ||
| # 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 torch.ao.quantization.fx.utils import get_new_attr_name_with_prefix | ||
|
|
||
| from torch.export.unflatten import _assign_attr, _AttrKind | ||
| from torch.fx import GraphModule, Node | ||
| from torch.fx.passes.infra.pass_base import PassBase, PassResult | ||
|
|
||
|
|
||
| class ConvertScalarToAttrPass(PassBase): | ||
| """ | ||
| Convert scalar (Python `int`/`float`) arguments of elementwise operators into | ||
| `get_attr` nodes holding a constant tensor. For example `aten.mul.Tensor(x, 2.0)` | ||
| is rewritten so the scalar `2.0` becomes a `get_attr` node referencing a tensor | ||
| constant with the value `2.0`. | ||
|
|
||
| x x get_attr(2.0) | ||
| | | / | ||
| ┌──────────────▼─────────────┐ replace with ┌────────────────▼───────────────┐ | ||
| | aten.mul.Tensor(x, 2.0) | ─────────────────► | aten.mul.Tensor(x, get_attr) | | ||
| └──────────────┬─────────────┘ └────────────────┬───────────────┘ | ||
| | | | ||
| v v | ||
| out out | ||
|
|
||
| If not done, the scalar arguments prevent from proper QDQ pattern utilization and | ||
| the operator cannot be delegated to Neutron. | ||
| """ | ||
|
|
||
| @staticmethod | ||
| def _get_ref_dtype(node: Node) -> torch.dtype: | ||
| # Infer the constant dtype from a sibling tensor input of the operator so | ||
| # the created constant matches the operator's tensor operand. | ||
| # Fall back to the node's own output dtype, then `float32`. | ||
| for arg in node.args: | ||
| if isinstance(arg, Node): | ||
| arg_val = arg.meta.get("val") | ||
| if isinstance(arg_val, torch.Tensor): | ||
| return arg_val.dtype | ||
|
|
||
| node_val = node.meta.get("val") | ||
| if isinstance(node_val, torch.Tensor): | ||
| return node_val.dtype | ||
|
|
||
| return torch.float32 | ||
|
|
||
| def _create_scalar_attr_node(self, node: Node, scalar_value: int | float) -> Node: | ||
|
Collaborator
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. Nit: |
||
| # Create a constant tensor holding the scalar value. | ||
| tensor = torch.tensor(scalar_value, dtype=self._get_ref_dtype(node)) | ||
| tensor_name = get_new_attr_name_with_prefix("_scalar_const_")(self.graph_module) | ||
|
|
||
| _assign_attr( | ||
| torch.nn.Parameter(tensor, requires_grad=False), | ||
| self.graph_module, | ||
| tensor_name, | ||
| _AttrKind.PARAMETER, | ||
| ) | ||
|
|
||
| fake_mode = node.meta["val"].fake_mode | ||
| with self.graph_module.graph.inserting_before(node): | ||
| get_attr_node = self.graph_module.graph.create_node( | ||
| "get_attr", tensor_name, (), {} | ||
| ) | ||
| get_attr_node.meta["val"] = fake_mode.from_tensor( | ||
| tensor, static_shapes=True | ||
| ) | ||
|
|
||
| return get_attr_node | ||
|
|
||
| def call(self, graph_module: GraphModule) -> PassResult: | ||
| self.graph_module = graph_module | ||
| made_changes = False | ||
|
|
||
| for node in list(graph_module.graph.nodes): | ||
| if node.op != "call_function": | ||
| continue | ||
|
|
||
| new_args = list(node.args) | ||
| node_changed = False | ||
| for i, arg in enumerate(new_args): | ||
| # Note: `bool` is subclass on `int`. | ||
| if isinstance(arg, bool) or not isinstance(arg, (int, float)): | ||
| continue | ||
|
|
||
| new_args[i] = self._create_scalar_attr_node(node, arg) | ||
| node_changed = True | ||
|
|
||
| if node_changed: | ||
| node.args = tuple(new_args) | ||
| made_changes = True | ||
|
|
||
| self.graph_module.graph.eliminate_dead_code() | ||
| self.graph_module.recompile() | ||
|
|
||
| return PassResult(graph_module, made_changes) | ||
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
112 changes: 112 additions & 0 deletions
112
backends/nxp/tests/generic_tests/test_convert_scalar_to_attr.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,112 @@ | ||
| # Copyright 2026 NXP | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| import numpy as np | ||
|
|
||
| # noinspection PyUnusedImports | ||
| import pytest | ||
| import torch | ||
|
|
||
| from executorch.backends.nxp.aten_passes.convert_scalar_to_attr import ( | ||
| ConvertScalarToAttrPass, | ||
| ) | ||
| from executorch.backends.nxp.aten_passes.neutron_aten_pass_manager import ( | ||
| NeutronAtenPassManager, | ||
| ) | ||
| from executorch.backends.nxp.tests.dataset_creator import RandomDatasetCreator | ||
| from executorch.backends.nxp.tests.executorch_pipeline import neutron_target_spec | ||
| from executorch.backends.nxp.tests.executors import graph_contains_any_of_ops | ||
| from executorch.backends.nxp.tests.graph_verifier import DetailedGraphVerifier | ||
| from executorch.backends.nxp.tests.models import ( | ||
| AddScalarModule, | ||
| MulScalarModule, | ||
| SubScalarModule, | ||
| ) | ||
| from executorch.backends.nxp.tests.nsys_testing import AllCloseOutputComparator, lower_run_compare | ||
| from executorch.backends.nxp.tests.ops_aliases import AddTensor, MulTensor, SubTensor | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def reseed_model_per_test_run(): | ||
| torch.manual_seed(42) | ||
| np.random.seed(23) | ||
|
|
||
|
|
||
| class TestConvertScalarToAttr: | ||
| @pytest.mark.parametrize( | ||
| "model_cls, expected_op", | ||
| [ | ||
| pytest.param(AddScalarModule, torch.ops.aten.add.Tensor, id="Add op."), | ||
| pytest.param(SubScalarModule, torch.ops.aten.sub.Tensor, id="Sub op."), | ||
| pytest.param(MulScalarModule, torch.ops.aten.mul.Tensor, id="Mul op."), | ||
| ], | ||
| ) | ||
| def test__scalar_to_attr(self, model_cls, expected_op): | ||
| input_shape = (2, 5, 7, 9) | ||
| model = model_cls(scalar=2.0) | ||
|
|
||
| example_input = torch.rand(input_shape) | ||
| exir_program_aten = torch.export.export(model, (example_input,)).module() | ||
|
|
||
| # Check if the node with scalar arg did not disappear. | ||
| assert graph_contains_any_of_ops(exir_program_aten.graph, [expected_op]) | ||
|
Collaborator
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. Nit: |
||
| outputs_before = [o.detach().numpy() for o in exir_program_aten(example_input)] | ||
|
|
||
| # Apply the optimization. | ||
| NeutronAtenPassManager( | ||
| neutron_target_spec, [ConvertScalarToAttrPass()] | ||
| )(exir_program_aten) | ||
|
|
||
| exp_op_node = [ | ||
| n for n in exir_program_aten.graph.nodes if n.target == expected_op | ||
| ][0] | ||
| # Check that no arg is `float` or `int`. | ||
| # Note: `bool` is subtype of `int`, but `bool` does not need to be converted to `get_attr`. | ||
| assert not any( | ||
| isinstance(arg, (int, float)) and not isinstance(arg, bool) for arg in exp_op_node.args | ||
| ) | ||
|
|
||
| outputs_after = [o.detach().numpy() for o in exir_program_aten(example_input)] | ||
|
|
||
| # Make sure the model still produces the exact same output. | ||
| assert len(outputs_before) == len(outputs_after) | ||
| for i in range(len(outputs_before)): | ||
| assert np.allclose(outputs_before[i], outputs_after[i]) | ||
|
|
||
| @pytest.mark.parametrize( | ||
| "model_cls, expected_op", | ||
| [ | ||
| pytest.param(AddScalarModule, AddTensor, id="Add op."), | ||
| pytest.param(SubScalarModule, SubTensor, id="Sub op."), | ||
| pytest.param(MulScalarModule, MulTensor, id="Mul op."), | ||
| ], | ||
| ) | ||
| def test__scalar_to_attr__full_pipeline( | ||
| self, mocker, request, model_cls, expected_op, | ||
| ): | ||
| input_shape = (2, 7, 5, 11) | ||
| model = model_cls(scalar=2.0) | ||
|
|
||
| graph_verifier = DetailedGraphVerifier( | ||
| mocker, | ||
| expected_delegated_ops={expected_op: 1}, | ||
| expected_non_delegated_ops={}, | ||
| ) | ||
| dataset_creator = RandomDatasetCreator(low=-1.0, high=1.0) | ||
|
|
||
| # Quantize the dataset and allow a single bit error. | ||
| remove_quant_io_ops = True | ||
| comparator = AllCloseOutputComparator(atol=1) | ||
|
|
||
| lower_run_compare( | ||
| model, | ||
| input_shape, | ||
| graph_verifier, | ||
| request, | ||
| dataset_creator, | ||
| comparator, | ||
| remove_quant_io_ops=remove_quant_io_ops, | ||
| ) | ||
|
|
||
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.
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.
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.
Nit:
Perhaps it would be better to call off the modification if we cannot infer the type.