|
| 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 | + |
| 7 | +from typing import Sequence, Set, Tuple, Type |
| 8 | + |
| 9 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 10 | +from executorch.exir.pass_base import ExportPass |
| 11 | + |
| 12 | +from torch._ops import OpOverload |
| 13 | + |
| 14 | + |
| 15 | +_PERMUTE_TARGETS: Tuple[OpOverload, ...] = ( |
| 16 | + exir_ops.edge.aten.permute.default, |
| 17 | + exir_ops.edge.aten.permute_copy.default, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +class ConvertPermuteSingletonToViewPass(ExportPass): |
| 22 | + """Replace permutations that only move singleton axes with a reshape. |
| 23 | +
|
| 24 | + Examples: |
| 25 | + x = rand(1,1,1,4) |
| 26 | + y = permute(x, (0,3,1,2)) |
| 27 | +
|
| 28 | + becomes: |
| 29 | + x = rand(1,1,1,4) |
| 30 | + y = view_copy(x, (1,4,1,1)) |
| 31 | + """ |
| 32 | + |
| 33 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 34 | + |
| 35 | + def call_operator(self, op, args, kwargs, meta): |
| 36 | + if op not in _PERMUTE_TARGETS: |
| 37 | + return super().call_operator(op, args, kwargs, meta) |
| 38 | + |
| 39 | + input_tensor = args[0].data |
| 40 | + permutation = args[1] |
| 41 | + if not is_singleton_permutation(input_tensor.shape, permutation): |
| 42 | + return super().call_operator(op, args, kwargs, meta) |
| 43 | + |
| 44 | + output_shape = meta["val"].shape |
| 45 | + view_args = (args[0], output_shape) |
| 46 | + return super().call_operator( |
| 47 | + exir_ops.edge.aten.view_copy.default, view_args, kwargs, meta |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +def is_singleton_permutation(shape: Sequence[int], permutation: Sequence[int]) -> bool: |
| 52 | + """ |
| 53 | + Treat as a view only when non-singleton axes keep their order; singleton |
| 54 | + axes may move freely since they carry no data volume. |
| 55 | + """ |
| 56 | + rank = len(shape) |
| 57 | + normalized_perm = [d % rank for d in permutation] |
| 58 | + |
| 59 | + non_singleton_axes = [i for i, size in enumerate(shape) if size != 1] |
| 60 | + permuted_non_singleton_axes = [axis for axis in normalized_perm if shape[axis] != 1] |
| 61 | + |
| 62 | + return permuted_non_singleton_axes == non_singleton_axes |
0 commit comments