|
| 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 | +# pyre-unsafe |
| 7 | + |
| 8 | +from executorch.backends.arm._passes import ArmPass |
| 9 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 10 | + |
| 11 | + |
| 12 | +class ConvertIntPowToMuls(ArmPass): |
| 13 | + """ |
| 14 | + Replaces pow with integer exponent with a series of multiplications. |
| 15 | + Only handles pow.Tensor_Scalar and not pow.Tensor_Tensor. |
| 16 | + Needs to be run before doing scalar to tensor conversion. |
| 17 | + """ |
| 18 | + |
| 19 | + def call_operator(self, op, args, kwargs, meta): |
| 20 | + if op != exir_ops.edge.aten.pow.Tensor_Scalar: |
| 21 | + return super().call_operator(op, args, kwargs, meta) |
| 22 | + |
| 23 | + x = args[0] |
| 24 | + exp = args[1] |
| 25 | + |
| 26 | + # Handle zero first and return early |
| 27 | + if exp == 0: |
| 28 | + # return a tensor of ones with the same shape as x |
| 29 | + return super().call_operator( |
| 30 | + exir_ops.edge.aten.full_like.default, (x, 1), {}, meta, True |
| 31 | + ) |
| 32 | + |
| 33 | + if not isinstance(exp, int): |
| 34 | + return super().call_operator(op, args, kwargs, meta) |
| 35 | + |
| 36 | + # Handle negative exponent |
| 37 | + if exp < 0: |
| 38 | + x = super().call_operator( |
| 39 | + exir_ops.edge.aten.reciprocal.default, (x,), {}, meta, True |
| 40 | + ) |
| 41 | + exp = -exp |
| 42 | + |
| 43 | + res = x |
| 44 | + |
| 45 | + # Consider exponentiation by squaring, if exp turns out to be large. |
| 46 | + # Now we just roll out the multiplications. |
| 47 | + for _ in range(exp - 1): |
| 48 | + res = super().call_operator( |
| 49 | + exir_ops.edge.aten.mul.Tensor, (res, x), {}, meta, True |
| 50 | + ) |
| 51 | + |
| 52 | + return res |
0 commit comments