|
| 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.backends.arm._passes import ArmPass |
| 8 | +from executorch.backends.arm._passes.arm_pass_utils import get_first_fake_tensor |
| 9 | +from executorch.backends.transforms.utils import create_constant_placeholder |
| 10 | + |
| 11 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 12 | +from executorch.exir.pass_base import PassResult |
| 13 | +from torch.export.graph_signature import InputKind |
| 14 | + |
| 15 | + |
| 16 | +class AddBiasPass(ArmPass): |
| 17 | + """TOSA requires convolution nodes to have a bias input. |
| 18 | + This pass adds a bias input to convolution nodes that do not have one. |
| 19 | + The bias is set to zero. |
| 20 | + """ |
| 21 | + |
| 22 | + targeted_ops = (exir_ops.edge.aten.convolution.default,) |
| 23 | + |
| 24 | + def call(self, graph_module): |
| 25 | + modified = False |
| 26 | + for node in graph_module.graph.nodes: |
| 27 | + if node.op != "call_function": |
| 28 | + continue |
| 29 | + if node.target not in self.targeted_ops: |
| 30 | + continue |
| 31 | + |
| 32 | + if len(node.all_input_nodes) < 3: |
| 33 | + modified = True |
| 34 | + # bias is missing |
| 35 | + weight_node = node.all_input_nodes[1] |
| 36 | + output_channels = get_first_fake_tensor(weight_node).shape[0] |
| 37 | + # add a node containging zeros |
| 38 | + # if quantized, use int32, otherwise use float32 |
| 39 | + if ( |
| 40 | + "output_qparams" in node.meta |
| 41 | + and len(node.meta["output_qparams"]) > 0 |
| 42 | + ): |
| 43 | + bias_data = torch.zeros(size=(output_channels,), dtype=torch.int32) |
| 44 | + else: |
| 45 | + bias_data = torch.zeros( |
| 46 | + size=(output_channels,), dtype=torch.float32 |
| 47 | + ) |
| 48 | + |
| 49 | + with graph_module.graph.inserting_after(weight_node): |
| 50 | + bias_node = create_constant_placeholder( |
| 51 | + self.exported_program, |
| 52 | + graph=graph_module.graph, |
| 53 | + kind=InputKind.PARAMETER, |
| 54 | + data=bias_data, |
| 55 | + persistent_buffer=True, |
| 56 | + name=f"{node.name}_bias", |
| 57 | + ) |
| 58 | + node.update_arg(2, bias_node) |
| 59 | + |
| 60 | + if modified: |
| 61 | + graph_module = super().call(graph_module).graph_module |
| 62 | + return PassResult(graph_module, modified) |
0 commit comments