|
| 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 | +from executorch.exir.passes import dead_code_elimination_pass |
| 12 | + |
| 13 | +from .utils import copy_meta |
| 14 | + |
| 15 | + |
| 16 | +class DecomposeFill(ExportPass): |
| 17 | + """ |
| 18 | + Decompose fill.Scalar into full.default. |
| 19 | + fill(input, value) is semantically equivalent to full(input.shape, value). |
| 20 | + """ |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + super().__init__() |
| 24 | + self.targets = { |
| 25 | + torch.ops.aten.fill.Scalar, |
| 26 | + torch.ops.aten.fill_.Scalar, |
| 27 | + exir_ops.edge.aten.fill.Scalar, |
| 28 | + exir_ops.edge.aten.fill_.Scalar, |
| 29 | + } |
| 30 | + |
| 31 | + def call(self, graph_module: torch.fx.GraphModule): |
| 32 | + graph = graph_module.graph |
| 33 | + for node in list(graph.nodes): |
| 34 | + if node.op == "call_function" and node.target in self.targets: |
| 35 | + fill_node = node |
| 36 | + is_edge = isinstance(node.target, EdgeOpOverload) |
| 37 | + input_node = node.args[0] |
| 38 | + scalar_value = node.args[1] |
| 39 | + |
| 40 | + # Get the shape from the input tensor metadata |
| 41 | + shape = list(input_node.meta["val"].shape) |
| 42 | + |
| 43 | + full_op = ( |
| 44 | + exir_ops.edge.aten.full.default |
| 45 | + if is_edge |
| 46 | + else torch.ops.aten.full.default |
| 47 | + ) |
| 48 | + |
| 49 | + with graph.inserting_after(input_node): |
| 50 | + full_node = graph.create_node( |
| 51 | + "call_function", |
| 52 | + full_op, |
| 53 | + (shape, scalar_value), |
| 54 | + ) |
| 55 | + full_node.meta = copy_meta(fill_node.meta) |
| 56 | + |
| 57 | + for user in fill_node.users.copy(): |
| 58 | + user.replace_input_with(fill_node, full_node) |
| 59 | + |
| 60 | + dead_code_elimination_pass(graph_module) |
| 61 | + return PassResult(graph_module, True) |
0 commit comments