|
| 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 | + |
| 7 | +import torch |
| 8 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 9 | +from executorch.exir.dialects.edge._ops import EdgeOpOverload |
| 10 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 11 | + |
| 12 | +from .utils import copy_meta |
| 13 | + |
| 14 | + |
| 15 | +class DecomposeTan(ExportPass): |
| 16 | + """ |
| 17 | + Decompose tan(x) = sin(x) / cos(x) |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self): |
| 21 | + super(DecomposeTan, self).__init__() |
| 22 | + self.targets = { |
| 23 | + torch.ops.aten.tan.default, |
| 24 | + exir_ops.edge.aten.tan.default, |
| 25 | + } |
| 26 | + |
| 27 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 28 | + graph = graph_module.graph |
| 29 | + |
| 30 | + for node in list(graph.nodes): |
| 31 | + if node.op == "call_function" and node.target in self.targets: |
| 32 | + is_edge = isinstance(node.target, EdgeOpOverload) |
| 33 | + |
| 34 | + sin_op = ( |
| 35 | + exir_ops.edge.aten.sin.default |
| 36 | + if is_edge |
| 37 | + else torch.ops.aten.sin.default |
| 38 | + ) |
| 39 | + cos_op = ( |
| 40 | + exir_ops.edge.aten.cos.default |
| 41 | + if is_edge |
| 42 | + else torch.ops.aten.cos.default |
| 43 | + ) |
| 44 | + div_op = ( |
| 45 | + exir_ops.edge.aten.div.Tensor |
| 46 | + if is_edge |
| 47 | + else torch.ops.aten.div.Tensor |
| 48 | + ) |
| 49 | + |
| 50 | + with graph.inserting_before(node): |
| 51 | + sin_node = graph.create_node( |
| 52 | + "call_function", sin_op, (node.args[0],) |
| 53 | + ) |
| 54 | + sin_node.meta = copy_meta(node.meta) |
| 55 | + |
| 56 | + cos_node = graph.create_node( |
| 57 | + "call_function", cos_op, (node.args[0],) |
| 58 | + ) |
| 59 | + cos_node.meta = copy_meta(node.meta) |
| 60 | + |
| 61 | + div_node = graph.create_node( |
| 62 | + "call_function", div_op, (sin_node, cos_node) |
| 63 | + ) |
| 64 | + div_node.meta = copy_meta(node.meta) |
| 65 | + |
| 66 | + for user in node.users.copy(): |
| 67 | + user.replace_input_with(node, div_node) |
| 68 | + |
| 69 | + graph.eliminate_dead_code() |
| 70 | + graph_module.recompile() |
| 71 | + return PassResult(graph_module, True) |
0 commit comments