|
| 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 | +from typing import Set, Type |
| 6 | + |
| 7 | +from executorch.backends.arm._passes import ArmPass |
| 8 | + |
| 9 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 10 | +from executorch.exir.pass_base import ExportPass, ProxyValue |
| 11 | + |
| 12 | +from torch import SymInt |
| 13 | + |
| 14 | + |
| 15 | +class RewriteSlicePass(ArmPass): |
| 16 | + """Rewrite slice operations with step of 1 to TOSA slice operators.""" |
| 17 | + |
| 18 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 19 | + |
| 20 | + def _fixup_start(self, start, input_shape, dim) -> int: |
| 21 | + """Convert negative and out-of-bounds start indices to valid positive |
| 22 | + indices. |
| 23 | + """ |
| 24 | + idx = start or 0 |
| 25 | + if idx < 0: |
| 26 | + idx = start % input_shape[dim] |
| 27 | + if idx >= input_shape[dim]: |
| 28 | + idx = input_shape[dim] - 1 |
| 29 | + return idx |
| 30 | + |
| 31 | + def call_operator(self, op, args, kwargs, meta, updated=False) -> ProxyValue: |
| 32 | + if op not in (exir_ops.edge.aten.slice_copy.Tensor,): |
| 33 | + return super().call_operator(op, args, kwargs, meta, updated) |
| 34 | + |
| 35 | + if len(args) == 5 and args[4] != 1: |
| 36 | + raise ValueError( |
| 37 | + f"Only slice with 4 arguments and step of 1 is supported, got {len(args)} arguments and step {args[4]}" |
| 38 | + ) |
| 39 | + input, dim, start, end = args[:4] |
| 40 | + input_shape = input.data.shape |
| 41 | + start_index = self._fixup_start(start, input_shape, dim) |
| 42 | + |
| 43 | + start_list = [0] * len(input_shape) |
| 44 | + start_list[dim] = start_index |
| 45 | + size_list = list(meta.data["val"].shape) |
| 46 | + |
| 47 | + if any(isinstance(dim, SymInt) for dim in start_list): |
| 48 | + starts = start_list |
| 49 | + else: |
| 50 | + starts = super().call_shape_operator( # type: ignore[assignment] |
| 51 | + exir_ops.backend.tosa.CONST_SHAPE.default, |
| 52 | + (start_list,), |
| 53 | + {}, |
| 54 | + meta, |
| 55 | + True, |
| 56 | + ) |
| 57 | + if any(isinstance(dim, SymInt) for dim in size_list): |
| 58 | + sizes = size_list |
| 59 | + else: |
| 60 | + sizes = super().call_shape_operator( # type: ignore[assignment] |
| 61 | + exir_ops.backend.tosa.CONST_SHAPE.default, |
| 62 | + (size_list,), |
| 63 | + {}, |
| 64 | + meta, |
| 65 | + True, |
| 66 | + ) |
| 67 | + |
| 68 | + return super().call_operator( |
| 69 | + exir_ops.backend.tosa.SLICE.default, |
| 70 | + (input, starts, sizes), |
| 71 | + kwargs, |
| 72 | + meta, |
| 73 | + updated=True, |
| 74 | + ) |
0 commit comments