|
| 1 | +# Copyright 2024 Arm Limited and/or its affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +from typing import cast |
| 8 | + |
| 9 | +import torch |
| 10 | +import torch.fx |
| 11 | +from executorch.backends.arm._passes.arm_pass_utils import create_node, insert_q_dq_pair |
| 12 | + |
| 13 | +from executorch.backends.arm.tosa_quant_utils import get_quant_node_args, is_quant_node |
| 14 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 15 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 16 | + |
| 17 | + |
| 18 | +class InsertSqueezeAfterSumPass(ExportPass): |
| 19 | + """ |
| 20 | + In Pytorch, the default behaviour of Tensor.sum is to squeeze |
| 21 | + the dimension that is summed (keep_dim = False). |
| 22 | + However, in TOSA, REDUCE_SUM always preserves the |
| 23 | + rank of the input (keep_dim = True). |
| 24 | + To get a 1-1 mapping in the sum lowering, normalize the |
| 25 | + keep_dim = False case to keep_dim = True and add squeeze ops. |
| 26 | +
|
| 27 | + Original: |
| 28 | + sum(dims, keep_dim = False) |
| 29 | + After pass: |
| 30 | + sum(dims, keep_dim = True) |
| 31 | + (q) |
| 32 | + (dq) |
| 33 | + squeeze(dim = dims) |
| 34 | + """ |
| 35 | + |
| 36 | + def call(self, graph_module: torch.fx.GraphModule): |
| 37 | + for node in graph_module.graph.nodes: |
| 38 | + if node.op != "call_function": |
| 39 | + continue |
| 40 | + if node.target != exir_ops.edge.aten.sum.dim_IntList: |
| 41 | + continue |
| 42 | + sum_node = cast(torch.fx.Node, node) |
| 43 | + keep_dim = cast(bool, sum_node.args[2] if len(sum_node.args) > 2 else False) |
| 44 | + if keep_dim: |
| 45 | + continue |
| 46 | + |
| 47 | + dim_list = cast(list[int], sum_node.args[1]) |
| 48 | + quantized = is_quant_node(sum_node) |
| 49 | + if quantized: |
| 50 | + qparams = get_quant_node_args(sum_node.all_input_nodes[0]) |
| 51 | + qparams = qparams + (torch.int8,) |
| 52 | + else: |
| 53 | + qparams = None |
| 54 | + |
| 55 | + # Add keep_dim = True arg to sum node. |
| 56 | + sum_node.args = sum_node.args[0:2] + (True,) |
| 57 | + |
| 58 | + with graph_module.graph.inserting_after(sum_node): |
| 59 | + squeeze_node = create_node( |
| 60 | + graph_module.graph, exir_ops.edge.aten.squeeze_copy.dims, () |
| 61 | + ) |
| 62 | + sum_node.replace_all_uses_with(squeeze_node) |
| 63 | + squeeze_node.args = (sum_node, dim_list) |
| 64 | + if quantized: |
| 65 | + sum_node = insert_q_dq_pair(graph_module.graph, sum_node, qparams) |
| 66 | + graph_module.graph.eliminate_dead_code() |
| 67 | + graph_module.recompile() |
| 68 | + graph_module = super().call(graph_module).graph_module |
| 69 | + return PassResult(graph_module, True) |
0 commit comments