|
| 1 | +# Copyright 2025 NXP |
| 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 typing import Collection |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from executorch.backends.nxp.backend.edge_helper import ( |
| 11 | + try_get_tensor_constant_from_node, |
| 12 | +) |
| 13 | +from torch._subclasses import FakeTensor, FakeTensorMode |
| 14 | +from torch.ao.quantization.fx.utils import get_new_attr_name_with_prefix |
| 15 | +from torch.export.unflatten import _assign_attr, _AttrKind |
| 16 | +from torch.fx import GraphModule, Node |
| 17 | +from torch.fx.passes.infra.pass_base import PassBase, PassResult |
| 18 | +from torch.nn import Parameter |
| 19 | + |
| 20 | + |
| 21 | +class RemoveNodesWithKnownOutputs(PassBase): |
| 22 | + """In some situations, a node will always produce the same output data at runtime. If these cases are identified, |
| 23 | + the nodes can simply be removed and replaced by a static parameter node, which holds the data the original |
| 24 | + node would produce. |
| 25 | + This pass identifies some of these cases and performs the replacement. |
| 26 | + """ |
| 27 | + |
| 28 | + # Nodes which don't have the `.meta['val']` attribute. The datatype and shape of their inferred output data will |
| 29 | + # therefore not be checked against the expected values in the `.meta['val']`. |
| 30 | + nodes_without_val_meta = [ |
| 31 | + torch.ops.aten.empty.memory_format, |
| 32 | + ] |
| 33 | + |
| 34 | + module: GraphModule |
| 35 | + |
| 36 | + def replace_nodes_in_list_with_their_data(self, list_of_args: list) -> list | None: |
| 37 | + """Replace the nodes in `list_of_args` by their static data. If not all data is available, return `None`. |
| 38 | +
|
| 39 | + :param list_of_args: List of arguments of an aten operator. Can include nodes, generic arguments, lists... |
| 40 | + :return:`list_of_args` but with tensors replaced by their static data, or `None` if not all data is available. |
| 41 | + """ |
| 42 | + args_with_data = [] |
| 43 | + for arg in list_of_args: |
| 44 | + match arg: |
| 45 | + case Node(): |
| 46 | + # `arg` is either another operator, a model input, or a static parameter. |
| 47 | + data = try_get_tensor_constant_from_node(self.module, arg) |
| 48 | + if data is None: |
| 49 | + # No static data is available. |
| 50 | + return None |
| 51 | + |
| 52 | + args_with_data.append(data) |
| 53 | + case list(): |
| 54 | + nested = self.replace_nodes_in_list_with_their_data(arg) |
| 55 | + if nested is None: |
| 56 | + return None |
| 57 | + args_with_data.append(nested) |
| 58 | + |
| 59 | + case _: |
| 60 | + # Generic argument. Not an input from a previous node. |
| 61 | + args_with_data.append(arg) |
| 62 | + |
| 63 | + return args_with_data |
| 64 | + |
| 65 | + @staticmethod |
| 66 | + def node_is_followed_only_by_getitem_nodes(node: Node) -> bool: |
| 67 | + def _is_getitem(node_: Node) -> bool: |
| 68 | + return node_.op == "call_function" and node_.target.__name__ == "getitem" |
| 69 | + |
| 70 | + users = list(node.users.keys()) |
| 71 | + return all(_is_getitem(user) for user in users) |
| 72 | + |
| 73 | + def replace_node_with_static_data(self, node: Node, static_data: Parameter): |
| 74 | + """Remove the given `node` from the graph and replace it with a parameter node containing the `static_data`.""" |
| 75 | + # Generate a unique name for the new static parameter. |
| 76 | + new_name = get_new_attr_name_with_prefix(node.name)(self.module) |
| 77 | + |
| 78 | + # Create the node for the parameter. |
| 79 | + param = torch.nn.Parameter(static_data, False) |
| 80 | + _assign_attr(param, self.module, str(new_name), _AttrKind.PARAMETER) |
| 81 | + with self.module.graph.inserting_before(node): |
| 82 | + static_parameter_node = self.module.graph.get_attr(new_name) |
| 83 | + |
| 84 | + with FakeTensorMode() as mode: |
| 85 | + # Assign the parameter node its shape and data type. |
| 86 | + static_parameter_node.meta["val"] = FakeTensor.from_tensor( |
| 87 | + torch.empty(static_data.shape, dtype=static_data.dtype), mode |
| 88 | + ) |
| 89 | + |
| 90 | + # Replace the old node with the new static parameter. |
| 91 | + node.replace_all_uses_with(static_parameter_node) |
| 92 | + self.module.graph.erase_node(node) |
| 93 | + |
| 94 | + def replace_following_getitem_nodes_with_static_data( |
| 95 | + self, root_node: Node, static_data: Collection[Parameter] |
| 96 | + ) -> bool: |
| 97 | + """Remove the `root_node` and all `GetItem` nodes that consume its output from the graph, and replace their |
| 98 | + uses with parameter nodes containing the provided `static_data`. |
| 99 | + If something other than just `GetItem` nodes follow after the `root_node`, nothing is done and `False` is |
| 100 | + returned. |
| 101 | +
|
| 102 | + :param root_node: The main compute node which is followed only by `GetItem` nodes. |
| 103 | + :param static_data: A tuple of static tensors with the data that will be used to replace the `GetItem` nodes |
| 104 | + after the `root_node`. |
| 105 | + :return: `True` if the replacement was successfully executed. `False` otherwise. |
| 106 | + """ |
| 107 | + |
| 108 | + if not self.node_is_followed_only_by_getitem_nodes(root_node): |
| 109 | + return False # Unexpected case. |
| 110 | + |
| 111 | + users = list(root_node.users.keys()) |
| 112 | + if len(users) != len(static_data): |
| 113 | + return False # Unexpected missmatch. |
| 114 | + |
| 115 | + # Replace the individual `GetItem` nodes. |
| 116 | + for get_item_node in users: |
| 117 | + idx = get_item_node.args[1] |
| 118 | + self.replace_node_with_static_data(get_item_node, static_data[idx]) |
| 119 | + |
| 120 | + # Finally remove the root node from the graph. |
| 121 | + self.module.graph.erase_node(root_node) |
| 122 | + |
| 123 | + return True |
| 124 | + |
| 125 | + def data_matches_node_meta(self, node: Node, data: Parameter) -> bool: |
| 126 | + """Verify that the provided `data` tensor has the same shape and datatype as the `node`.""" |
| 127 | + if node.target not in self.nodes_without_val_meta: |
| 128 | + if node.meta["val"].shape != data.shape: |
| 129 | + return False # The inferred data has a different shape than expected. |
| 130 | + |
| 131 | + if node.meta["val"].dtype != data.dtype: |
| 132 | + return ( |
| 133 | + False # The inferred data has a different data type than expected. |
| 134 | + ) |
| 135 | + |
| 136 | + return True |
| 137 | + |
| 138 | + def data_matches_meta_of_following_getitem_nodes( |
| 139 | + self, root_node: Node, data: Collection[Parameter] |
| 140 | + ) -> bool: |
| 141 | + """Verify that the provided `data` tensor has the same shape and datatype as the `GetItem` nodes which consume |
| 142 | + the output of the `root_node`. |
| 143 | + """ |
| 144 | + if not self.node_is_followed_only_by_getitem_nodes(root_node): |
| 145 | + return False # Unexpected case |
| 146 | + |
| 147 | + users = list(root_node.users.keys()) |
| 148 | + return all( |
| 149 | + self.data_matches_node_meta(get_item, data[get_item.args[1]]) |
| 150 | + for get_item in users |
| 151 | + ) |
| 152 | + |
| 153 | + def call(self, module: GraphModule) -> bool: |
| 154 | + self.module = module |
| 155 | + made_changes = False |
| 156 | + |
| 157 | + for node in module.graph.nodes: |
| 158 | + if node.op != "call_function": |
| 159 | + continue # Not a compute operator. |
| 160 | + |
| 161 | + # Try to access the static data for the inputs of the node. |
| 162 | + args_with_data = self.replace_nodes_in_list_with_their_data(node.args) |
| 163 | + |
| 164 | + if args_with_data is None: |
| 165 | + # Output data inference is not possible. |
| 166 | + continue |
| 167 | + |
| 168 | + # All input data is static. Run the operator to compute the input it would produce at runtime. |
| 169 | + # noinspection PyBroadException |
| 170 | + try: |
| 171 | + output = node.target(*args_with_data, **node.kwargs) |
| 172 | + |
| 173 | + if isinstance(output, tuple) or isinstance(output, list): |
| 174 | + if not self.data_matches_meta_of_following_getitem_nodes( |
| 175 | + node, output |
| 176 | + ): |
| 177 | + continue # The inferred data does not have the expected type/shape. |
| 178 | + else: |
| 179 | + if not self.data_matches_node_meta(node, output): |
| 180 | + continue # The inferred data does not have the expected type/shape. |
| 181 | + |
| 182 | + except Exception: |
| 183 | + continue # Failed to infer the data. Continue with the other nodes. |
| 184 | + # The output data appears to have been correctly inferred. Create a static parameter node for it. |
| 185 | + |
| 186 | + if isinstance(output, tuple) or isinstance(output, list): |
| 187 | + # The node produces multiple outputs (e.g. `split`). If the node is followed only by `GetItem` nodes |
| 188 | + # which extract the individual outputs, replace them by the static data. |
| 189 | + if self.replace_following_getitem_nodes_with_static_data(node, output): |
| 190 | + made_changes = True |
| 191 | + |
| 192 | + else: |
| 193 | + self.replace_node_with_static_data(node, output) |
| 194 | + made_changes = True # Indicate that changes were made. |
| 195 | + |
| 196 | + return PassResult(module, made_changes) |
0 commit comments