|
| 1 | +# Copyright (c) Qualcomm Innovation Center, Inc. |
| 2 | +# All rights reserved |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | +import torch |
| 7 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 8 | + |
| 9 | +from .utils import copy_meta |
| 10 | + |
| 11 | + |
| 12 | +class ConvertSquareToPow(ExportPass): |
| 13 | + """ |
| 14 | + Convert square to pow with a scalar value of 2. |
| 15 | + This allows LiftConstantScalarOperands to lift the scalar into a scalar. |
| 16 | + Otherwise, the square op will be converted to pow.tensor_scalar after to_edge. |
| 17 | + """ |
| 18 | + |
| 19 | + def __init__(self) -> None: |
| 20 | + super().__init__() |
| 21 | + |
| 22 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 23 | + graph = graph_module.graph |
| 24 | + for node in graph.nodes: |
| 25 | + if node.target == torch.ops.aten.square.default: |
| 26 | + input_node = node.args[0] |
| 27 | + with graph_module.graph.inserting_after(input_node): |
| 28 | + pow_op = torch.ops.aten.pow.Tensor_Scalar |
| 29 | + pow_node = graph.create_node( |
| 30 | + "call_function", pow_op, (input_node, 2) |
| 31 | + ) |
| 32 | + pow_node.meta = copy_meta(node.meta) |
| 33 | + for user in node.users.copy(): |
| 34 | + user.replace_input_with(node, pow_node) |
| 35 | + |
| 36 | + graph.eliminate_dead_code() |
| 37 | + graph_module.recompile() |
| 38 | + return PassResult(graph_module, True) |
0 commit comments