-
Notifications
You must be signed in to change notification settings - Fork 1k
Add extended support from new Neutron C flow for Clamp operator #19510
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
StrycekSimon
wants to merge
4
commits into
pytorch:main
Choose a base branch
from
nxp-upstream:feature/nxg10272/EIEX-864-add-clamp-support-using-new-neutron-flow
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
4 commits
Select commit
Hold shift + click to select a range
683638e
NXP backend: Add use_new_neutron_c_flag to NeutronTargetSpec
StrycekSimon fb27dd9
NXP backend: Replace CustomDelegationOptions with NeutronTargetSpec i…
StrycekSimon cd18329
NXP backend: Enable new Neutron C flow support for Clamp operator
StrycekSimon 54e327d
NXP backend: Add test cases for new Neutron C flow
StrycekSimon 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
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
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 |
|---|---|---|
|
|
@@ -3,15 +3,32 @@ | |
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| import math | ||
|
|
||
| import numpy as np | ||
| import torch | ||
| from executorch.backends.nxp.backend.edge_helper import try_get_arg | ||
| from executorch.backends.nxp.backend.ir.converter.conversion.translator import ( | ||
| torch_type_to_numpy_type, | ||
| ) | ||
| from executorch.backends.nxp.backend.ir.converter.node_converter import ( | ||
| _is_dequant_node, | ||
| _is_quant_node, | ||
| CustomDelegationOptions, | ||
| is_not_qdq_node, | ||
| NodeConverter, | ||
| ) | ||
| from executorch.backends.nxp.backend.ir.converter.quantization_utils import ( | ||
| propagate_quantization, | ||
| ) | ||
| from executorch.backends.nxp.backend.ir.lib.tflite.BuiltinOperator import ( | ||
| BuiltinOperator, | ||
| ) | ||
| from executorch.backends.nxp.backend.ir.tflite_generator import tflite_model | ||
| from executorch.backends.nxp.backend.ir.tflite_generator.builtin_options import ( | ||
| maximum_options, | ||
| minimum_options, | ||
| ) | ||
| from executorch.backends.nxp.backend.neutron_operator_support import ( | ||
| activation_supported_on_target, | ||
| ) | ||
|
|
@@ -21,15 +38,26 @@ | |
| from torch.nn import Parameter | ||
|
|
||
|
|
||
| def _is_convertible_to_relu(node): | ||
| bounds = ClampConverter._get_clamp_bounds(node) | ||
| bounds = tuple(v if v is not None and math.isfinite(v) else None for v in bounds) | ||
|
|
||
| # Some specific bounds can be replaced with single op ReLU. | ||
| if bounds not in ClampConverter.RELU_COMPATIBLE_BOUNDS.values(): | ||
| return False | ||
|
|
||
| return True | ||
|
|
||
|
|
||
| class ClampConverter(NodeConverter): | ||
| SUPPORTED_BOUNDS = { | ||
| RELU_COMPATIBLE_BOUNDS = { | ||
| "ReluN1To1": (-1, 1), | ||
| "Relu0To1": (0, 1), | ||
| "Relu6": (0, 6), | ||
| "Relu": (0, None), | ||
| } | ||
|
|
||
| BOUNDS_TO_NEUTRON_IR_OP = { | ||
| BOUNDS_TO_RELU_NEUTRON_IR_OP = { | ||
| (-1, 1): BuiltinOperator.RELU_N1_TO_1, | ||
| (0, 1): BuiltinOperator.RELU_0_TO_1, | ||
| (0, 6): BuiltinOperator.RELU6, | ||
|
|
@@ -53,27 +81,52 @@ def _is_supported_in_IR( | |
| # No NeutronIR-specific restrictions. | ||
| return True | ||
|
|
||
| @staticmethod | ||
| def _io_quant_is_same(node: Node): | ||
| quant = next(iter(node.users.keys())) | ||
| dequant = node.args[0] | ||
|
|
||
| if not _is_dequant_node(dequant): | ||
| return False | ||
|
|
||
| if not _is_quant_node(quant): | ||
| return False | ||
|
|
||
| q_params = quant.args[1:] | ||
| dq_params = dequant.args[1:] | ||
| return all([q == dq for q, dq in zip(q_params, dq_params)]) | ||
|
|
||
| @staticmethod | ||
| def _is_supported_on_target( | ||
| node: Node, | ||
| neutron_target_spec: NeutronTargetSpec, | ||
| parameters_mapping: dict[str, Parameter], | ||
| custom_delegation_options: CustomDelegationOptions, | ||
| ) -> bool: | ||
| bounds = ClampConverter._get_clamp_bounds(node) | ||
| relu_compatible = _is_convertible_to_relu(node) | ||
|
|
||
| if neutron_target_spec.use_new_flow_neutron_c: | ||
| io_quant_consistent = ClampConverter._io_quant_is_same(node) | ||
| quant_supported = NodeConverter.uses_quantization_type_for_io( | ||
| node, | ||
| supported_types=[torch.int8, torch.uint8], | ||
| input_indices=[0], | ||
| output_indices=[0], | ||
| ) | ||
|
|
||
| # Only some specific bounds are supported on the target hardware. | ||
| if bounds not in ClampConverter.SUPPORTED_BOUNDS.values(): | ||
| return False | ||
| # We either convert to ReLU -> SingleInputQuantization pattern | ||
| # or we convert to Min/Max, which requires same quantization on | ||
| # both input and output. | ||
| return (relu_compatible | io_quant_consistent) and quant_supported | ||
|
|
||
| return True | ||
| return relu_compatible | ||
|
|
||
| @classmethod | ||
| def supports_partitioning_result( | ||
| cls, | ||
| node: Node, | ||
| partition_list: list[Partition], | ||
| custom_delegation_options: CustomDelegationOptions, | ||
| _: CustomDelegationOptions, | ||
| neutron_target_spec: NeutronTargetSpec, | ||
| parameters_mapping: dict[str, Parameter], | ||
| ) -> bool: | ||
|
|
@@ -82,7 +135,10 @@ def supports_partitioning_result( | |
| # Neutron cannot delegate a partition where ReLU or ReLU6 is the only operator | ||
| # and at the same time the node does not satisfy delegation requirements. | ||
| # In contrast, ReLUN1To1 and ReLU0To1 are supported and delegated successfuly. | ||
| if bounds in [cls.SUPPORTED_BOUNDS["Relu"], cls.SUPPORTED_BOUNDS["Relu6"]]: | ||
| if bounds in [ | ||
| cls.RELU_COMPATIBLE_BOUNDS["Relu"], | ||
| cls.RELU_COMPATIBLE_BOUNDS["Relu6"], | ||
| ]: | ||
| is_alone_in_partition = cls.is_node_alone_in_partition( | ||
| node, partition_list, filter_fn=is_not_qdq_node | ||
| ) | ||
|
|
@@ -91,8 +147,21 @@ def supports_partitioning_result( | |
|
|
||
| return True | ||
|
|
||
| @staticmethod | ||
| def _quantize_value( | ||
| value: int, | ||
| zp: int, | ||
| scale: float, | ||
| quant_min: int, | ||
| quant_max: int, | ||
| dtype: type = np.int8, | ||
| ) -> np.integer: | ||
| rescaled_value = round(value / scale) + zp | ||
| return dtype(np.clip(rescaled_value, quant_min, quant_max)) | ||
|
StrycekSimon marked this conversation as resolved.
|
||
|
|
||
| def convert(self, node: Node): | ||
| """Convert the `aten.clamp.default` operator to Neutron IR `Relu*` operators. | ||
| """Convert the `aten.clamp.default` operator to either | ||
| Neutron IR `Relu*` operator or combination of `Min` and `Max`. | ||
| The schema is: | ||
| aten::clamp( | ||
| Tensor self, | ||
|
|
@@ -101,13 +170,83 @@ def convert(self, node: Node): | |
| ) -> Tensor | ||
| """ | ||
| self.assert_convertible(node) | ||
| to_relu = _is_convertible_to_relu(node) | ||
|
|
||
| bounds = self._get_clamp_bounds(node) | ||
|
|
||
| bounds = tuple( | ||
| v if v is not None and math.isfinite(v) else None for v in bounds | ||
| ) | ||
| t_op = self._create_tflite_op_with_io_tensors(node) | ||
|
|
||
| # noinspection PyTypeChecker,PyUnboundLocalVariable | ||
| t_op.opcode_index = self.builder.op_code_index_for_op_type( | ||
| self.BOUNDS_TO_NEUTRON_IR_OP[bounds] | ||
| ) | ||
| self.builder.append_operators([t_op]) | ||
| if not self.neutron_target_spec.use_new_flow_neutron_c or to_relu: | ||
| # noinspection PyTypeChecker,PyUnboundLocalVariable | ||
| t_op.opcode_index = self.builder.op_code_index_for_op_type( | ||
| self.BOUNDS_TO_RELU_NEUTRON_IR_OP[bounds] | ||
| ) | ||
| self.builder.append_operators([t_op]) | ||
| return | ||
|
|
||
| q_node = node.args[0] | ||
| assert _is_dequant_node(q_node) | ||
| _, scale, zp, quant_min, quant_max, q_type = q_node.args | ||
| q_type = torch_type_to_numpy_type(q_type).type | ||
|
|
||
| x = t_op.tmp_inputs[0] | ||
| y = t_op.tmp_outputs[0] | ||
|
|
||
| if x.quantization is not None and y.quantization is None: | ||
| propagate_quantization(x, y) | ||
|
|
||
| min_value, max_value = bounds | ||
|
|
||
| if min_value is not None: | ||
| min_value = self._quantize_value( | ||
| value=min_value, | ||
| zp=zp, | ||
| scale=scale, | ||
| quant_min=quant_min, | ||
| quant_max=quant_max, | ||
| dtype=q_type, | ||
| ) | ||
| min_tensor = self.builder.create_tensor_for_data( | ||
| np.array([min_value], q_type), "min" | ||
| ) | ||
| propagate_quantization(x, min_tensor) | ||
|
|
||
| if max_value is not None: | ||
| max_value = self._quantize_value( | ||
| value=max_value, | ||
| zp=zp, | ||
| scale=scale, | ||
| quant_min=quant_min, | ||
| quant_max=quant_max, | ||
| dtype=q_type, | ||
| ) | ||
| max_tensor = self.builder.create_tensor_for_data( | ||
| np.array([max_value], q_type), "max" | ||
| ) | ||
| propagate_quantization(x, max_tensor) | ||
|
|
||
| if None not in bounds: | ||
| tmp_y = self.builder.duplicate_tensor(x) | ||
| tmp_x = tmp_y | ||
| propagate_quantization(x, tmp_y) | ||
| else: | ||
| tmp_y = y | ||
| tmp_x = x | ||
|
|
||
| ops_to_add = [] | ||
| if max_value is not None: | ||
| min_op = tflite_model.Operator(builtin_options=minimum_options.Minimum()) | ||
| min_op.tmp_inputs = [x, max_tensor] | ||
| min_op.tmp_outputs = [tmp_y] | ||
| ops_to_add.append(min_op) | ||
|
|
||
| if min_value is not None: | ||
| max_op = tflite_model.Operator(builtin_options=maximum_options.Maximum()) | ||
| max_op.tmp_inputs = [tmp_x, min_tensor] | ||
| max_op.tmp_outputs = [y] | ||
| ops_to_add.append(max_op) | ||
|
|
||
| ops_to_add = ops_to_add if len(ops_to_add) >= 1 else [x] | ||
|
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. Why are you assigning a list with the tensor
Collaborator
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. Sorry, should not have trusted Copilot... 😄 |
||
| self.builder.append_operators(ops_to_add) | ||
|
StrycekSimon marked this conversation as resolved.
|
||
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
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.