|
| 1 | +# Copyright 2026 Arm Limited and/or its affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the BSD-style license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from numbers import Number |
| 9 | +from typing import Dict, Optional, Union |
| 10 | + |
| 11 | +import torch |
| 12 | +from executorch.backends.transforms.utils import create_constant_placeholder |
| 13 | +from executorch.backends.xnnpack._passes.xnnpack_pass import XNNPACKPass |
| 14 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 15 | +from executorch.exir.dialects.edge._ops import EdgeOpOverload |
| 16 | +from executorch.exir.pass_base import PassResult |
| 17 | +from torch._ops import OpOverload |
| 18 | +from torch.export import ExportedProgram |
| 19 | +from torch.export.graph_signature import InputKind |
| 20 | + |
| 21 | +ScalarOp = Union[EdgeOpOverload, OpOverload] |
| 22 | + |
| 23 | + |
| 24 | +class LiftConstantScalarOperandsPass(XNNPACKPass): |
| 25 | + """ |
| 26 | + Lift scalar operands into tensor constants for selected binary ops. |
| 27 | +
|
| 28 | + XNNPACK already supports the tensor overloads for these binary operations. |
| 29 | + This pass converts explicitly listed scalar overloads to their tensor |
| 30 | + overloads by replacing constant scalar operands with small tensor constants. |
| 31 | + The constants are registered as exported-program constant tensor inputs. |
| 32 | + Keep the op map narrow until each new scalar overload is covered by tests. |
| 33 | + """ |
| 34 | + |
| 35 | + default_scalar_to_tensor_ops: Dict[ScalarOp, ScalarOp] = { |
| 36 | + exir_ops.edge.aten.mul.Scalar: exir_ops.edge.aten.mul.Tensor, |
| 37 | + } |
| 38 | + |
| 39 | + def __init__( |
| 40 | + self, |
| 41 | + exported_program: ExportedProgram, |
| 42 | + scalar_to_tensor_ops: Optional[Dict[ScalarOp, ScalarOp]] = None, |
| 43 | + ) -> None: |
| 44 | + super().__init__(exported_program) |
| 45 | + self.scalar_to_tensor_ops = ( |
| 46 | + scalar_to_tensor_ops |
| 47 | + if scalar_to_tensor_ops is not None |
| 48 | + else self.default_scalar_to_tensor_ops |
| 49 | + ) |
| 50 | + |
| 51 | + def _create_constant_node( |
| 52 | + self, |
| 53 | + graph_module: torch.fx.GraphModule, |
| 54 | + node: torch.fx.Node, |
| 55 | + value: Number, |
| 56 | + ) -> torch.fx.Node: |
| 57 | + input_node = node.args[0] |
| 58 | + if not isinstance(input_node, torch.fx.Node): |
| 59 | + raise RuntimeError("Expected scalar op input to be an FX node.") |
| 60 | + |
| 61 | + input_value = input_node.meta["val"] |
| 62 | + tensor = torch.tensor(value, dtype=input_value.dtype, device=input_value.device) |
| 63 | + name = self._get_new_constant_name(graph_module) |
| 64 | + first_placeholder = next( |
| 65 | + graph_node |
| 66 | + for graph_node in graph_module.graph.nodes |
| 67 | + if graph_node.op == "placeholder" |
| 68 | + ) |
| 69 | + with graph_module.graph.inserting_before(first_placeholder): |
| 70 | + return create_constant_placeholder( |
| 71 | + self.exported_program, |
| 72 | + graph_module.graph, |
| 73 | + name, |
| 74 | + InputKind.CONSTANT_TENSOR, |
| 75 | + tensor, |
| 76 | + ) |
| 77 | + |
| 78 | + def _get_new_constant_name(self, graph_module: torch.fx.GraphModule) -> str: |
| 79 | + prefix = "_tensor_constant_" |
| 80 | + existing_names = {node.name for node in graph_module.graph.nodes} |
| 81 | + existing_names.update(self.exported_program.constants) |
| 82 | + existing_names.update(self.exported_program.state_dict) |
| 83 | + index = 0 |
| 84 | + while f"{prefix}{index}" in existing_names: |
| 85 | + index += 1 |
| 86 | + return f"{prefix}{index}" |
| 87 | + |
| 88 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 89 | + modified = False |
| 90 | + |
| 91 | + for node in list(graph_module.graph.nodes): |
| 92 | + if ( |
| 93 | + node.op != "call_function" |
| 94 | + or node.target not in self.scalar_to_tensor_ops |
| 95 | + or len(node.args) != 2 |
| 96 | + or not isinstance(node.args[0], torch.fx.Node) |
| 97 | + or not isinstance(node.args[1], Number) |
| 98 | + ): |
| 99 | + continue |
| 100 | + |
| 101 | + input_value = node.args[0].meta.get("val") |
| 102 | + output_value = node.meta.get("val") |
| 103 | + if ( |
| 104 | + not isinstance(input_value, torch.Tensor) |
| 105 | + or not isinstance(output_value, torch.Tensor) |
| 106 | + or input_value.dtype != output_value.dtype |
| 107 | + ): |
| 108 | + continue |
| 109 | + |
| 110 | + tensor_arg = self._create_constant_node(graph_module, node, node.args[1]) |
| 111 | + node.args = (node.args[0], tensor_arg) |
| 112 | + node.target = self.scalar_to_tensor_ops[node.target] |
| 113 | + modified = True |
| 114 | + |
| 115 | + graph_module.graph.eliminate_dead_code() |
| 116 | + graph_module.graph.lint() |
| 117 | + graph_module.recompile() |
| 118 | + |
| 119 | + return PassResult(graph_module, modified) |
0 commit comments