|
| 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 cast |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from executorch.backends.arm._passes.arm_pass import ArmPass |
| 11 | +from executorch.backends.arm._passes.arm_pass_utils import get_first_fake_tensor |
| 12 | +from executorch.backends.arm.tosa import TosaSpecification |
| 13 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 14 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 15 | +from torch.fx.experimental.symbolic_shapes import statically_known_true |
| 16 | + |
| 17 | +_EDGE_GATHER = exir_ops.edge.aten.gather.default |
| 18 | +_EDGE_CAST = exir_ops.edge.dim_order_ops._to_dim_order_copy.default |
| 19 | +_INT32_MAX = torch.iinfo(torch.int32).max |
| 20 | + |
| 21 | + |
| 22 | +def _is_compatible_gather_user(boundary: torch.fx.Node, gather: torch.fx.Node) -> bool: |
| 23 | + if gather.target != _EDGE_GATHER: |
| 24 | + return False |
| 25 | + if len(gather.args) != 3 or gather.args[2] is not boundary: |
| 26 | + return False |
| 27 | + |
| 28 | + values = get_first_fake_tensor(cast(torch.fx.Node, gather.args[0])) |
| 29 | + indices = get_first_fake_tensor(boundary) |
| 30 | + values_shape = tuple(values.shape) |
| 31 | + indices_shape = tuple(indices.shape) |
| 32 | + if len(values_shape) not in (2, 3) or len(indices_shape) not in (2, 3): |
| 33 | + return False |
| 34 | + |
| 35 | + dim = cast(int, gather.args[1]) % len(values_shape) |
| 36 | + if dim != 1 or not statically_known_true(values_shape[dim] <= _INT32_MAX): |
| 37 | + return False |
| 38 | + if not statically_known_true(values_shape[0] == indices_shape[0]): |
| 39 | + return False |
| 40 | + return len(indices_shape) == 2 or statically_known_true( |
| 41 | + values_shape[-1] == indices_shape[-1] |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +def is_safe_int32_to_int64_gather_boundary(node: torch.fx.Node) -> bool: |
| 46 | + """Return whether a cast is a removable gather compatibility boundary. |
| 47 | +
|
| 48 | + Args: |
| 49 | + node: Candidate int32-to-int64 cast node. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + True when every user is a compatible, int32-bounded gather. |
| 53 | +
|
| 54 | + """ |
| 55 | + if node.target != _EDGE_CAST: |
| 56 | + return False |
| 57 | + if node.kwargs.get("dtype") != torch.int64: |
| 58 | + return False |
| 59 | + source = node.args[0] |
| 60 | + if not isinstance(source, torch.fx.Node): |
| 61 | + return False |
| 62 | + source_tensor = get_first_fake_tensor(source) |
| 63 | + if source_tensor.dtype != torch.int32: |
| 64 | + return False |
| 65 | + if source_tensor.dim_order() != get_first_fake_tensor(node).dim_order(): |
| 66 | + return False |
| 67 | + if not node.users: |
| 68 | + return False |
| 69 | + return all(_is_compatible_gather_user(node, gather) for gather in node.users) |
| 70 | + |
| 71 | + |
| 72 | +class PrepareGatherIndicesPass(ArmPass): |
| 73 | + """Remove safe int64 compatibility boundaries from gather indices. |
| 74 | +
|
| 75 | + Portable ExecuTorch gather requires int64 indices, while TOSA gather uses |
| 76 | + int32. This pass runs during backend preprocessing, after delegation is |
| 77 | + established, and removes only an int32-to-int64 compatibility cast. It |
| 78 | + never narrows an arbitrary int64 tensor. |
| 79 | +
|
| 80 | + Args: |
| 81 | + tosa_spec: Target capabilities used to gate gather |
| 82 | + value dtypes. |
| 83 | +
|
| 84 | + """ |
| 85 | + |
| 86 | + _passes_required_after: set[type[ExportPass]] = set() |
| 87 | + |
| 88 | + _edge_gather = _EDGE_GATHER |
| 89 | + |
| 90 | + def __init__(self, tosa_spec: TosaSpecification) -> None: |
| 91 | + super().__init__() |
| 92 | + self.tosa_spec = tosa_spec |
| 93 | + |
| 94 | + def _values_dtype_supported(self, dtype: torch.dtype) -> bool: |
| 95 | + if dtype in (torch.bool, torch.int8, torch.int16, torch.int32): |
| 96 | + return self.tosa_spec.support_integer() |
| 97 | + floating_profile = ( |
| 98 | + self.tosa_spec.support_float() or self.tosa_spec.support_integer() |
| 99 | + ) |
| 100 | + if dtype == torch.bfloat16: |
| 101 | + return floating_profile and self.tosa_spec.support_extension("bf16") |
| 102 | + if dtype == torch.float8_e4m3fn: |
| 103 | + return floating_profile and self.tosa_spec.support_extension("fp8e4m3") |
| 104 | + if dtype == torch.float8_e5m2: |
| 105 | + return floating_profile and self.tosa_spec.support_extension("fp8e5m2") |
| 106 | + if dtype in (torch.float16, torch.float32): |
| 107 | + return floating_profile |
| 108 | + return False |
| 109 | + |
| 110 | + def _is_supported_gather(self, node: torch.fx.Node) -> bool: |
| 111 | + if node.target != self._edge_gather: |
| 112 | + return False |
| 113 | + if len(node.args) != 3 or not isinstance(node.args[2], torch.fx.Node): |
| 114 | + return False |
| 115 | + |
| 116 | + values = get_first_fake_tensor(cast(torch.fx.Node, node.args[0])) |
| 117 | + indices = get_first_fake_tensor(node.args[2]) |
| 118 | + if not self._values_dtype_supported(values.dtype): |
| 119 | + return False |
| 120 | + if indices.dtype != torch.int64 or not is_safe_int32_to_int64_gather_boundary( |
| 121 | + node.args[2] |
| 122 | + ): |
| 123 | + return False |
| 124 | + |
| 125 | + values_shape = tuple(values.shape) |
| 126 | + indices_shape = tuple(indices.shape) |
| 127 | + if len(values_shape) not in (2, 3): |
| 128 | + return False |
| 129 | + if len(indices_shape) not in (2, 3): |
| 130 | + return False |
| 131 | + |
| 132 | + dim = cast(int, node.args[1]) % len(values_shape) |
| 133 | + if dim != 1: |
| 134 | + return False |
| 135 | + if values_shape[0] != indices_shape[0]: |
| 136 | + return False |
| 137 | + return len(indices_shape) == 2 or values_shape[-1] == indices_shape[-1] |
| 138 | + |
| 139 | + @classmethod |
| 140 | + def _int32_input_before_boundary( |
| 141 | + cls, indices: torch.fx.Node |
| 142 | + ) -> torch.fx.Node | None: |
| 143 | + if not is_safe_int32_to_int64_gather_boundary(indices): |
| 144 | + return None |
| 145 | + return cast(torch.fx.Node, indices.args[0]) |
| 146 | + |
| 147 | + def should_run_pass(self, graph_module: torch.fx.GraphModule) -> bool: |
| 148 | + """Return whether the graph contains a removable gather boundary.""" |
| 149 | + return any( |
| 150 | + node.op == "call_function" and self._is_supported_gather(node) |
| 151 | + for node in graph_module.graph.nodes |
| 152 | + ) |
| 153 | + |
| 154 | + def call(self, graph_module: torch.fx.GraphModule): |
| 155 | + """Remove safe compatibility casts from delegated gather inputs.""" |
| 156 | + graph = graph_module.graph |
| 157 | + modified = False |
| 158 | + for gather in list(graph.nodes): |
| 159 | + if gather.op != "call_function" or not self._is_supported_gather(gather): |
| 160 | + continue |
| 161 | + |
| 162 | + indices = cast(torch.fx.Node, gather.args[2]) |
| 163 | + int32_indices = self._int32_input_before_boundary(indices) |
| 164 | + if int32_indices is None: |
| 165 | + continue |
| 166 | + |
| 167 | + gather.replace_input_with(indices, int32_indices) |
| 168 | + modified = True |
| 169 | + |
| 170 | + if modified: |
| 171 | + graph.eliminate_dead_code() |
| 172 | + graph.lint() |
| 173 | + graph_module.recompile() |
| 174 | + return PassResult(graph_module, modified) |
0 commit comments