|
| 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, Optional |
| 7 | + |
| 8 | +from executorch.backends.arm._passes import ArmPass |
| 9 | +from executorch.backends.arm.tosa.dialect.shape import meta_has_shape_mark |
| 10 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 11 | + |
| 12 | + |
| 13 | +class InsertConstShapesPass(ArmPass): |
| 14 | + """Materialize literal shape arguments as CONST_SHAPE nodes. |
| 15 | +
|
| 16 | + This pass targets ops such as `aten.view_copy` and `aten.repeat` whose shape |
| 17 | + arguments might otherwise remain raw Python lists/tuples. Replacing them |
| 18 | + with explicit CONST_SHAPE nodes simplifies the serialization of these ops |
| 19 | + the serialization of their arguments is handled by the CONST_SHAPE node visitor. |
| 20 | +
|
| 21 | + """ |
| 22 | + |
| 23 | + _passes_required_after = set() |
| 24 | + targeted_ops = { |
| 25 | + exir_ops.edge.aten.view_copy.default, |
| 26 | + exir_ops.edge.aten.repeat.default, |
| 27 | + } |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def _is_shape_arg(arg: Any) -> bool: |
| 31 | + """Return True when `arg` looks like a literal shape list/tuple.""" |
| 32 | + is_shape_op = meta_has_shape_mark(arg.meta) if hasattr(arg, "meta") else False |
| 33 | + return ( |
| 34 | + not is_shape_op |
| 35 | + and isinstance(arg, (list, tuple)) |
| 36 | + and all(isinstance(x, int) for x in arg) |
| 37 | + ) |
| 38 | + |
| 39 | + def call_operator(self, op, args, kwargs, meta, updated: Optional[bool] = False): |
| 40 | + if op not in self.targeted_ops: |
| 41 | + return super().call_operator(op, args, kwargs, meta, updated) |
| 42 | + if any(InsertConstShapesPass._is_shape_arg(arg) for arg in args): |
| 43 | + new_args = [] |
| 44 | + for arg in args: |
| 45 | + if InsertConstShapesPass._is_shape_arg(arg): |
| 46 | + # Insert a const node for the shape argument |
| 47 | + if op == exir_ops.edge.aten.view_copy.default: |
| 48 | + arg = meta.data["val"].shape |
| 49 | + const_node = super().call_shape_operator( |
| 50 | + exir_ops.backend.tosa.CONST_SHAPE.default, |
| 51 | + (arg,), |
| 52 | + {}, |
| 53 | + meta, |
| 54 | + True, |
| 55 | + ) |
| 56 | + new_args.append(const_node) |
| 57 | + updated = True |
| 58 | + else: |
| 59 | + new_args.append(arg) |
| 60 | + |
| 61 | + return super().call_operator(op, tuple(new_args), kwargs, meta, updated) |
| 62 | + |
| 63 | + return super().call_operator(op, args, kwargs, meta, updated) |
0 commit comments