|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 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 | +# pyre-strict |
| 8 | + |
| 9 | +import torch |
| 10 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 11 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 12 | + |
| 13 | + |
| 14 | +def remove_local_scalar_dense_ops(graph: torch.fx.Graph) -> torch.fx.Graph: |
| 15 | + """ |
| 16 | + Remove local_scalar_dense op nodes and replace uses with parent node, or the |
| 17 | + original scalar tensor. |
| 18 | + """ |
| 19 | + target_op = torch.ops.aten._local_scalar_dense.default |
| 20 | + for node in graph.nodes: |
| 21 | + if node.op == "call_function" and node.target == target_op: |
| 22 | + replace_node = node.args[0] |
| 23 | + # If the argument to the local_scalar_dense op is a select op with only |
| 24 | + # one user, and the argument to the select op is a tensor with only one |
| 25 | + # element (i.e. a scalar tensor), then replace the entire pattern with the |
| 26 | + # scalar tensor. |
| 27 | + if ( |
| 28 | + replace_node.op == "call_function" |
| 29 | + and replace_node.target == exir_ops.edge.aten.select_copy.int |
| 30 | + ): |
| 31 | + if replace_node.args[0].meta["val"].numel() == 1: |
| 32 | + replace_node = replace_node.args[0] |
| 33 | + |
| 34 | + with graph.inserting_after(node): |
| 35 | + node.replace_all_uses_with(replace_node) |
| 36 | + |
| 37 | + graph.eliminate_dead_code() |
| 38 | + return graph |
| 39 | + |
| 40 | + |
| 41 | +class RemoveLocalScalarDenseOpsTransform(ExportPass): |
| 42 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 43 | + graph_module.graph = remove_local_scalar_dense_ops(graph_module.graph) |
| 44 | + return PassResult(graph_module, True) |
0 commit comments