|
| 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 | +import torch |
| 7 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 8 | +from executorch.exir.pass_base import ExportPass |
| 9 | + |
| 10 | + |
| 11 | +def _get_sum_decomp(op): |
| 12 | + match op: |
| 13 | + case exir_ops.edge.aten.sum.dim_IntList: |
| 14 | + return ( |
| 15 | + exir_ops.edge.aten.view_copy.default, |
| 16 | + exir_ops.edge.aten.sum.dim_IntList, |
| 17 | + ) |
| 18 | + case torch.ops.aten.sum.dim_IntList: |
| 19 | + return (torch.ops.aten.view_copy.default, torch.ops.aten.sum.dim_IntList) |
| 20 | + case _: |
| 21 | + raise RuntimeError("Unvalid op in DecomposeSumPass") |
| 22 | + |
| 23 | + |
| 24 | +class DecomposeSumPass(ExportPass): |
| 25 | + """ |
| 26 | + In Pytorch, the default behaviour of for example Tensor.sum is to squeeze the |
| 27 | + dimension that is summed (keep_dim = False). However, in TOSA, REDUCE_SUM always |
| 28 | + preserves the rank of the input (keep_dim = True). To get a 1-1 mapping in the sum |
| 29 | + lowering, normalize the keep_dim = False case to keep_dim = True and lower the rank |
| 30 | + with a view op. |
| 31 | +
|
| 32 | + Since TOSA can only reduce one dimension at a time, multiple dims are additionally |
| 33 | + unrolled into multiple ops. |
| 34 | +
|
| 35 | + Original: |
| 36 | + sum((dim_1, dim_2), keep_dim = False) -> squeezed_shape |
| 37 | + After pass: |
| 38 | + sum(dim_1, keep_dim = True) -> unsqueezed_shape |
| 39 | + sum(dim_2, keep_dim = True) -> unsqueezed_shape |
| 40 | + view(shape = squeezed_shape) -> squeezed_shape |
| 41 | + """ |
| 42 | + |
| 43 | + def call_operator(self, op, args, kwargs, meta): |
| 44 | + if op not in [ |
| 45 | + exir_ops.edge.aten.sum.dim_IntList, |
| 46 | + torch.ops.aten.sum.dim_IntList, |
| 47 | + ]: |
| 48 | + return super().call_operator(op, args, kwargs, meta) |
| 49 | + |
| 50 | + match len(args): |
| 51 | + case 3: |
| 52 | + ( |
| 53 | + input_node, |
| 54 | + dims, |
| 55 | + keepdims, |
| 56 | + ) = args |
| 57 | + case 2: |
| 58 | + ( |
| 59 | + input_node, |
| 60 | + dims, |
| 61 | + ) = args |
| 62 | + keepdims = False |
| 63 | + case _: |
| 64 | + raise ValueError(f"Invalid number of arguments ({len(args)}) provided.") |
| 65 | + |
| 66 | + view_op, sum_op = _get_sum_decomp(op) |
| 67 | + |
| 68 | + for dim in dims: |
| 69 | + input_node = super().call_operator( |
| 70 | + sum_op, (input_node, dim, True), kwargs, meta |
| 71 | + ) |
| 72 | + |
| 73 | + if not keepdims: |
| 74 | + shape = list(meta["val"].size()) |
| 75 | + input_node = super().call_operator( |
| 76 | + view_op, (input_node, shape), kwargs, meta |
| 77 | + ) |
| 78 | + |
| 79 | + return input_node |
0 commit comments