|
| 1 | +# Copyright 2026 Arm Limited and/or its affiliates. |
| 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 Any, Set, Type |
| 7 | + |
| 8 | +import torch |
| 9 | +from executorch.backends.arm._passes import ArmPass |
| 10 | +from executorch.backends.arm._passes.arm_pass_utils import ( |
| 11 | + create_node, |
| 12 | + get_first_fake_tensor, |
| 13 | + is_param_node, |
| 14 | +) |
| 15 | +from executorch.exir import ExportedProgram |
| 16 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 17 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 18 | + |
| 19 | + |
| 20 | +class NormalizeDelegateIOLayoutPass(ArmPass): |
| 21 | + """Adjust delegated boundary tensor shapes and insert permutes at I/O.""" |
| 22 | + |
| 23 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 24 | + |
| 25 | + def __init__(self, exported_program: ExportedProgram, *args, **kwargs) -> None: |
| 26 | + super().__init__(*args, **kwargs) |
| 27 | + self.exported_program = exported_program |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def _inverse_permutation(perm: tuple[int, ...]) -> tuple[int, ...]: |
| 31 | + inverse = [0] * len(perm) |
| 32 | + for idx, axis in enumerate(perm): |
| 33 | + inverse[axis] = idx |
| 34 | + return tuple(inverse) |
| 35 | + |
| 36 | + @staticmethod |
| 37 | + def _permute_shape(shape: torch.Size, perm: tuple[int, ...]) -> tuple[int, ...]: |
| 38 | + return tuple(shape[axis] for axis in perm) |
| 39 | + |
| 40 | + @staticmethod |
| 41 | + def _is_identity_dim_order(dim_order: tuple[int, ...]) -> bool: |
| 42 | + return dim_order == tuple(range(len(dim_order))) |
| 43 | + |
| 44 | + def _normalize_input_layout(self, graph_module: torch.fx.GraphModule) -> bool: |
| 45 | + modified = False |
| 46 | + for node in graph_module.graph.nodes: |
| 47 | + if node.op != "placeholder" or is_param_node(self.exported_program, node): |
| 48 | + continue |
| 49 | + |
| 50 | + input_fake = get_first_fake_tensor(node) |
| 51 | + dim_order = input_fake.dim_order() |
| 52 | + if self._is_identity_dim_order(dim_order): |
| 53 | + continue |
| 54 | + |
| 55 | + boundary_shape = self._permute_shape(input_fake.shape, dim_order) |
| 56 | + node.meta["val"] = input_fake.reshape(boundary_shape) |
| 57 | + |
| 58 | + transpose_perm = self._inverse_permutation(dim_order) |
| 59 | + with graph_module.graph.inserting_after(node): |
| 60 | + permute_node = create_node( |
| 61 | + graph_module.graph, |
| 62 | + exir_ops.edge.aten.permute_copy.default, |
| 63 | + args=(node, list(transpose_perm)), |
| 64 | + from_node=node, |
| 65 | + ) |
| 66 | + permute_node.meta["val"] = exir_ops.edge.aten.permute_copy.default( |
| 67 | + node.meta["val"], list(transpose_perm) |
| 68 | + ) |
| 69 | + |
| 70 | + users = [user for user in node.users if user != permute_node] |
| 71 | + for user in users: |
| 72 | + user.replace_input_with(node, permute_node) |
| 73 | + |
| 74 | + modified = True |
| 75 | + |
| 76 | + return modified |
| 77 | + |
| 78 | + def _rewrite_output_arg( |
| 79 | + self, arg: Any, graph_module: torch.fx.GraphModule |
| 80 | + ) -> tuple[Any, bool]: |
| 81 | + if isinstance(arg, torch.fx.Node): |
| 82 | + output_fake = get_first_fake_tensor(arg) |
| 83 | + dim_order = output_fake.dim_order() |
| 84 | + if self._is_identity_dim_order(dim_order): |
| 85 | + return arg, False |
| 86 | + |
| 87 | + with graph_module.graph.inserting_after(arg): |
| 88 | + permute_node = create_node( |
| 89 | + graph_module.graph, |
| 90 | + exir_ops.edge.aten.permute_copy.default, |
| 91 | + args=(arg, list(dim_order)), |
| 92 | + from_node=arg, |
| 93 | + ) |
| 94 | + permute_node.meta["val"] = exir_ops.edge.aten.permute_copy.default( |
| 95 | + output_fake, list(dim_order) |
| 96 | + ) |
| 97 | + |
| 98 | + return permute_node, True |
| 99 | + |
| 100 | + if isinstance(arg, tuple): |
| 101 | + modified = False |
| 102 | + rewritten = [] |
| 103 | + for item in arg: |
| 104 | + new_item, item_modified = self._rewrite_output_arg(item, graph_module) |
| 105 | + rewritten.append(new_item) |
| 106 | + modified = modified or item_modified |
| 107 | + return tuple(rewritten), modified |
| 108 | + |
| 109 | + if isinstance(arg, list): |
| 110 | + modified = False |
| 111 | + rewritten = [] |
| 112 | + for item in arg: |
| 113 | + new_item, item_modified = self._rewrite_output_arg(item, graph_module) |
| 114 | + rewritten.append(new_item) |
| 115 | + modified = modified or item_modified |
| 116 | + return rewritten, modified |
| 117 | + |
| 118 | + return arg, False |
| 119 | + |
| 120 | + def _normalize_output_layout(self, graph_module: torch.fx.GraphModule) -> bool: |
| 121 | + output_node = graph_module.graph.output_node() |
| 122 | + rewritten_outputs, modified = self._rewrite_output_arg( |
| 123 | + output_node.args[0], graph_module |
| 124 | + ) |
| 125 | + if modified: |
| 126 | + output_node.args = (rewritten_outputs,) |
| 127 | + return modified |
| 128 | + |
| 129 | + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: |
| 130 | + modified = self._normalize_input_layout(graph_module) |
| 131 | + modified = self._normalize_output_layout(graph_module) or modified |
| 132 | + |
| 133 | + if modified: |
| 134 | + graph_module.recompile() |
| 135 | + graph_module = super().call(graph_module).graph_module |
| 136 | + |
| 137 | + return PassResult(graph_module, modified) |
0 commit comments