|
| 1 | +# Copyright 2025 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 | +# pyre-unsafe |
| 7 | + |
| 8 | + |
| 9 | +import logging |
| 10 | + |
| 11 | +import torch |
| 12 | +from executorch.backends.arm._passes.arm_pass_utils import ( |
| 13 | + create_node, |
| 14 | + get_first_fake_tensor, |
| 15 | + set_node_arg, |
| 16 | +) |
| 17 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 18 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 19 | + |
| 20 | + |
| 21 | +logger = logging.getLogger(__name__) |
| 22 | + |
| 23 | + |
| 24 | +class ConvertInt64OutputOpsToInt32Pass(ExportPass): |
| 25 | + """ |
| 26 | + Rewrites or removes operations that produce int64 outputs, converting them |
| 27 | + to int32 where possible. |
| 28 | +
|
| 29 | +
|
| 30 | + Currently, this pass handles casting and argmax operators: |
| 31 | + 1. int32 -> int64: |
| 32 | + removes the cast and redirects all uses to the original int32 value. |
| 33 | + 2. other types -> int64: |
| 34 | + rewrites the cast to produce int32 instead of int64. |
| 35 | + 3. torch.argmax() |
| 36 | + insert an int64->int32 cast after the argmax node |
| 37 | +
|
| 38 | + Future extensions may include operators that return int64 outputs by default |
| 39 | + (e.g., `argmin`), rewriting them or inserting an int64 -> int32 cast to yield |
| 40 | + int32 results. |
| 41 | +
|
| 42 | + Note: Overflow checks are applied selectively in this pass. For operators without |
| 43 | + such checks, it is the user's responsibility to ensure that values fit within |
| 44 | + the int32 range. |
| 45 | + """ |
| 46 | + |
| 47 | + aten_cast_ops = ( |
| 48 | + torch.ops.aten.to.dtype, |
| 49 | + torch.ops.aten.to.dtype_layout, |
| 50 | + ) |
| 51 | + edge_cast_ops = (exir_ops.edge.dim_order_ops._to_dim_order_copy.default,) |
| 52 | + |
| 53 | + aten_argmax_ops = (torch.ops.aten.argmax.default,) |
| 54 | + edge_argmax_ops = (exir_ops.edge.aten.argmax.default,) |
| 55 | + |
| 56 | + aten_ops = aten_cast_ops + aten_argmax_ops |
| 57 | + edge_ops = edge_cast_ops + edge_argmax_ops |
| 58 | + |
| 59 | + # dtype is specified in args |
| 60 | + cast_ops_args = ( |
| 61 | + torch.ops.aten.to.dtype, # to_2: node.args: (gt, torch.int64) node.kwargs: {} |
| 62 | + ) |
| 63 | + # dtype is specified in kwargs |
| 64 | + cast_ops_kwargs = ( |
| 65 | + torch.ops.aten.to.dtype_layout, # to_1: node.args: (unsqueeze,) node.kwargs: {'dtype': torch.int64, 'layout': torch.strided, 'device': device(type='cpu')} |
| 66 | + exir_ops.edge.dim_order_ops._to_dim_order_copy.default, # node.args: (aten_gt_scalar,) node.kwargs: {'dtype': torch.int64, 'dim_order': [0, 1]} |
| 67 | + ) |
| 68 | + |
| 69 | + def _get_decomposition(self, op): |
| 70 | + if op in self.edge_ops: |
| 71 | + return exir_ops.edge.aten._to_copy.default |
| 72 | + |
| 73 | + if op in self.aten_ops: |
| 74 | + return torch.ops.aten._to_copy.default |
| 75 | + |
| 76 | + raise RuntimeError( |
| 77 | + f"[{self.__class__.__name__}] Can't get decomposition for op {op}" |
| 78 | + ) |
| 79 | + |
| 80 | + def _convert_casting_operators(self, node: torch.fx.Node): |
| 81 | + input_node = node.all_input_nodes[0] |
| 82 | + input_dtype = get_first_fake_tensor(input_node).dtype |
| 83 | + # Case 1: int32 -> int64 - removes the ops |
| 84 | + if input_dtype == torch.int32: |
| 85 | + users = [user for user in node.users if node != user] |
| 86 | + for user in users: |
| 87 | + logger.warning( |
| 88 | + f"Removing int32->int64 casting node {node.name} defined in" |
| 89 | + f" {node.meta.get('stack_trace','[no stack trace found]')}" |
| 90 | + ) |
| 91 | + user.replace_input_with(node, input_node) |
| 92 | + # Case 2: other types -> int64 - rewrites to cast to int32 |
| 93 | + else: |
| 94 | + if node.target in self.cast_ops_kwargs: |
| 95 | + set_node_arg(node, "dtype", torch.int32) |
| 96 | + elif node.target in self.cast_ops_args: |
| 97 | + set_node_arg(node, 1, torch.int32) |
| 98 | + else: |
| 99 | + raise RuntimeError(f"Unexpected target {node.target} in {node.name}") |
| 100 | + output_dtype = get_first_fake_tensor(node).dtype |
| 101 | + logger.warning( |
| 102 | + f"Converting casting node {node.name} from {input_dtype}->{output_dtype} to" |
| 103 | + f" {input_dtype}->torch.int32 defined in {node.meta.get('stack_trace','[no stack trace found]')}" |
| 104 | + ) |
| 105 | + |
| 106 | + def _convert_argmax_operators(self, node: torch.fx.Node, graph: torch.fx.Graph): |
| 107 | + output_tensor = node |
| 108 | + to_copy_op = self._get_decomposition(node.target) |
| 109 | + with graph.inserting_after(node): |
| 110 | + cast_after = create_node( |
| 111 | + graph, |
| 112 | + to_copy_op, |
| 113 | + args=(output_tensor,), |
| 114 | + kwargs={ |
| 115 | + "dtype": torch.int32, |
| 116 | + }, |
| 117 | + ) |
| 118 | + users = [user for user in node.users if user != cast_after] |
| 119 | + for user in users: |
| 120 | + user.replace_input_with(output_tensor, cast_after) |
| 121 | + logger.warning( |
| 122 | + f"Inserting a casting node {cast_after.name} after {node.name} to cast int64 output" |
| 123 | + f" to int32 for {node.name} defined in {node.meta.get('stack_trace','[no stack trace found]')}" |
| 124 | + ) |
| 125 | + |
| 126 | + def call(self, graph_module: torch.fx.GraphModule): |
| 127 | + modified = False |
| 128 | + graph = graph_module.graph |
| 129 | + for node in list(graph.nodes): |
| 130 | + if node.op != "call_function": |
| 131 | + continue |
| 132 | + if node.target not in self.aten_ops + self.edge_ops: |
| 133 | + continue |
| 134 | + output_dtype = get_first_fake_tensor(node).dtype |
| 135 | + if output_dtype != torch.int64: |
| 136 | + continue |
| 137 | + |
| 138 | + if node.target in self.aten_cast_ops + self.edge_cast_ops: |
| 139 | + self._convert_casting_operators(node) |
| 140 | + elif node.target in self.aten_argmax_ops + self.edge_argmax_ops: |
| 141 | + # TODO: Add range check based on the input tensor shape before casting the output |
| 142 | + self._convert_argmax_operators(node, graph) |
| 143 | + else: |
| 144 | + raise RuntimeError(f"Unexpected target {node.target} in {node.name}") |
| 145 | + |
| 146 | + modified = True |
| 147 | + |
| 148 | + if modified: |
| 149 | + graph_module.graph.eliminate_dead_code() |
| 150 | + graph_module.recompile() |
| 151 | + graph_module = super().call(graph_module).graph_module |
| 152 | + |
| 153 | + return PassResult(graph_module, modified) |
0 commit comments