|
| 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 Set, Type |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from executorch.backends.arm._passes import ArmPass |
| 11 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 12 | +from executorch.exir.pass_base import ExportPass |
| 13 | + |
| 14 | + |
| 15 | +class RewritePadPass(ArmPass): |
| 16 | + """Rewrite constant_pad_nd operator to TOSA Pad operator with constant |
| 17 | + mode. |
| 18 | + """ |
| 19 | + |
| 20 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 21 | + targeted_ops = { |
| 22 | + exir_ops.edge.aten.constant_pad_nd.default, |
| 23 | + } |
| 24 | + |
| 25 | + def call_operator(self, op, args, kwargs, meta, updated=False): |
| 26 | + if op not in self.targeted_ops: |
| 27 | + return super().call_operator(op, args, kwargs, meta) |
| 28 | + |
| 29 | + if len(args) == 3: |
| 30 | + input_tensor, pad, value = args |
| 31 | + else: |
| 32 | + input_tensor, pad = args |
| 33 | + value = 0 |
| 34 | + |
| 35 | + output_dtype = meta["val"].dtype |
| 36 | + if output_dtype in (torch.int8, torch.int16): |
| 37 | + input_qparams = meta.data.get("input_qparams", {}) |
| 38 | + if len(input_qparams) == 0: |
| 39 | + raise ValueError( |
| 40 | + f"No input quantization parameters found in metadata for constant_pad_nd with output dtype {output_dtype}" |
| 41 | + ) |
| 42 | + value = input_qparams[0].quantize_value(value).item() |
| 43 | + |
| 44 | + # Each dim needs 2 padding values. For example, to pad the last dimension, the pad has the form |
| 45 | + # (padding_left, padding_right); to pad the last two dimensions, the pad has the form |
| 46 | + # (padding_left, padding_right, padding_top, padding_bottom), and so on. We want to reverse the padding |
| 47 | + # so that we get (N_before, N_after, C_before, C_after, H_before, H_after, W_before, W_after) for a 4D |
| 48 | + # input tensor. |
| 49 | + pad_pairs = [[pad[i], pad[i + 1]] for i in range(0, len(pad), 2)] |
| 50 | + input_pad = [] |
| 51 | + for pair in reversed(pad_pairs): |
| 52 | + input_pad.extend(pair) |
| 53 | + input_rank = len(input_tensor.data.shape) |
| 54 | + # Place spatial dimensions last and pad non-spatial dimensions with 0 padding |
| 55 | + shape = [0] * ((input_rank * 2 - len(pad))) + input_pad |
| 56 | + |
| 57 | + pad_shape = super().call_shape_operator( |
| 58 | + exir_ops.backend.tosa.CONST_SHAPE.default, (shape,), {}, meta, True |
| 59 | + ) |
| 60 | + |
| 61 | + return super().call_operator( |
| 62 | + exir_ops.backend.tosa.PAD.default, |
| 63 | + (input_tensor, pad_shape), |
| 64 | + {"value": value}, |
| 65 | + meta, |
| 66 | + True, |
| 67 | + ) |
0 commit comments