|
| 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 | +from typing import Set, Type |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from executorch.backends.arm._passes.arm_pass import ArmPass |
| 11 | +from executorch.backends.arm._passes.arm_pass_utils import ( |
| 12 | + create_node, |
| 13 | + get_first_fake_tensor, |
| 14 | + set_node_arg, |
| 15 | +) |
| 16 | +from executorch.backends.arm.tosa.specification import get_context_spec |
| 17 | +from executorch.exir.dialects._ops import ops as exir_ops |
| 18 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 19 | + |
| 20 | + |
| 21 | +class RewriteBoolToFp32CastViaInt8Pass(ArmPass): |
| 22 | + """ |
| 23 | + Legalizes unsupported bool->fp32 to_dim_order_copy casts for the Arm TOSA |
| 24 | + backend when both integer and float TOSA profiles are enabled. |
| 25 | +
|
| 26 | + For the combined INT+FP profile, this pass rewrites a single bool->fp32 cast |
| 27 | + into a bool->int8 cast followed by an int8->fp32 cast, so that each cast |
| 28 | + is individually supported by the TOSA INT and FP profiles. For other |
| 29 | + profiles (INT-only or FP-only) the pass is a no-op. |
| 30 | + """ |
| 31 | + |
| 32 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 33 | + |
| 34 | + targeted_ops = {exir_ops.edge.dim_order_ops._to_dim_order_copy.default} |
| 35 | + |
| 36 | + def call(self, graph_module: torch.fx.GraphModule): |
| 37 | + modified = False |
| 38 | + |
| 39 | + tosa_spec = get_context_spec() |
| 40 | + if not (tosa_spec.support_integer() and tosa_spec.support_float()): |
| 41 | + return PassResult(graph_module, modified) |
| 42 | + |
| 43 | + graph = graph_module.graph |
| 44 | + for node in graph.nodes: |
| 45 | + if node.op != "call_function" or node.target not in self.targeted_ops: |
| 46 | + continue |
| 47 | + |
| 48 | + input_node = node.all_input_nodes[0] |
| 49 | + input_dtype = get_first_fake_tensor(input_node).dtype |
| 50 | + if input_dtype != torch.bool: |
| 51 | + continue |
| 52 | + |
| 53 | + output_dtype = get_first_fake_tensor(node).dtype |
| 54 | + if output_dtype != torch.float32: |
| 55 | + continue |
| 56 | + |
| 57 | + set_node_arg(node, "dtype", torch.int8) |
| 58 | + |
| 59 | + users = list(node.users) |
| 60 | + with graph.inserting_after(node): |
| 61 | + cast_after = create_node( |
| 62 | + graph, |
| 63 | + node.target, |
| 64 | + args=(node,), |
| 65 | + kwargs={ |
| 66 | + "dtype": torch.float32, |
| 67 | + }, |
| 68 | + ) |
| 69 | + for user in users: |
| 70 | + user.replace_input_with(node, cast_after) |
| 71 | + modified = True |
| 72 | + |
| 73 | + if modified: |
| 74 | + graph_module.recompile() |
| 75 | + graph_module = super().call(graph_module).graph_module |
| 76 | + |
| 77 | + return PassResult(graph_module, modified) |
0 commit comments