From d0be101cd9d85c308cd973dde4042e92a505dca8 Mon Sep 17 00:00:00 2001 From: Usamah Zaheer Date: Tue, 3 Nov 2026 14:01:52 +0000 Subject: [PATCH] Add shared elementwise LUT fusion Find single-input, single-output pointwise regions in a shared pass and lower each region directly to one lookup table. Extend Arm table insertion to use the region search, including int16 tables and their output rescale, and configure Cortex-M lowering through a subclass. Fuse add, subtract, multiply and divide with one-element constants. Evaluate regions in FP32, preserving input and constant dequantization and quantizing only the final table entries with backend rounding. Keep graph search independent of backend operators and quantization conventions. Preserve standalone requantization and unary input boundaries, and retain valid suffixes after multi-input operations. Cover integer code domains, branches, constants, mutation boundaries, explicit Q/DQ, Arm int16 interpolation and both Cortex-M layouts. Authored with AI assistance using OpenAI Codex. Jira: MLETORCH-2880 Signed-off-by: Usamah Zaheer Change-Id: I79816eec03db314c38d90faa8a6ef9fa4719f83c --- backends/arm/_passes/insert_table_ops.py | 329 ++++++++---- .../test_arm_fuse_elementwise_to_lut.py | 472 ++++++++++++++++++ .../passes/test_insert_table_ops_lowering.py | 178 +++++++ .../cortex_m/passes/aten_to_cortex_m_pass.py | 52 -- .../cortex_m/passes/cortex_m_pass_manager.py | 9 + .../passes/fuse_elementwise_to_lut_pass.py | 46 ++ .../cortex_m/test/misc/test_quantization.py | 5 +- backends/cortex_m/test/ops/test_sdpa.py | 21 +- backends/cortex_m/test/test_activation_lut.py | 12 +- .../test_cortex_m_fuse_elementwise_to_lut.py | 205 ++++++++ backends/cortex_m/utils.py | 15 +- .../transforms/fuse_elementwise_to_lut.py | 241 +++++++++ .../test/test_fuse_elementwise_to_lut.py | 424 ++++++++++++++++ 13 files changed, 1830 insertions(+), 179 deletions(-) create mode 100644 backends/arm/test/passes/test_arm_fuse_elementwise_to_lut.py create mode 100644 backends/arm/test/passes/test_insert_table_ops_lowering.py create mode 100644 backends/cortex_m/passes/fuse_elementwise_to_lut_pass.py create mode 100644 backends/cortex_m/test/test_cortex_m_fuse_elementwise_to_lut.py create mode 100644 backends/transforms/fuse_elementwise_to_lut.py create mode 100644 backends/transforms/test/test_fuse_elementwise_to_lut.py diff --git a/backends/arm/_passes/insert_table_ops.py b/backends/arm/_passes/insert_table_ops.py index d2b2f8ccf39..59a25ce3ed6 100644 --- a/backends/arm/_passes/insert_table_ops.py +++ b/backends/arm/_passes/insert_table_ops.py @@ -14,18 +14,19 @@ POW_LOG_POSITIVE_LOWER_BOUND_META, ) from executorch.backends.arm._passes.quant_args import QuantArgs -from executorch.backends.arm._passes.tosa_lowering_utils import create_rescale_node -from executorch.backends.transforms.utils import create_constant_placeholder +from executorch.backends.arm._passes.tosa_lowering_utils import set_rescale_args +from executorch.backends.transforms.fuse_elementwise_to_lut import ( + FuseElementwiseToLUTPass, + FusionRegion, +) from executorch.exir import ExportedProgram 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.export.graph_signature import InputKind -from torch.fx import GraphModule -from torch.fx.node import Node +from executorch.exir.pass_base import ExportPass +from torch.fx.node import map_arg, Node class TableOps: @@ -160,26 +161,208 @@ def included_ops() -> Iterator[EdgeOpOverload]: return chain(TableOps.unary_table_ops, TableOps.special_table_ops) -class InsertTableOpsPass(ArmPass): - """For ops in self.table_ops they need to be serialized as a TOSA TABLE. - - This pass replaces these edge ops with a tosa._table(input: Tensor, - target_str: str) where target_str == str(node.target). When lowering the - _table node target_str will be used to find the corresponding torch operator - which will be used to produce the table values in operators/op_table.py. - +class InsertTableOpsPass(FuseElementwiseToLUTPass, ArmPass): + """Lower quantized pointwise regions directly to INT8 or INT16 TOSA + TABLE. """ _passes_required_after: Set[Type[ExportPass]] = set() + quantize_op = exir_ops.edge.quantized_decomposed.quantize_per_tensor.default + dequantize_op = exir_ops.edge.quantized_decomposed.dequantize_per_tensor.default + + arithmetic_ops = { + exir_ops.edge.aten.add.Tensor, + exir_ops.edge.aten.sub.Tensor, + exir_ops.edge.aten.mul.Tensor, + exir_ops.edge.aten.div.Tensor, + exir_ops.edge.aten.clamp.default, + exir_ops.edge.aten.minimum.default, + exir_ops.edge.aten.maximum.default, + } def __init__(self, exported_program: ExportedProgram) -> None: - super().__init__() - self.exported_program = exported_program + super().__init__( + exported_program, + exir_ops.backend.tosa.TABLE.default, + { + *TableOps.included_ops(), + *self.arithmetic_ops, + self.quantize_op, + self.dequantize_op, + }, + supported_dtypes=( + torch.int8, + torch.int16, + torch.int32, + torch.float32, + torch.float64, + ), + min_region_size=1, + ) self.table_ops = TableOps(exported_program) + self.table_targets = set(TableOps.included_ops()) + + def _is_supported_node(self, node: Node) -> bool: + if node.target == self.table_op or not super()._is_supported_node(node): + return False + if node.target in (self.quantize_op, self.dequantize_op): + if any(isinstance(arg, Node) for arg in node.args[1:]): + return False + if node.target == self.quantize_op: + source = node.args[0] + if not isinstance(source, Node): + return False + if ( + source.target == self.dequantize_op + and source.args[5] != node.args[5] + ): + # Keep dtype-changing requantization outside the LUT domain. + return False + return self._is_supported_node(source) + return True + inputs = node.meta.get("input_qparams", {}) + outputs = node.meta.get("output_qparams", {}) + if not inputs and not outputs: + return node.meta["val"].is_floating_point() + return ( + bool(inputs) + and set(outputs) == {0} + and all( + not qparams.per_channel + for qparams in (*inputs.values(), *outputs.values()) + ) + and all( + index in inputs or self._constant(arg) is not None + for index, arg in enumerate(node.args) + if isinstance(arg, Node) + ) + ) + + def _region_input_qparams(self, region: FusionRegion) -> list[QuantArgs]: + qparams = [] + for node in region.nodes: + for index, arg in enumerate(node.args): + if arg is not region.input_node: + continue + if node.target == self.dequantize_op: + qparams.append(QuantArgs.from_operator(node.target, node.args)) + elif index in node.meta.get("input_qparams", {}): + qparams.append(node.meta["input_qparams"][index]) + else: + return [] + return qparams + + def _region_output_qparams(self, region: FusionRegion) -> dict[int, QuantArgs]: + sink = region.nodes[-1] + if sink.target == self.quantize_op: + return {0: QuantArgs.from_operator(sink.target, sink.args)} + return sink.meta.get("output_qparams", {}) + + def _find_fusion_region(self, sink: Node) -> FusionRegion | None: + region = super()._find_fusion_region(sink) + if region is None or ( + len(region.nodes) == 1 and sink.target not in self.table_targets + ): + return None + pointwise_ops = sum( + node.target not in (self.quantize_op, self.dequantize_op) + for node in region.nodes + ) + if pointwise_ops == 0: + return None + if pointwise_ops == 1: + table_index = next( + ( + index + for index, node in enumerate(region.nodes) + if node.target in self.table_targets + ), + None, + ) + if table_index is not None: + for index in range(table_index - 1, -1, -1): + if region.nodes[index].target == self.quantize_op: + # A lone TABLE already lowers the operator; keep its + # input requantization visible near singularities. + region = FusionRegion( + region.nodes[index + 1 :], region.nodes[index] + ) + break + qparams = self._region_input_qparams(region) + if ( + not qparams + or region.input_node.meta["val"].dtype != qparams[0].dtype + or any(value != qparams[0] for value in qparams) + ): + return None + outputs = self._region_output_qparams(region) + if not outputs or (qparams[0].dtype, outputs[0].dtype) not in ( + (torch.int8, torch.int8), + (torch.int16, torch.int16), + (torch.int16, torch.int32), + ): + return None + return region + + def _evaluate_region( + self, region: FusionRegion, value: torch.Tensor + ) -> torch.Tensor: + values = {region.input_node: value.to(torch.float32)} + for node in region.nodes: + args = [] + for index, arg in enumerate(node.args): + if not isinstance(arg, Node): + args.append(arg) + continue + constant = self._constant(arg) + if constant is None: + args.append(values[arg]) + continue + tensor = constant.reshape(()).to(torch.float32) + qparams = node.meta.get("input_qparams", {}).get(index) + if node.target == self.dequantize_op: + qparams = QuantArgs.from_operator(node.target, node.args) + args.append( + (tensor - qparams.get_zp_per_tensor()) + * qparams.get_scale_per_tensor() + if qparams + else tensor + ) + # Region inputs are already dequantized by the table generator. + # Keep internal edges in float until it quantizes the final result. + values[node] = ( + cast(torch.Tensor, args[0]) + if node.target in (self.quantize_op, self.dequantize_op) + else self._evaluate_node( + node, args, map_arg(node.kwargs, values.__getitem__) + ) + ) + return values[region.nodes[-1]] - def register_buffer(self, buffer_name: str, buffer: torch.Tensor) -> None: - """Add buffer to self.exported_program.state_dict.""" - self.exported_program.state_dict[buffer_name] = buffer + def _evaluate_node(self, node: Node, args: list, kwargs: dict) -> torch.Tensor: + if node in self.table_ops: + if node.meta.get("input_qparams"): + self._validate_pow_log_positive_lower_bound( + node, node.meta["input_qparams"][0] + ) + return self.table_ops[node](args[0]) + if node.target == exir_ops.edge.aten.clamp.default and node.meta.get( + "output_qparams" + ): + # QuantizeClampArgumentsPass has already encoded the bounds. + qparams = node.meta["output_qparams"][0] + for index in range(1, len(args)): + if args[index] is not None: + args[index] = ( + args[index] - qparams.get_zp_per_tensor() + ) * qparams.get_scale_per_tensor() + kwargs = dict(kwargs) + for key in ("min", "max"): + if kwargs.get(key) is not None: + kwargs[key] = ( + kwargs[key] - qparams.get_zp_per_tensor() + ) * qparams.get_scale_per_tensor() + return cast(EdgeOpOverload, node.target)(*args, **kwargs) @staticmethod def _validate_pow_log_positive_lower_bound( @@ -356,79 +539,37 @@ def generate_table_values( f"Unsupported output dtype for table: {out_quantargs.dtype}" ) - def call(self, graph_module: GraphModule) -> PassResult: - modified = False - for node in graph_module.graph.nodes: - if node.op != "call_function" or node not in self.table_ops: - continue - input_qparams = node.meta.get("input_qparams", {}) - output_qparams = node.meta.get("output_qparams", {}) - if len(input_qparams) == 0 or len(output_qparams) == 0: - # We only want to replace the node if it's quantized - continue - # Create table node - insert_pos = list(node.graph.nodes)[0] - with graph_module.graph.inserting_before(insert_pos): - # Expect exactly one quantization parameter for input and output - if len(input_qparams) != 1: - raise ValueError( - f"InsertTableOpsPass expected exactly one input quantization parameter, " - f"got {len(input_qparams)} for node {node.name}" - ) - if len(output_qparams) != 1: - raise ValueError( - f"InsertTableOpsPass expected exactly one output quantization parameter, " - f"got {len(output_qparams)} for node {node.name}" - ) - - # Generate table buffer and how much to lshift the table output. - input_qargs = input_qparams[0] - self._validate_pow_log_positive_lower_bound(node, input_qargs) - buffer, lshift = self.generate_table_values( - torch_op=self.table_ops[node], - in_quantargs=input_qargs, - out_quantargs=output_qparams[0], - ) - # Register buffer in self.exported_program.state_dict - # b_ prefix is important to be recognized as a constant in RemovePermutesAroundElementwiseOps - const_table_node = create_constant_placeholder( - exp_program=self.exported_program, - graph=node.graph, - kind=InputKind.BUFFER, - name="b_" + node.name + "_table_constant", - data=buffer, - persistent_buffer=True, - ) - - # Create table node - with graph_module.graph.inserting_before(node): - table_op_node = create_node( - graph=graph_module.graph, - op_target=exir_ops.backend.tosa.TABLE.default, - args=(node.args[0], const_table_node), - ) - table_op_node.meta["val"] = exir_ops.backend.tosa.TABLE.default( - node.args[0].meta["val"], const_table_node.meta["val"] + def _fuse_region(self, region: FusionRegion) -> None: + sink = region.nodes[-1] + input_qparams = {0: self._region_input_qparams(region)[0]} + output_qparams = self._region_output_qparams(region) + table, lshift = self.generate_table_values( + lambda value: self._evaluate_region(region, value), + input_qparams[0], + output_qparams[0], + ) + table_node = self._insert_table_constant(region, table) + sink.target = self.table_op + sink.args = (region.input_node, table_node) + sink.kwargs = {} + sink.meta["input_qparams"] = input_qparams + sink.meta["output_qparams"] = output_qparams + sink.meta["val"] = torch.empty_like( + sink.meta["val"], dtype=output_qparams[0].dtype + ) + if lshift != 0: + with sink.graph.inserting_before(sink): + table_op = create_node( + sink.graph, cast(EdgeOpOverload, self.table_op), args=sink.args ) - output_node = table_op_node - - if lshift != 0: - scale = 2.0**lshift - rescale_node = create_rescale_node( - graph=graph_module.graph, - args=(table_op_node, output_qparams[0].dtype, [scale], 0, 0), - ) - output_node = rescale_node - - node.replace_all_uses_with(output_node) - graph_module.graph.erase_node(node) - table_op_node.meta["input_qparams"] = input_qparams - table_op_node.meta["output_qparams"] = output_qparams - modified = True - - if modified: - # retrace the graph to update the fake tensor types - graph_module = super().call(graph_module).graph_module - - graph_module.recompile() - return PassResult(graph_module, modified) + table_op.meta["input_qparams"] = input_qparams + table_op.meta["output_qparams"] = output_qparams + table_op.meta["val"] = torch.empty_like( + region.input_node.meta["val"], dtype=torch.int32 + ) + sink.target = exir_ops.backend.tosa.RESCALE.default + set_rescale_args( + sink, table_op, output_qparams[0].dtype, [2.0**lshift], 0, 0 + ) + sink.meta.pop("input_qparams") + sink.meta.pop("output_qparams") diff --git a/backends/arm/test/passes/test_arm_fuse_elementwise_to_lut.py b/backends/arm/test/passes/test_arm_fuse_elementwise_to_lut.py new file mode 100644 index 00000000000..8edecf60782 --- /dev/null +++ b/backends/arm/test/passes/test_arm_fuse_elementwise_to_lut.py @@ -0,0 +1,472 @@ +# 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 + +import torch +from executorch.backends.arm._passes.insert_table_ops import InsertTableOpsPass +from executorch.backends.arm._passes.quant_args import QuantArgs +from executorch.backends.arm._passes.tosa_lowering_utils import rescale_parameters +from executorch.backends.transforms.utils import get_param_tensor +from executorch.exir import to_edge +from executorch.exir.dialects._ops import ops as exir_ops +from torch.export import export + + +class _SigmoidTanh(torch.nn.Module): + def forward(self, x): + return torch.tanh(torch.sigmoid(x)) + + +def _quantized_region(dtype=torch.int8, arithmetic=False, scalar_input=False): + class InputWithConstant(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("constant", torch.tensor([[7]], dtype=dtype)) + + def forward(self, x): + return x + self.constant + + info = torch.iinfo(dtype) + domain = ( + torch.arange(info.min, info.max + 1, dtype=torch.int32).to(dtype).reshape(1, -1) + ) + if scalar_input: + domain = domain[:, :1] + program = to_edge(export(InputWithConstant(), (domain,))).exported_program() + graph = program.graph + constant, source = [node for node in graph.nodes if node.op == "placeholder"] + sink = next(node for node in graph.nodes if node.op == "call_function") + input_qparams = QuantArgs( + 0.05 if dtype == torch.int8 else 0.0001, 3, info.min, info.max, dtype + ) + hidden_qparams = QuantArgs( + 0.01 if dtype == torch.int8 else 0.00005, -10, info.min, info.max, dtype + ) + output_qparams = QuantArgs(hidden_qparams.scale, -7, info.min, info.max, dtype) + with graph.inserting_before(sink): + first = graph.call_function(exir_ops.edge.aten.sigmoid.default, (source,)) + first.meta = sink.meta.copy() + first.meta["input_qparams"] = {0: input_qparams} + first.meta["output_qparams"] = {0: hidden_qparams} + previous = first + if arithmetic: + constant_qparams = QuantArgs(0.05, 2, info.min, info.max, dtype) + for target in ( + exir_ops.edge.aten.add.Tensor, + exir_ops.edge.aten.sub.Tensor, + exir_ops.edge.aten.mul.Tensor, + exir_ops.edge.aten.div.Tensor, + ): + node = graph.call_function(target, (previous, constant)) + node.meta = sink.meta.copy() + node.meta["input_qparams"] = {0: hidden_qparams, 1: constant_qparams} + node.meta["output_qparams"] = {0: hidden_qparams} + previous = node + sink.target = exir_ops.edge.aten.tanh.default + sink.args = (previous,) + sink.meta["input_qparams"] = {0: hidden_qparams} + sink.meta["output_qparams"] = {0: output_qparams} + graph.eliminate_dead_code() + graph.lint() + program.graph_module.recompile() + return program, source, first, sink, domain + + +class FuseElementwiseToLUTTests(unittest.TestCase): + def test_quantized_arithmetic_dequantizes_only_constant_operands(self): + from executorch.backends.arm.tosa.specification import ( + TosaLoweringContext, + TosaSpecification, + ) + + program, source, first, sink, domain = _quantized_region(arithmetic=True) + input_qparams = first.meta["input_qparams"][0] + hidden_qparams = first.meta["output_qparams"][0] + output_qparams = sink.meta["output_qparams"][0] + value = torch.sigmoid(input_qparams.dequantize_value(domain)) + previous = hidden_qparams.quantize_value(value) + for op in (torch.add, torch.sub, torch.mul, torch.div): + value = op(value, torch.tensor(0.25)) + previous = hidden_qparams.quantize_value( + op(hidden_qparams.dequantize_value(previous), torch.tensor(0.25)) + ) + reference = torch.tanh(value) + expected = output_qparams.quantize_value(reference) + previous = output_qparams.quantize_value( + torch.tanh(hidden_qparams.dequantize_value(previous)) + ) + + with TosaLoweringContext(TosaSpecification.create_from_string("TOSA-1.0+INT")): + result = InsertTableOpsPass(program).call(program.graph_module) + program.validate() + + self.assertTrue(result.modified) + calls = [node for node in program.graph.nodes if node.op == "call_function"] + self.assertEqual(calls, [sink]) + self.assertIs(sink.target, exir_ops.backend.tosa.TABLE.default) + self.assertIs(sink.args[0], source) + self.assertEqual(sink.meta["input_qparams"], {0: input_qparams}) + self.assertEqual(sink.meta["output_qparams"], {0: output_qparams}) + actual = get_param_tensor(program, sink.args[1]).reshape_as(domain) + torch.testing.assert_close(actual, expected) + error = (output_qparams.dequantize_value(actual) - reference).abs() + previous_error = (output_qparams.dequantize_value(previous) - reference).abs() + self.assertLess(error.mean(), previous_error.mean()) + self.assertLess(error.max(), previous_error.max()) + self.assertNotIn("constant", program.state_dict) + + def test_int16_chain_builds_one_interpolated_table_and_rescale(self): + from executorch.backends.arm.tosa.specification import ( + TosaLoweringContext, + TosaSpecification, + ) + + program, source, first, sink, domain = _quantized_region(dtype=torch.int16) + input_qparams = first.meta["input_qparams"][0] + hidden_qparams = first.meta["output_qparams"][0]._replace(scale=0.0005) + first.meta["output_qparams"][0] = hidden_qparams + sink.meta["input_qparams"][0] = hidden_qparams + output_qparams = sink.meta["output_qparams"][0] + reference = torch.tanh(torch.sigmoid(input_qparams.dequantize_value(domain))) + hidden = hidden_qparams.quantize_value( + torch.sigmoid(input_qparams.dequantize_value(domain)) + ) + previous = output_qparams.quantize_value( + torch.tanh(hidden_qparams.dequantize_value(hidden)) + ) + expected = output_qparams.quantize_value(reference) + with TosaLoweringContext( + TosaSpecification.create_from_string("TOSA-1.0+INT+int16") + ): + self.assertTrue( + InsertTableOpsPass(program).call(program.graph_module).modified + ) + program.validate() + + tables = [ + node + for node in program.graph.nodes + if node.target == exir_ops.backend.tosa.TABLE.default + ] + self.assertEqual(len(tables), 1) + self.assertIs(tables[0].args[0], source) + table = get_param_tensor(program, tables[0].args[1]) + self.assertEqual(table.dtype, torch.int16) + self.assertEqual(table.numel(), 513) + self.assertIs(sink.target, exir_ops.backend.tosa.RESCALE.default) + self.assertAlmostEqual(rescale_parameters(sink)[0][0], 1 / 128) + self.assertIs(sink.kwargs["dtype"], torch.int16) + index = (domain.to(torch.int32) + 32768) >> 7 + fraction = domain.to(torch.int32) & 127 + interpolated = ( + table[index].to(torch.int32) * (128 - fraction) + + table[index + 1].to(torch.int32) * fraction + ) + actual = ((interpolated + 64) >> 7).to(torch.int16) + self.assertLessEqual( + int((actual.to(torch.int32) - expected.to(torch.int32)).abs().max()), 2 + ) + error = (output_qparams.dequantize_value(actual) - reference).abs() + previous_error = (output_qparams.dequantize_value(previous) - reference).abs() + self.assertLess(error.mean(), previous_error.mean()) + self.assertLess(error.max(), previous_error.max()) + + def test_explicit_qdq_region_keeps_internal_values_in_fp32(self): + for dtype in (torch.int8, torch.int16): + with self.subTest(dtype=dtype): + program, _, first, sink, _ = _quantized_region( + dtype=dtype, arithmetic=True, scalar_input=True + ) + input_qparams = first.meta["input_qparams"][0] + output_qparams = sink.meta["output_qparams"][0] + info = torch.iinfo(dtype) + domain = torch.arange(info.min, info.max + 1, dtype=torch.int32).to( + dtype + ) + reference = torch.sigmoid(input_qparams.dequantize_value(domain)) + for op in (torch.add, torch.sub, torch.mul, torch.div): + reference = op(reference, torch.tensor(0.25)) + reference = torch.tanh(reference) + graph = program.graph + for node in list(graph.nodes): + if node.op != "call_function": + continue + args = list(node.args) + with graph.inserting_before(node): + for index, qparams in node.meta.pop("input_qparams").items(): + dequant = graph.call_function( + InsertTableOpsPass.dequantize_op, + (args[index], *qparams[:5]), + ) + dequant.meta["val"] = torch.empty_like( + args[index].meta["val"], dtype=torch.float32 + ) + args[index] = dequant + node.args = tuple(args) + qparams = node.meta.pop("output_qparams")[0] + users = list(node.users) + with graph.inserting_after(node): + quant = graph.call_function( + InsertTableOpsPass.quantize_op, (node, *qparams[:5]) + ) + quant.meta["val"] = node.meta["val"] + node.meta["val"] = torch.empty_like( + node.meta["val"], dtype=torch.float32 + ) + for user in users: + user.replace_input_with(node, quant) + graph.lint() + fusion = InsertTableOpsPass(program) + region = fusion._find_fusion_region(quant) + self.assertIsNotNone(region) + self.assertEqual(fusion._region_input_qparams(region), [input_qparams]) + self.assertEqual( + fusion._region_output_qparams(region), {0: output_qparams} + ) + actual = fusion._evaluate_region( + region, input_qparams.dequantize_value(domain) + ) + self.assertEqual(actual.dtype, torch.float32) + torch.testing.assert_close(actual, reference, rtol=0, atol=0) + + def test_single_unary_preserves_input_requantization(self): + from executorch.backends.arm.tosa.specification import ( + TosaLoweringContext, + TosaSpecification, + ) + + for target, op, output_scale in ( + (exir_ops.edge.aten.asin.default, torch.asin, 0.02), + (exir_ops.edge.aten.acos.default, torch.acos, 0.02), + (exir_ops.edge.aten.atanh.default, torch.atanh, 0.1), + ): + with self.subTest(target=target): + program, source, _, sink, _ = _quantized_region(scalar_input=True) + input_qparams = QuantArgs(1 / 255, -128, -128, 127, torch.int8) + activation_qparams = QuantArgs(1 / 128, 0, -128, 127, torch.int8) + output_qparams = QuantArgs(output_scale, 0, -128, 127, torch.int8) + graph = program.graph + with graph.inserting_before(sink): + dequant = graph.call_function( + InsertTableOpsPass.dequantize_op, + (source, *input_qparams[:5]), + ) + dequant.meta["val"] = torch.empty_like( + source.meta["val"], dtype=torch.float32 + ) + requant = graph.call_function( + InsertTableOpsPass.quantize_op, + (dequant, *activation_qparams[:5]), + ) + requant.meta["val"] = source.meta["val"] + sink.target = target + sink.args = (requant,) + sink.meta["input_qparams"] = {0: activation_qparams} + sink.meta["output_qparams"] = {0: output_qparams} + graph.eliminate_dead_code() + graph.lint() + program.graph_module.recompile() + + with TosaLoweringContext( + TosaSpecification.create_from_string("TOSA-1.0+INT") + ): + self.assertTrue( + InsertTableOpsPass(program).call(program.graph_module).modified + ) + program.validate() + + self.assertIs(sink.target, exir_ops.backend.tosa.TABLE.default) + table = get_param_tensor(program, sink.args[1]) + input_code = torch.tensor([127], dtype=torch.int8) + activation_code = activation_qparams.quantize_value( + input_qparams.dequantize_value(input_code) + ) + expected = output_qparams.quantize_value( + op(activation_qparams.dequantize_value(activation_code)) + ) + self.assertEqual( + table[int(activation_code.item()) + 128].item(), + expected.item(), + ) + self.assertIs(sink.args[0], requant) + self.assertIs(requant.args[0], dequant) + + def test_pure_int16_requantization_does_not_become_table(self): + program, source, _, sink, _ = _quantized_region( + dtype=torch.int16, scalar_input=True + ) + input_qparams = QuantArgs(1.0, 0, -32768, 32767, torch.int16) + output_qparams = QuantArgs(0.0006408887, 0, -32768, 32767, torch.int16) + graph = program.graph + with graph.inserting_before(sink): + dequant = graph.call_function( + InsertTableOpsPass.dequantize_op, + (source, *input_qparams[:5]), + ) + dequant.meta["val"] = torch.empty_like( + source.meta["val"], dtype=torch.float32 + ) + sink.target = InsertTableOpsPass.quantize_op + sink.args = (dequant, *output_qparams[:5]) + sink.meta.pop("input_qparams") + sink.meta.pop("output_qparams") + graph.eliminate_dead_code() + graph.lint() + program.graph_module.recompile() + + self.assertFalse( + InsertTableOpsPass(program).call(program.graph_module).modified + ) + program.validate() + self.assertIs(sink.target, InsertTableOpsPass.quantize_op) + self.assertIs(sink.args[0], dequant) + self.assertFalse( + any( + node.target == exir_ops.backend.tosa.TABLE.default + for node in program.graph.nodes + ) + ) + raw = torch.tensor([-21, -11, 18], dtype=torch.int16) + actual = output_qparams.dequantize_value( + output_qparams.quantize_value(input_qparams.dequantize_value(raw)) + ) + torch.testing.assert_close(actual, raw.to(torch.float32), rtol=0, atol=0.001) + + def test_single_unary_with_explicit_output_quantization_keeps_input_boundary(self): + from executorch.backends.arm.tosa.specification import ( + TosaLoweringContext, + TosaSpecification, + ) + + program, source, _, sink, _ = _quantized_region(scalar_input=True) + input_qparams = QuantArgs(1 / 255, -128, -128, 127, torch.int8) + activation_qparams = QuantArgs(1 / 128, 0, -128, 127, torch.int8) + output_qparams = QuantArgs(0.02, 0, -128, 127, torch.int8) + graph = program.graph + with graph.inserting_before(sink): + dequant = graph.call_function( + InsertTableOpsPass.dequantize_op, + (source, *input_qparams[:5]), + ) + dequant.meta["val"] = torch.empty_like( + source.meta["val"], dtype=torch.float32 + ) + requant = graph.call_function( + InsertTableOpsPass.quantize_op, + (dequant, *activation_qparams[:5]), + ) + requant.meta["val"] = source.meta["val"] + activation_input = graph.call_function( + InsertTableOpsPass.dequantize_op, + (requant, *activation_qparams[:5]), + ) + activation_input.meta["val"] = dequant.meta["val"] + unary = graph.call_function( + exir_ops.edge.aten.asin.default, (activation_input,) + ) + unary.meta["val"] = dequant.meta["val"] + sink.target = InsertTableOpsPass.quantize_op + sink.args = (unary, *output_qparams[:5]) + sink.meta.pop("input_qparams") + sink.meta.pop("output_qparams") + graph.eliminate_dead_code() + graph.lint() + program.graph_module.recompile() + + with TosaLoweringContext(TosaSpecification.create_from_string("TOSA-1.0+INT")): + self.assertTrue( + InsertTableOpsPass(program).call(program.graph_module).modified + ) + program.validate() + + self.assertIs(sink.target, exir_ops.backend.tosa.TABLE.default) + self.assertIs(sink.args[0], requant) + table = get_param_tensor(program, sink.args[1]) + expected = output_qparams.quantize_value( + torch.asin( + activation_qparams.dequantize_value( + torch.tensor([127], dtype=torch.int8) + ) + ) + ) + self.assertEqual(table[-1].item(), expected.item()) + + def test_per_channel_region_is_rejected(self): + program, _, first, sink, _ = _quantized_region() + first.meta["input_qparams"][0] = first.meta["input_qparams"][0]._replace( + per_channel=True + ) + sink.meta["output_qparams"][0] = sink.meta["output_qparams"][0]._replace( + per_channel=True + ) + self.assertIsNone(InsertTableOpsPass(program)._find_fusion_region(sink)) + + def test_int16_input_with_int32_output_keeps_rescale(self): + from executorch.backends.arm.tosa.specification import ( + TosaLoweringContext, + TosaSpecification, + ) + + program, _, _, sink, _ = _quantized_region(dtype=torch.int16) + sink.meta["output_qparams"][0] = QuantArgs( + 1e-8, 0, -2147483648, 2147483647, torch.int32 + ) + sink.meta["val"] = torch.empty_like(sink.meta["val"], dtype=torch.int32) + with TosaLoweringContext( + TosaSpecification.create_from_string("TOSA-1.0+INT+int16") + ): + assert InsertTableOpsPass(program).call(program.graph_module).modified + program.validate() + + self.assertIs(sink.target, exir_ops.backend.tosa.RESCALE.default) + self.assertIs(sink.kwargs["dtype"], torch.int32) + self.assertGreater(rescale_parameters(sink)[0][0], 1) + table_op = sink.args[0] + table = get_param_tensor(program, table_op.args[1]) + self.assertEqual(table.dtype, torch.int16) + self.assertEqual(table.numel(), 513) + + def test_arm_quantized_chain_lowers_to_one_table(self): + from executorch.backends.arm._passes import FoldAndAnnotateQParamsPass + from executorch.backends.arm._passes.arm_pass_manager import ArmPassManager + from executorch.backends.arm._passes.insert_table_ops import InsertTableOpsPass + from executorch.backends.arm.quantizer import ( + get_symmetric_quantization_config, + TOSAQuantizer, + ) + from executorch.backends.arm.tosa.compile_spec import TosaCompileSpec + from executorch.backends.arm.tosa.specification import TosaLoweringContext + from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e + + x = torch.randn(2, 5, generator=torch.Generator().manual_seed(42)) + spec = TosaCompileSpec("TOSA-1.0+INT") + quantizer = TOSAQuantizer(spec) + quantizer.set_global(get_symmetric_quantization_config()) + prepared = prepare_pt2e(export(_SigmoidTanh(), (x,)).module(), quantizer) + prepared(x) + quantized = convert_pt2e(prepared) + program = to_edge(export(quantized, (x,))).exported_program() + manager = ArmPassManager(spec) + manager.add_pass(FoldAndAnnotateQParamsPass(program)) + manager.add_pass(InsertTableOpsPass(program)) + + with TosaLoweringContext(spec.tosa_spec): + manager._transform(program, program.graph_module) + program.validate() + + self.assertEqual( + sum( + node.op == "call_function" + and node.target == exir_ops.backend.tosa.TABLE.default + for node in program.graph.nodes + ), + 1, + ) + self.assertEqual(len(program.state_dict), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/backends/arm/test/passes/test_insert_table_ops_lowering.py b/backends/arm/test/passes/test_insert_table_ops_lowering.py new file mode 100644 index 00000000000..22eb20a9db4 --- /dev/null +++ b/backends/arm/test/passes/test_insert_table_ops_lowering.py @@ -0,0 +1,178 @@ +# 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 copy import deepcopy + +import pytest +import torch +from executorch.backends.arm._passes.insert_table_ops import InsertTableOpsPass +from executorch.backends.arm.quantizer.quantization_config import QuantizationConfig +from executorch.backends.arm.test.tester.test_pipeline import TosaPipelineINT +from executorch.exir.dialects._ops import ops as exir_ops +from torchao.quantization.pt2e import HistogramObserver +from torchao.quantization.pt2e.quantizer import QuantizationSpec + + +class Unary(torch.nn.Module): + def __init__(self, op): + super().__init__() + self.op = op + + def forward(self, x): + return self.op(x) + + +class Sigmoid(torch.nn.Module): + def __init__(self, with_add): + super().__init__() + self.sigmoid = torch.nn.Sigmoid() + self.with_add = with_add + + def forward(self, x): + value = self.sigmoid(x) + return self.sigmoid(value + value) if self.with_add else value + + +class FloorDiv(torch.nn.Module): + def forward(self, x, y): + return torch.div(x, y, rounding_mode="floor") + + +@pytest.fixture +def table_graphs(monkeypatch): + graphs = [] + original = InsertTableOpsPass.call + + def capture(self, graph_module): + result = original(self, graph_module) + graphs.append(deepcopy(result.graph_module)) + return result + + monkeypatch.setattr(InsertTableOpsPass, "call", capture) + return graphs + + +@pytest.mark.parametrize( + "op,values", + [ + (torch.acosh, [1.01, 1.1, 2.0, 3.0]), + (torch.asin, [0.0, 0.25, 0.5, 0.75]), + (torch.asinh, [-1.0, 0.0, 1.0, 2.0]), + (torch.atanh, [-0.5, -0.25, 0.0, 0.5]), + (torch.acos, [0.0, 0.25, 0.5, 0.75]), + (torch.expm1, [0.0, 0.25, 0.5, 1.0]), + (torch.erfinv, [0.125, 0.25, 0.5, 0.75]), + (torch.cosh, [0.5, 1.0, 1.5, 2.0]), + (torch.log10, [0.5, 1.0, 1.5, 2.0]), + (torch.tan, [-0.5, -0.25, 0.0, 0.5]), + ], + ids=lambda value: value.__name__ if callable(value) else None, +) +def test_integer_promoting_unary_lowers_to_int8_table(op, values, table_graphs): + pipeline = TosaPipelineINT( + Unary(op), (torch.tensor(values),), [], run_on_tosa_ref_model=False + ) + pipeline.pop_stage("to_executorch") + pipeline.count_tosa_ops({"TABLE": 1}) + pipeline.run() + + tables = [ + node + for graph in table_graphs + for node in graph.graph.nodes + if node.target == exir_ops.backend.tosa.TABLE.default + ] + assert len(tables) == 1 + assert tables[0].meta["val"].dtype == torch.int8 + assert tables[0].args[0].meta["val"].dtype == torch.int8 + + +@pytest.mark.parametrize("with_add", [False, True]) +def test_int32_requantization_stays_outside_int16_sigmoid_table(with_add, table_graphs): + pipeline = TosaPipelineINT( + Sigmoid(with_add), + (torch.linspace(-16, 16, 17),), + [], + tosa_extensions=["int16"], + run_on_tosa_ref_model=False, + ) + int16_spec, int32_spec = ( + QuantizationSpec( + dtype=dtype, + observer_or_fake_quant_ctr=HistogramObserver, + qscheme=torch.per_tensor_symmetric, + ) + for dtype in (torch.int16, torch.int32) + ) + pipeline.quantizer.set_global( + QuantizationConfig( + input_activation=int32_spec, + output_activation=int32_spec, + weight=None, + bias=None, + ) + ) + pipeline.quantizer.set_module_type( + torch.nn.Sigmoid, + QuantizationConfig( + input_activation=int16_spec, + output_activation=int32_spec, + weight=None, + bias=None, + ), + ) + pipeline.pop_stage("to_executorch") + pipeline.count_tosa_ops({"TABLE": 2 if with_add else 1, "SIGMOID": 0}) + pipeline.run() + + tables = [ + node + for graph in table_graphs + for node in graph.graph.nodes + if node.target == exir_ops.backend.tosa.TABLE.default + ] + assert len(tables) == (2 if with_add else 1) + for table in tables: + quantize = table.args[0] + assert quantize.target == InsertTableOpsPass.quantize_op + assert quantize.meta["val"].dtype == torch.int16 + assert quantize.args[0].target == InsertTableOpsPass.dequantize_op + assert quantize.args[0].args[5] == torch.int32 + assert table.meta["val"].dtype == torch.int32 + rescale = next(iter(table.users)) + assert rescale.target == exir_ops.backend.tosa.RESCALE.default + assert rescale.meta["val"].dtype == torch.int32 + + +def test_int32_floor_div_lowers_reciprocal_after_int8_requantization(table_graphs): + pipeline = TosaPipelineINT( + FloorDiv(), + ( + torch.tensor([[-101, -29, 31, 199]], dtype=torch.int32), + torch.tensor([[11, 13, 17, 19]], dtype=torch.int32), + ), + [], + tosa_extensions=["u55"], + run_on_tosa_ref_model=False, + ) + pipeline.pop_stage("to_executorch") + pipeline.count_tosa_ops({"TABLE": 2, "RECIPROCAL": 0}) + pipeline.run() + + reciprocal_tables = [ + node + for graph in table_graphs + for node in graph.graph.nodes + if node.target == exir_ops.backend.tosa.TABLE.default + and node.args[0].target == InsertTableOpsPass.quantize_op + ] + assert len(reciprocal_tables) == 1 + table = reciprocal_tables[0] + assert table.meta["val"].dtype == torch.int8 + quantize = table.args[0] + assert quantize.meta["val"].dtype == torch.int8 + dequantize = quantize.args[0] + assert dequantize.target == InsertTableOpsPass.dequantize_op + assert dequantize.args[5] == torch.int32 diff --git a/backends/cortex_m/passes/aten_to_cortex_m_pass.py b/backends/cortex_m/passes/aten_to_cortex_m_pass.py index 21e3a7f5d2f..e34f682832d 100644 --- a/backends/cortex_m/passes/aten_to_cortex_m_pass.py +++ b/backends/cortex_m/passes/aten_to_cortex_m_pass.py @@ -22,7 +22,6 @@ from executorch.backends.cortex_m.target_config import CortexMTargetConfig from executorch.backends.cortex_m.utils import ( - build_activation_lut, is_foldable_alpha, quantize_multiplier_aot, quantize_val, @@ -270,57 +269,6 @@ def _has_qparams(node: Node) -> bool: ) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.sigmoid.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.tanh.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.silu.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.gelu.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.log.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.log2.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.log10.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.log1p.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.sqrt.default) -@AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.rsqrt.default) -def _get_activation_replacement( - node: Node, dialect_pass: AtenToDialectPass -) -> DialectNodeSpec | None: - """Lower a standalone quantized unary activation to a single - cortex_m.quantized_activation call backed by an AoT-built 256-entry - int8 LUT. The kernel is shape-agnostic; the LUT encodes both the - activation function and the input/output qparams. - """ - if not _has_qparams(node): - return None - - exported_program = dialect_pass.exported_program - input_qparams = node.meta["input_qparams"][0] - output_qparams = node.meta["output_qparams"][0] - lut_tensor = build_activation_lut( - node.target, - float(input_qparams.scale), - int(input_qparams.zp), - float(output_qparams.scale), - int(output_qparams.zp), - ) - - # Constant placeholders must appear before user-input placeholders; - # anchor on the first existing placeholder so the new LUT lands in the - # constant-placeholder block at the top of the graph. - first_placeholder = next(n for n in node.graph.nodes if n.op == "placeholder") - with node.graph.inserting_before(first_placeholder): - lut_node = create_constant_placeholder( - exported_program, - node.graph, - node.name + "_lut", - InputKind.PARAMETER, - lut_tensor, - ) - - new_args = (node.args[0], lut_node) - return DialectNodeSpec( - exir_ops.edge.cortex_m.quantized_activation.default, new_args - ) - - @AtenToCortexMPass.register_dialect_substitution(exir_ops.edge.aten.linear.default) def _get_linear_replacement( node: Node, dialect_pass: AtenToDialectPass diff --git a/backends/cortex_m/passes/cortex_m_pass_manager.py b/backends/cortex_m/passes/cortex_m_pass_manager.py index d4e56db84a3..e85163559b2 100644 --- a/backends/cortex_m/passes/cortex_m_pass_manager.py +++ b/backends/cortex_m/passes/cortex_m_pass_manager.py @@ -15,6 +15,9 @@ FoldAndAnnotateQParamsPass, ScalarsToAttributePass, ) +from executorch.backends.arm._passes.arm_pass_manager import ( + _ExportedProgramGraphPassAdapter, +) from executorch.backends.cortex_m.target_config import CortexM, CortexMTargetConfig from executorch.backends.cortex_m.utils import _ACTIVATION_FNS from executorch.backends.transforms.aten_to_dialect_pass import AtenToDialectPass @@ -62,6 +65,7 @@ ValidateCortexMExplicitLayoutPass, ) from .fuse_conv_padding_pass import FuseConvPaddingPass +from .fuse_elementwise_to_lut_pass import FuseQuantizedElementwiseToLUTPass from .initialize_scratch_buffers_pass import InitializeScratchBuffersPass from .matmul_to_bmm_pass import MatmulToBmmPass from .quantized_clamp_activation_pass import QuantizedClampActivationPass @@ -138,6 +142,9 @@ def call(self, exported_program: ExportedProgram) -> ExportedProgramPassResult: kwargs["target_config"] = self.target_config transform_pass = _preserving_quantized_dtype(pass_cls)(**kwargs) + if isinstance(transform_pass, FuseQuantizedElementwiseToLUTPass): + # Constant creation must update the pass manager's shallow copy. + transform_pass = _ExportedProgramGraphPassAdapter(transform_pass) transformed = _transform(exported_program, transform_pass) modified |= transformed is not exported_program exported_program = transformed @@ -157,6 +164,7 @@ class CortexMPassManager(ExportedProgramPassManager): ConvertFullLikeToFullPass, ComputeQuantizedConstantOpsPass, DecomposeHardswishPass, + FuseQuantizedElementwiseToLUTPass, AtenToCortexMPass, # Retrace only after quantized ATen ops have become Cortex-M kernels. ReplaceQuantNodesPass, @@ -184,6 +192,7 @@ class CortexMPassManager(ExportedProgramPassManager): RemovePermutesAroundElementwiseOps, CortexMCanonicalizeViewCopyPermutePass, ValidateCortexMExplicitLayoutPass, + FuseQuantizedElementwiseToLUTPass, ReplaceQuantNodesPass, AtenToCortexMPass, FuseConvPaddingPass, diff --git a/backends/cortex_m/passes/fuse_elementwise_to_lut_pass.py b/backends/cortex_m/passes/fuse_elementwise_to_lut_pass.py new file mode 100644 index 00000000000..4c0c5d633f9 --- /dev/null +++ b/backends/cortex_m/passes/fuse_elementwise_to_lut_pass.py @@ -0,0 +1,46 @@ +# 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 collections.abc import Callable + +import torch +from executorch.backends.arm._passes.insert_table_ops import InsertTableOpsPass +from executorch.backends.arm._passes.quant_args import QuantArgs +from executorch.backends.cortex_m.utils import _ACTIVATION_FNS, build_activation_lut +from executorch.exir.dialects._ops import ops as exir_ops +from torch.export import ExportedProgram + + +class FuseQuantizedElementwiseToLUTPass(InsertTableOpsPass): + """Use the shared region search with Cortex-M table and rounding semantics.""" + + def __init__(self, exported_program: ExportedProgram) -> None: + super().__init__(exported_program) + self.table_op = exir_ops.edge.cortex_m.quantized_activation.default + self.table_targets = set(_ACTIVATION_FNS) + self.supported_ops = ( + self.table_targets + | self.arithmetic_ops + | {self.quantize_op, self.dequantize_op} + ) + self.supported_dtypes = (torch.int8, torch.float32, torch.float64) + + def generate_table_values( + self, + torch_op: Callable[[torch.Tensor], torch.Tensor], + in_quantargs: QuantArgs, + out_quantargs: QuantArgs, + ) -> tuple[torch.Tensor, int]: + return ( + build_activation_lut( + None, + in_quantargs.get_scale_per_tensor(), + in_quantargs.get_zp_per_tensor(), + out_quantargs.get_scale_per_tensor(), + out_quantargs.get_zp_per_tensor(), + activation_fn=torch_op, + ), + 0, + ) diff --git a/backends/cortex_m/test/misc/test_quantization.py b/backends/cortex_m/test/misc/test_quantization.py index 9253f8d2a3a..17f09928cfe 100644 --- a/backends/cortex_m/test/misc/test_quantization.py +++ b/backends/cortex_m/test/misc/test_quantization.py @@ -252,9 +252,10 @@ class SharedQspecSurroundedQuantizedOp(torch.nn.Module): } ops_after_transforms = { "executorch_exir_dialects_edge__ops_cortex_m_dequantize_per_tensor_default": 1, - "executorch_exir_dialects_edge__ops_cortex_m_maximum_default": 1, + "executorch_exir_dialects_edge__ops_cortex_m_maximum_default": 0, "executorch_exir_dialects_edge__ops_cortex_m_quantize_per_tensor_default": 1, - "executorch_exir_dialects_edge__ops_cortex_m_quantized_add_default": 1, + "executorch_exir_dialects_edge__ops_cortex_m_quantized_add_default": 0, + "executorch_exir_dialects_edge__ops_cortex_m_quantized_activation_default": 1, "executorch_exir_dialects_edge__ops_dim_order_ops__clone_dim_order_default": 1, } diff --git a/backends/cortex_m/test/ops/test_sdpa.py b/backends/cortex_m/test/ops/test_sdpa.py index a537d3980ee..77644d4ffff 100644 --- a/backends/cortex_m/test/ops/test_sdpa.py +++ b/backends/cortex_m/test/ops/test_sdpa.py @@ -7,7 +7,7 @@ from collections import Counter import torch -from executorch.backends.arm.test.common import parametrize, xfail_type +from executorch.backends.arm.test.common import parametrize from executorch.backends.cortex_m.quantizer.quantizer import CortexMQuantizer from executorch.backends.cortex_m.test.tester import CortexMTester, McuTestCase @@ -113,23 +113,6 @@ def _qkv(query_shape, key_shape, value_shape, dtype=torch.float32): "rank2": McuTestCase(CortexMSDPA(), _qkv((8, 16), (8, 16), (8, 16))), } -_SCALE_NOT_FOLDED = ( - "The attention scale mul is left as an fp32 aten.mul between dequantize " - "and quantize, no pass folds it into the quantize yet" -) -_LINEAR_RETRACED_AS_INT32 = ( - "Retracing a folded quantized linear gives an int32 output, which fails " - "the dtype check of the bmm consuming it" -) - -xfail_cases_dialect: dict[str, xfail_type] = { - "self_attention": (_SCALE_NOT_FOLDED, RuntimeError), - "cross_attention": (_SCALE_NOT_FOLDED, RuntimeError), - "rank3": (_SCALE_NOT_FOLDED, RuntimeError), - "explicit_scale": (_SCALE_NOT_FOLDED, RuntimeError), - "multihead_attention": (_LINEAR_RETRACED_AS_INT32, Exception), -} - def _transform_for_annotation(model, example_inputs, dynamic_shapes=None): # Without check_guards=False, whether export adds a _guards_fn call_module, @@ -146,7 +129,7 @@ def _op_counts(graph_module) -> Counter: ) -@parametrize("test_case", test_cases, xfails=xfail_cases_dialect) +@parametrize("test_case", test_cases) def test_dialect_sdpa(test_case, cortex_m_target): tester = CortexMTester( test_case.model, test_case.example_inputs, target_config=cortex_m_target diff --git a/backends/cortex_m/test/test_activation_lut.py b/backends/cortex_m/test/test_activation_lut.py index e2e80d0d566..17d2a21823e 100644 --- a/backends/cortex_m/test/test_activation_lut.py +++ b/backends/cortex_m/test/test_activation_lut.py @@ -15,9 +15,8 @@ import unittest import torch -from executorch.backends.cortex_m.passes.aten_to_cortex_m_pass import ( - _get_activation_replacement, - AtenToCortexMPass, +from executorch.backends.cortex_m.passes.fuse_elementwise_to_lut_pass import ( + FuseQuantizedElementwiseToLUTPass, ) from executorch.backends.cortex_m.quantizer.quantizer_support import ( ACTIVATION_OP_PATTERNS, @@ -113,11 +112,8 @@ def test_every_registry_lists_the_same_activations(self): } # gelu is the exception: torch exposes no in-place spelling for it. self.assertEqual(in_place, quantizer - {aten.gelu.default}) - substituted = { - target - for target, fn in AtenToCortexMPass._DIALECT_SUBSTITUTIONS.items() - if fn is _get_activation_replacement - } + program = torch.export.export(torch.nn.Identity(), (torch.ones(2),)) + substituted = FuseQuantizedElementwiseToLUTPass(program).table_targets self.assertEqual(quantizer, set(_ACTIVATION_FNS)) self.assertEqual(quantizer, substituted) diff --git a/backends/cortex_m/test/test_cortex_m_fuse_elementwise_to_lut.py b/backends/cortex_m/test/test_cortex_m_fuse_elementwise_to_lut.py new file mode 100644 index 00000000000..6b5854fe5f7 --- /dev/null +++ b/backends/cortex_m/test/test_cortex_m_fuse_elementwise_to_lut.py @@ -0,0 +1,205 @@ +# 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 pytest +import torch +from executorch.backends.arm._passes.quant_args import QuantArgs +from executorch.backends.cortex_m.library import cmsis_nn +from executorch.backends.cortex_m.passes.cortex_m_pass_manager import CortexMPassManager +from executorch.backends.cortex_m.passes.fuse_elementwise_to_lut_pass import ( + FuseQuantizedElementwiseToLUTPass, +) +from executorch.backends.cortex_m.target_config import CortexM, CortexMTargetConfig +from executorch.backends.cortex_m.test.tester import CortexMTester +from executorch.backends.cortex_m.utils import _ACTIVATION_FNS, build_activation_lut +from executorch.backends.transforms.utils import get_param_tensor +from executorch.exir import to_edge +from executorch.exir.dialects._ops import ops as exir_ops +from torch.export import export + + +class _SigmoidTanh(torch.nn.Module): + def forward(self, x): + return torch.tanh(torch.sigmoid(x)) + + +class _ScalarArithmetic(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("constant", torch.tensor([0.25])) + + def forward(self, x): + value = torch.sigmoid(x) + self.constant + value = (value - self.constant) * self.constant + return torch.tanh(value / self.constant) + + +@pytest.mark.parametrize("explicit_layout", [False, True]) +def test_unary_after_two_input_add_lowers_to_table(explicit_layout): + class AddSqrt(torch.nn.Module): + def forward(self, x, y): + return torch.sqrt(x + y) + + inputs = (torch.linspace(0, 2, 256), torch.linspace(0, 3, 256)) + tester = CortexMTester( + AddSqrt(), + inputs, + target_config=CortexMTargetConfig(cpu=CortexM.M55, isa=cmsis_nn.Backend.MVE), + ) + tester.test_dialect( + { + "executorch_exir_dialects_edge__ops_aten_add_Tensor": 1, + "executorch_exir_dialects_edge__ops_aten_sqrt_default": 1, + }, + { + "executorch_exir_dialects_edge__ops_aten_sqrt_default": 0, + "executorch_exir_dialects_edge__ops_cortex_m_quantized_add_default": 1, + "executorch_exir_dialects_edge__ops_cortex_m_quantized_activation_default": 1, + }, + qtol=2, + use_explicit_layout=explicit_layout, + ) + + +@pytest.mark.parametrize("explicit_layout", [False, True]) +@pytest.mark.parametrize("model", [_SigmoidTanh, _ScalarArithmetic]) +def test_cortex_m_quantized_chain_lowers_to_one_table(explicit_layout, model): + from executorch.backends.cortex_m.edge_compile_config import ( + cortex_m_edge_compile_config, + ) + from executorch.backends.cortex_m.quantizer.quantizer import CortexMQuantizer + from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e + + x = torch.randn(2, 5, generator=torch.Generator().manual_seed(42)) + prepared = prepare_pt2e( + export(model(), (x,)).module(), + CortexMQuantizer(use_explicit_layout=explicit_layout), + ) + prepared(x) + quantized = convert_pt2e(prepared) + expected = quantized(x) + output_scale = [ + node.args[1] + for node in quantized.graph.nodes + if node.target == torch.ops.quantized_decomposed.dequantize_per_tensor.default + ][-1] + edge = to_edge( + export(quantized, (x,)), + compile_config=cortex_m_edge_compile_config(), + ) + manager = CortexMPassManager( + use_explicit_layout=explicit_layout, + target_config=CortexMTargetConfig(cpu=CortexM.M55, isa=cmsis_nn.Backend.MVE), + ) + passes = manager.passes[0].pass_classes + assert FuseQuantizedElementwiseToLUTPass in passes + + program = edge.transform(manager).exported_program() + + program.validate() + assert ( + sum( + node.op == "call_function" + and node.target == exir_ops.edge.cortex_m.quantized_activation.default + for node in program.graph.nodes + ) + == 1 + ) + assert len(program.state_dict) == 1 + torch.testing.assert_close( + program.module()(x), expected, rtol=0, atol=2 * output_scale + ) + + +@pytest.mark.parametrize("folded_qdq", [False, True]) +def test_chain_table_improves_accuracy_over_intermediate_qdq(folded_qdq): + from executorch.backends.cortex_m.edge_compile_config import ( + cortex_m_edge_compile_config, + ) + from executorch.backends.cortex_m.quantizer.quantizer import CortexMQuantizer + from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e + + x = torch.linspace(-6.5, 6.25, 256) + model = _SigmoidTanh() + prepared = prepare_pt2e(export(model, (x,)).module(), CortexMQuantizer()) + prepared(x) + edge = to_edge( + export(convert_pt2e(prepared), (x,)), + compile_config=cortex_m_edge_compile_config(), + ) + program = edge.exported_program() + input_qparams, hidden_qparams, output_qparams = [ + QuantArgs.from_operator(node.target, node.args) + for node in program.graph.nodes + if node.target == FuseQuantizedElementwiseToLUTPass.quantize_op + ] + if folded_qdq: + program = edge.transform( + CortexMPassManager( + target_config=CortexMTargetConfig( + cpu=CortexM.M55, isa=cmsis_nn.Backend.MVE + ) + ) + ).exported_program() + else: + assert ( + FuseQuantizedElementwiseToLUTPass(program) + .call(program.graph_module) + .modified + ) + program.validate() + tables = [ + node + for node in program.graph.nodes + if node.target == exir_ops.edge.cortex_m.quantized_activation.default + ] + assert len(tables) == 1 + table = tables[0] + assert table.meta["input_qparams"] == {0: input_qparams} + assert table.meta["output_qparams"] == {0: output_qparams} + + def quantize(value, qparams): + scaled = value / qparams.scale + qparams.zp + return ( + (torch.sign(scaled) * torch.floor(torch.abs(scaled) + 0.5)) + .clamp(qparams.qmin, qparams.qmax) + .to(qparams.dtype) + ) + + domain = torch.arange(-128, 128, dtype=torch.int8) + inputs = input_qparams.dequantize_value(domain) + reference = model(inputs) + actual = get_param_tensor(program, table.args[1]) + torch.testing.assert_close(actual, quantize(reference, output_qparams)) + previous_hidden = quantize(torch.sigmoid(inputs), hidden_qparams) + previous = quantize( + torch.tanh(hidden_qparams.dequantize_value(previous_hidden)), output_qparams + ) + error = (output_qparams.dequantize_value(actual) - reference).abs() + previous_error = (output_qparams.dequantize_value(previous) - reference).abs() + assert error.mean() < previous_error.mean() + assert error.max() < previous_error.max() + + +@pytest.mark.parametrize("target", list(_ACTIVATION_FNS)) +def test_standalone_activation_preserves_table_entries(target): + program = to_edge(export(torch.nn.Sigmoid(), (torch.ones(256),))).exported_program() + source = next(node for node in program.graph.nodes if node.op == "placeholder") + sink = next(node for node in program.graph.nodes if node.op == "call_function") + source.meta["val"] = torch.empty_like(source.meta["val"], dtype=torch.int8) + sink.meta["val"] = torch.empty_like(sink.meta["val"], dtype=torch.int8) + sink.target = target + sink.meta["input_qparams"] = {0: QuantArgs(0.02, 0, -128, 127, torch.int8)} + sink.meta["output_qparams"] = {0: QuantArgs(0.05, 7, -128, 127, torch.int8)} + + assert ( + FuseQuantizedElementwiseToLUTPass(program).call(program.graph_module).modified + ) + + program.validate() + torch.testing.assert_close( + get_param_tensor(program, sink.args[1]), + build_activation_lut(target, 0.02, 0, 0.05, 7), + ) diff --git a/backends/cortex_m/utils.py b/backends/cortex_m/utils.py index 66a80929957..6534aef75cc 100644 --- a/backends/cortex_m/utils.py +++ b/backends/cortex_m/utils.py @@ -279,28 +279,35 @@ def build_activation_lut( input_zp: int, output_scale: float, output_zp: int, + *, + activation_fn: Callable[[torch.Tensor], torch.Tensor] | None = None, ) -> torch.Tensor: """AoT-compute a 256-entry int8 lookup table for a quantized activation. `target` is the edge-dialect op being lowered (e.g. - `exir_ops.edge.aten.sigmoid.default`). + `exir_ops.edge.aten.sigmoid.default`). When `activation_fn` is supplied, + `target` can be None: the callback replaces it and evaluates the complete + region on a dequantized floating-point tensor before final quantization. The LUT is indexed by the input byte value biased by 128: for any int8 input `q_in`, the kernel reads `lut[q_in + 128]` to get the int8 output. Because the LUT is computed in float and quantized once per entry, the runtime kernel is a single memory-lookup with no requantization math. """ - if target not in _ACTIVATION_FNS: + if activation_fn is None and target not in _ACTIVATION_FNS: raise ValueError( f"build_activation_lut: unsupported activation target {target!r} " f"(supported: {sorted(t.__name__ for t in _ACTIVATION_FNS)})" ) - f = _ACTIVATION_FNS[target] + values = None + if activation_fn is not None: + domain = (torch.arange(-128, 128, dtype=torch.float64) - input_zp) * input_scale + values = activation_fn(domain) defined: dict[int, int] = {} undefined: list[int] = [] for q in range(-128, 128): x = (q - input_zp) * input_scale - y = f(x) + y = values[q + 128].item() if values is not None else _ACTIVATION_FNS[target](x) scaled = y / output_scale + output_zp if math.isfinite(y) else y if math.isnan(scaled): # log of a negative, rsqrt of a negative. Filled in below. diff --git a/backends/transforms/fuse_elementwise_to_lut.py b/backends/transforms/fuse_elementwise_to_lut.py new file mode 100644 index 00000000000..06e84ed639e --- /dev/null +++ b/backends/transforms/fuse_elementwise_to_lut.py @@ -0,0 +1,241 @@ +# 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. + +"""Find and lower single-input, single-output pointwise regions.""" + +from collections import Counter +from collections.abc import Callable, Collection +from dataclasses import dataclass + +import torch +from executorch.backends.transforms.utils import ( + create_constant_placeholder, + delete_constant_placeholder, + get_param_tensor, + is_param_node, +) +from executorch.exir.pass_base import ExportPass +from torch.export import ExportedProgram +from torch.export.graph_signature import InputKind +from torch.fx import GraphModule, Node +from torch.fx.node import map_arg +from torch.fx.passes.infra.pass_base import PassResult + + +@dataclass(frozen=True) +class FusionRegion: + nodes: tuple[Node, ...] + input_node: Node + + +class FuseElementwiseToLUTPass(ExportPass): + """Replace single-input, single-output int8 pointwise regions with a TABLE. + + The caller supplies a TABLE target with ``(input, table)`` arguments and + ``table[input + 128]`` semantics, and pure pointwise targets that can be + evaluated in integer code space. Backend quantization restrictions and + metadata updates belong in backend specializations. Backends can override + table generation and replacement for other table formats. + """ + + def __init__( + self, + exported_program: ExportedProgram, + table_op: Callable, + supported_ops: Collection[Callable], + *, + region_filter: Callable[[FusionRegion], bool] | None = None, + supported_dtypes: Collection[torch.dtype] = (torch.int8,), + min_region_size: int = 2, + ) -> None: + super().__init__() + self.exported_program = exported_program + self.table_op = table_op + self.supported_ops = {*supported_ops, table_op} + self.region_filter = region_filter + self.supported_dtypes = supported_dtypes + self.min_region_size = min_region_size + + def _constant(self, node: Node) -> torch.Tensor | None: + if node.op != "placeholder" or not is_param_node(self.exported_program, node): + return None + signature = self.exported_program.graph_signature + buffer_target = signature.inputs_to_buffers.get(node.name) + if buffer_target in signature.buffers_to_mutate.values(): + return None + return get_param_tensor(self.exported_program, node) + + def _is_supported_node(self, node: Node) -> bool: + if node.op != "call_function" or node.target not in self.supported_ops: + return False + value = node.meta.get("val") + if ( + not isinstance(value, torch.Tensor) + or value.dtype not in self.supported_dtypes + ): + return False + if node.target == self.table_op: + _, table = node.args + data = self._constant(table) + return ( + data is not None and data.dtype == torch.int8 and data.shape == (256,) + ) + return all( + data is None or data.numel() == 1 + for arg in node.all_input_nodes + for data in (self._constant(arg),) + ) + + def _data_inputs(self, node: Node) -> list[Node]: + return [arg for arg in node.all_input_nodes if self._constant(arg) is None] + + def _single_input_suffix(self, nodes: tuple[Node, ...]) -> FusionRegion | None: + candidates = set(nodes) + inputs = Counter( + arg + for node in nodes + for arg in self._data_inputs(node) + if arg not in candidates + ) + # A multi-input prefix can still feed a single-input suffix. + for start in range(len(nodes) - self.min_region_size + 1): + if len(inputs) == 1: + return FusionRegion(nodes[start:], next(iter(inputs))) + node = nodes[start] + candidates.remove(node) + for arg in self._data_inputs(node): + inputs[arg] -= 1 + if inputs[arg] == 0: + del inputs[arg] + users = sum(user in candidates for user in node.users) + if users: + inputs[node] = users + return None + + def _find_fusion_region(self, sink: Node) -> FusionRegion | None: + candidates: set[Node] = set() + pending = [sink] + while pending: + node = pending.pop() + if node in candidates or not self._is_supported_node(node): + continue + candidates.add(node) + pending.extend(self._data_inputs(node)) + + # An interior result with an outside consumer is a boundary tensor. + while True: + exposed = { + node + for node in candidates - {sink} + if any(user not in candidates for user in node.users) + } + if not exposed: + break + candidates.difference_update(exposed) + + if len(candidates) < self.min_region_size: + return None + region = self._single_input_suffix( + tuple(node for node in sink.graph.nodes if node in candidates) + ) + if region is None: + return None + input_value = region.input_node.meta.get("val") + if ( + not isinstance(input_value, torch.Tensor) + or input_value.dtype not in self.supported_dtypes + ): + return None + if any(node.meta["val"].shape != input_value.shape for node in region.nodes): + return None + if self.region_filter is not None and not self.region_filter(region): + return None + return region + + def _build_lookup_table(self, region: FusionRegion) -> torch.Tensor: + values = {region.input_node: torch.arange(-128, 128, dtype=torch.int8)} + for node in region.nodes: + for arg in node.all_input_nodes: + constant = self._constant(arg) + if constant is not None: + values[arg] = ( + constant.reshape(()) if constant.numel() == 1 else constant + ) + args = map_arg(node.args, values.__getitem__) + kwargs = map_arg(node.kwargs, values.__getitem__) + if node.target == self.table_op: + input_tensor, table = args + values[node] = table[input_tensor.to(torch.int64) + 128] + else: + values[node] = node.target(*args, **kwargs) + table = values[region.nodes[-1]] + if table.dtype != torch.int8 or table.shape != (256,): + raise ValueError( + "Configured pointwise operators must produce 256 int8 codes" + ) + return table + + def _insert_table_constant(self, region: FusionRegion, table: torch.Tensor) -> Node: + graph = region.input_node.graph + first_placeholder = next( + node for node in graph.nodes if node.op == "placeholder" + ) + with graph.inserting_before(first_placeholder): + return create_constant_placeholder( + self.exported_program, + graph, + f"b_{region.nodes[-1].name}_fused_table_constant", + InputKind.BUFFER, + table, + persistent_buffer=True, + ) + + def _fuse_region(self, region: FusionRegion) -> None: + table_node = self._insert_table_constant( + region, self._build_lookup_table(region) + ) + sink = region.nodes[-1] + sink.target = self.table_op + sink.args = (region.input_node, table_node) + sink.kwargs = {} + + def call(self, graph_module: GraphModule) -> PassResult: + graph = graph_module.graph + modified = False + for sink in reversed(list(graph.nodes)): + if sink not in graph.nodes or not self._is_supported_node(sink): + continue + region = self._find_fusion_region(sink) + if region is None: + continue + old_constants = { + arg + for node in region.nodes + for arg in node.all_input_nodes + if self._constant(arg) is not None + } + self._fuse_region(region) + for node in reversed(region.nodes[:-1]): + graph.erase_node(node) + signature = self.exported_program.graph_signature + protected = { + spec.target + for spec in signature.output_specs + if spec.target is not None + } + for constant in old_constants: + if not constant.users: + target = next( + spec.target + for spec in signature.input_specs + if spec.arg.name == constant.name + ) + if target not in protected: + delete_constant_placeholder(self.exported_program, constant) + modified = True + + if modified: + graph_module.recompile() + return PassResult(graph_module, modified) diff --git a/backends/transforms/test/test_fuse_elementwise_to_lut.py b/backends/transforms/test/test_fuse_elementwise_to_lut.py new file mode 100644 index 00000000000..94e24ba9bd5 --- /dev/null +++ b/backends/transforms/test/test_fuse_elementwise_to_lut.py @@ -0,0 +1,424 @@ +# 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 + +import torch +from executorch.backends.transforms.fuse_elementwise_to_lut import ( + FuseElementwiseToLUTPass, +) +from executorch.backends.transforms.utils import ( + _validate_graph_signature, + create_constant_placeholder, + get_param_tensor, +) +from executorch.exir import to_edge +from executorch.exir.dialects._ops import ops as exir_ops +from torch.export import export +from torch.export.graph_signature import ( + ExportGraphSignature, + InputKind, + OutputKind, + OutputSpec, + TensorArgument, +) + + +@torch.library.custom_op("test_elementwise_lut::lookup_table", mutates_args=()) +def _lookup_table(input: torch.Tensor, table: torch.Tensor) -> torch.Tensor: + return table[input.to(torch.int64) + 128] + + +@_lookup_table.register_fake +def _lookup_table_fake(input, table): + return torch.empty_like(input) + + +def _fusion_pass(program, table_op=None, **kwargs): + if table_op is None: + table_op = exir_ops.edge.test_elementwise_lut.lookup_table.default + return FuseElementwiseToLUTPass( + program, + table_op, + { + exir_ops.edge.aten.clamp.default, + exir_ops.edge.aten.minimum.default, + exir_ops.edge.aten.maximum.default, + }, + **kwargs, + ) + + +class _Identity(torch.nn.Module): + def forward(self, x): + return x + + +class _TwoInputs(torch.nn.Module): + def forward(self, x, y): + return x, y + + +def _program(two_inputs=False): + model = _TwoInputs() if two_inputs else _Identity() + inputs = (torch.arange(-128, 128, dtype=torch.int8),) + if two_inputs: + inputs += (torch.arange(-128, 128, dtype=torch.int8),) + program = to_edge(export(model, inputs)).exported_program() + placeholders = [node for node in program.graph.nodes if node.op == "placeholder"] + return program, placeholders + + +def _table(program, target, input_node, values, name): + graph = program.graph + first = next(node for node in graph.nodes if node.op == "placeholder") + with graph.inserting_before(first): + constant = create_constant_placeholder( + program, + graph, + name, + InputKind.BUFFER, + values, + persistent_buffer=True, + ) + output = graph.output_node() + with graph.inserting_before(output): + node = graph.call_function(target, (input_node, constant)) + node.meta["val"] = input_node.meta["val"] + return node + + +def _constant(program, values, name): + first = next(node for node in program.graph.nodes if node.op == "placeholder") + with program.graph.inserting_before(first): + return create_constant_placeholder( + program, + program.graph, + name, + InputKind.BUFFER, + values, + persistent_buffer=True, + ) + + +def _set_output(program, node): + program.graph.output_node().args = ((node,),) + program._graph_signature = ExportGraphSignature( + program.graph_signature.input_specs, + [OutputSpec(OutputKind.USER_OUTPUT, TensorArgument(node.name), None)], + ) + + +class FuseElementwiseToLUTTests(unittest.TestCase): + def test_linear_chain_with_configured_table_target(self): + domain = torch.arange(-128, 128, dtype=torch.int8) + for target in ( + torch.ops.test_elementwise_lut.lookup_table.default, + exir_ops.edge.test_elementwise_lut.lookup_table.default, + ): + with self.subTest(target=target): + program, (source,) = _program() + first_values = torch.bitwise_xor( + domain, torch.tensor(0x55, dtype=torch.int8) + ) + second_values = torch.flip(domain, (0,)) + first = _table(program, target, source, first_values, "first_lut") + with program.graph.inserting_before(program.graph.output_node()): + clamp = program.graph.call_function( + exir_ops.edge.aten.clamp.default, (first, -20, 30) + ) + clamp.meta["val"] = source.meta["val"] + last = _table(program, target, clamp, second_values, "last_lut") + _set_output(program, last) + + result = _fusion_pass(program, target).call(program.graph_module) + + self.assertTrue(result.modified) + tables = [ + node for node in program.graph.nodes if node.op == "call_function" + ] + self.assertEqual(len(tables), 1) + self.assertIs(tables[0].target, target) + self.assertIs(tables[0].args[0], source) + expected = second_values[ + torch.clamp(first_values, -20, 30).to(torch.int64) + 128 + ] + torch.testing.assert_close( + get_param_tensor(program, tables[0].args[1]), expected + ) + _validate_graph_signature(program) + self.assertFalse( + _fusion_pass(program, target).call(program.graph_module).modified + ) + + def test_diamond_with_minimum(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + left_values = -domain + right_values = torch.clamp(domain, -70, 70) + left = _table(program, target, source, left_values, "left_lut") + right = _table(program, target, source, right_values, "right_lut") + with program.graph.inserting_before(program.graph.output_node()): + minimum = program.graph.call_function( + exir_ops.edge.aten.minimum.default, (left, right) + ) + minimum.meta["val"] = source.meta["val"] + _set_output(program, minimum) + + result = _fusion_pass(program).call(program.graph_module) + + self.assertTrue(result.modified) + nodes = [node for node in program.graph.nodes if node.op == "call_function"] + self.assertEqual(len(nodes), 1) + torch.testing.assert_close( + get_param_tensor(program, nodes[0].args[1]), + torch.minimum(left_values, right_values), + ) + _validate_graph_signature(program) + + def test_single_input_suffix_after_multiple_input_prefix(self): + program, (left, right) = _program(two_inputs=True) + with program.graph.inserting_before(program.graph.output_node()): + minimum = program.graph.call_function( + exir_ops.edge.aten.minimum.default, (left, right) + ) + first = program.graph.call_function( + exir_ops.edge.aten.clamp.default, (minimum, -70, 70) + ) + last = program.graph.call_function( + exir_ops.edge.aten.clamp.default, (first, -20, 30) + ) + for node in (minimum, first, last): + node.meta["val"] = left.meta["val"] + _set_output(program, last) + + self.assertTrue(_fusion_pass(program).call(program.graph_module).modified) + + nodes = [node for node in program.graph.nodes if node.op == "call_function"] + self.assertEqual(nodes, [minimum, last]) + self.assertIs(last.args[0], minimum) + self.assertIs( + last.target, exir_ops.edge.test_elementwise_lut.lookup_table.default + ) + domain = torch.arange(-128, 128, dtype=torch.int8) + torch.testing.assert_close( + get_param_tensor(program, last.args[1]), torch.clamp(domain, -20, 30) + ) + _validate_graph_signature(program) + + def test_scalar_constant_is_fused_and_retired(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + table = _table(program, target, source, domain, "scalar_table") + constant = _constant(program, torch.tensor(7, dtype=torch.int8), "limit") + with program.graph.inserting_before(program.graph.output_node()): + minimum = program.graph.call_function( + exir_ops.edge.aten.minimum.default, (table, constant) + ) + minimum.meta["val"] = source.meta["val"] + _set_output(program, minimum) + + result = _fusion_pass(program).call(program.graph_module) + + self.assertTrue(result.modified) + self.assertNotIn("limit", program.state_dict) + tables = [node for node in program.graph.nodes if node.op == "call_function"] + torch.testing.assert_close( + get_param_tensor(program, tables[0].args[1]), + torch.minimum(domain, torch.tensor(7, dtype=torch.int8)), + ) + _validate_graph_signature(program) + + def test_non_scalar_constant_does_not_fuse(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + table = _table(program, target, source, domain, "ranked_table") + constant = _constant( + program, torch.tensor([7, 8], dtype=torch.int8), "ranked_limit" + ) + with program.graph.inserting_before(program.graph.output_node()): + minimum = program.graph.call_function( + exir_ops.edge.aten.minimum.default, (table, constant) + ) + minimum.meta["val"] = source.meta["val"] + _set_output(program, minimum) + + self.assertFalse(_fusion_pass(program).call(program.graph_module).modified) + + def test_mutated_buffer_is_not_treated_as_a_constant(self): + class Mutable(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("value", torch.zeros(256, dtype=torch.int8)) + + def forward(self, x): + self.value.add_(1) + return x + + program = to_edge( + export(Mutable(), (torch.arange(-128, 128, dtype=torch.int8),)) + ).exported_program() + buffer = next( + node + for node in program.graph.nodes + if node.op == "placeholder" + and node.name in program.graph_signature.inputs_to_buffers + ) + self.assertIsNone(_fusion_pass(program)._constant(buffer)) + + def test_side_user_stops_cluster_at_boundary(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + first = _table(program, target, source, domain, "side_first") + second = _table(program, target, first, torch.flip(domain, (0,)), "side_second") + third = _table(program, target, second, domain, "side_third") + program.graph.output_node().args = ((first, third),) + + result = _fusion_pass(program).call(program.graph_module) + + self.assertTrue(result.modified) + tables = [node for node in program.graph.nodes if node.op == "call_function"] + self.assertEqual(len(tables), 2) + self.assertIs(tables[-1].args[0], first) + torch.testing.assert_close( + get_param_tensor(program, tables[-1].args[1]), torch.flip(domain, (0,)) + ) + + def test_two_variable_sources_are_not_fused(self): + program, (x, y) = _program(two_inputs=True) + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + left = _table(program, target, x, domain, "two_left") + right = _table(program, target, y, domain, "two_right") + with program.graph.inserting_before(program.graph.output_node()): + minimum = program.graph.call_function( + exir_ops.edge.aten.minimum.default, (left, right) + ) + minimum.meta["val"] = x.meta["val"] + _set_output(program, minimum) + + result = _fusion_pass(program).call(program.graph_module) + + self.assertFalse(result.modified) + self.assertEqual( + len([node for node in program.graph.nodes if node.op == "call_function"]), + 3, + ) + + def test_configured_pointwise_ops_fuse_without_an_existing_table(self): + class NegateAndClamp(torch.nn.Module): + def forward(self, x): + return torch.clamp(torch.neg(x), min=-20, max=30) + + domain = torch.arange(-128, 128, dtype=torch.int8) + model = NegateAndClamp() + program = to_edge(export(model, (domain,))).exported_program() + transform = FuseElementwiseToLUTPass( + program, + exir_ops.edge.test_elementwise_lut.lookup_table.default, + {exir_ops.edge.aten.neg.default, exir_ops.edge.aten.clamp.default}, + ) + + self.assertTrue(transform.call(program.graph_module).modified) + program.validate() + torch.testing.assert_close(program.module()(domain), model(domain)) + self.assertEqual( + sum(node.op == "call_function" for node in program.graph.nodes), 1 + ) + + def test_one_element_tensor_arithmetic(self): + class ScalarArithmetic(torch.nn.Module): + def __init__(self): + super().__init__() + self.register_buffer("constant", torch.tensor([[7]], dtype=torch.int8)) + + def forward(self, x): + return (x + self.constant) * self.constant - self.constant + + domain = torch.arange(-128, 128, dtype=torch.int8).reshape(1, 256) + model = ScalarArithmetic() + program = to_edge(export(model, (domain,))).exported_program() + transform = FuseElementwiseToLUTPass( + program, + exir_ops.edge.test_elementwise_lut.lookup_table.default, + { + exir_ops.edge.aten.add.Tensor, + exir_ops.edge.aten.mul.Tensor, + exir_ops.edge.aten.sub.Tensor, + }, + ) + + self.assertTrue(transform.call(program.graph_module).modified) + program.validate() + torch.testing.assert_close(program.module()(domain), model(domain)) + self.assertNotIn("constant", program.state_dict) + + def test_unconfigured_operator_is_a_boundary(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + first = _table(program, target, source, domain, "boundary_first") + with program.graph.inserting_before(program.graph.output_node()): + bitwise_not = program.graph.call_function( + exir_ops.edge.aten.bitwise_not.default, (first,) + ) + bitwise_not.meta["val"] = source.meta["val"] + second = _table(program, target, bitwise_not, domain, "boundary_second") + _set_output(program, second) + + self.assertFalse(_fusion_pass(program).call(program.graph_module).modified) + torch.testing.assert_close(program.module()(domain), torch.bitwise_not(domain)) + self.assertEqual(len(program.state_dict), 2) + + def test_region_filter_can_reject_fusion(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + first = _table(program, target, source, domain, "filter_first") + second = _table(program, target, first, domain, "filter_second") + _set_output(program, second) + + self.assertFalse( + _fusion_pass(program, region_filter=lambda region: False) + .call(program.graph_module) + .modified + ) + self.assertEqual(len(program.state_dict), 2) + + def test_invalid_operator_signature_is_not_silently_skipped(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + with program.graph.inserting_before(program.graph.output_node()): + malformed = program.graph.call_function(target, (source,)) + malformed.meta["val"] = source.meta["val"] + _set_output(program, malformed) + + with self.assertRaises(ValueError): + _fusion_pass(program).call(program.graph_module) + + def test_kwargs_are_evaluated_in_the_lookup_table(self): + program, (source,) = _program() + target = exir_ops.edge.test_elementwise_lut.lookup_table.default + domain = torch.arange(-128, 128, dtype=torch.int8) + first = _table(program, target, source, domain, "kwargs_first") + with program.graph.inserting_before(program.graph.output_node()): + clamp = program.graph.call_function( + exir_ops.edge.aten.clamp.default, (first,), {"min": -20, "max": 30} + ) + clamp.meta["val"] = source.meta["val"] + _set_output(program, clamp) + + self.assertTrue(_fusion_pass(program).call(program.graph_module).modified) + torch.testing.assert_close( + program.module()(domain), torch.clamp(domain, -20, 30) + ) + + +if __name__ == "__main__": + unittest.main()