|
| 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 collections import deque |
| 7 | +from typing import Any, Deque, Dict, Hashable, List, Set, Tuple, Type |
| 8 | + |
| 9 | +import torch |
| 10 | +from executorch.backends.arm._passes.arm_pass import ArmPass |
| 11 | +from executorch.exir.dialects.edge._ops import EdgeOpOverload |
| 12 | +from executorch.exir.pass_base import ExportPass, PassResult |
| 13 | +from torch._ops import OpOverload |
| 14 | +from torch.fx import GraphModule, Node |
| 15 | +from torch.fx.node import Argument, map_arg |
| 16 | + |
| 17 | + |
| 18 | +class FuseDuplicateUsersPass(ArmPass): |
| 19 | + """Fuse identical users of a producer node into a single operation. |
| 20 | +
|
| 21 | + Example: |
| 22 | +
|
| 23 | + y = producer(x) |
| 24 | + z0 = torch.add(y, bias) |
| 25 | + z1 = torch.add(y, bias) |
| 26 | +
|
| 27 | + becomes a single ``torch.add`` that feeds both consumers. |
| 28 | + """ |
| 29 | + |
| 30 | + _passes_required_after: Set[Type[ExportPass]] = set() |
| 31 | + |
| 32 | + def call(self, graph_module: GraphModule) -> PassResult: |
| 33 | + graph = graph_module.graph |
| 34 | + modified = False |
| 35 | + |
| 36 | + producers: Deque[Node] = deque(node for node in graph.nodes) |
| 37 | + |
| 38 | + while producers: |
| 39 | + producer = producers.popleft() |
| 40 | + |
| 41 | + if producer.graph is None: |
| 42 | + # Node was deleted by a previous rewrite while still queued. |
| 43 | + continue |
| 44 | + |
| 45 | + # Only meaningful if a value is consumed by multiple users. |
| 46 | + user_nodes = list(producer.users) |
| 47 | + if len(user_nodes) < 2: |
| 48 | + continue |
| 49 | + |
| 50 | + candidate_groups = self._get_candidate_groups(user_nodes) |
| 51 | + |
| 52 | + signature_to_user: Dict[Tuple[Hashable, ...], Node] = {} |
| 53 | + for group in candidate_groups: |
| 54 | + for user in group: |
| 55 | + signature = self._build_user_signature(user) |
| 56 | + if signature is None: |
| 57 | + continue |
| 58 | + |
| 59 | + representative = signature_to_user.get(signature) |
| 60 | + if representative is None: |
| 61 | + # Check if we already encountered identical node that we can fuse with. |
| 62 | + signature_to_user[signature] = user |
| 63 | + continue |
| 64 | + |
| 65 | + if user is representative: |
| 66 | + # The queue can enqueue the surviving node again after rewrites. |
| 67 | + continue |
| 68 | + |
| 69 | + user.replace_all_uses_with(representative) |
| 70 | + graph.erase_node(user) |
| 71 | + modified = True |
| 72 | + |
| 73 | + # Revisit the current producer and the surviving user so that |
| 74 | + # newly formed duplicate chains can be fused in later |
| 75 | + # iterations. |
| 76 | + producers.append(producer) |
| 77 | + producers.append(representative) |
| 78 | + |
| 79 | + if modified: |
| 80 | + graph_module.recompile() |
| 81 | + graph_module.graph.lint() |
| 82 | + graph_module = super().call(graph_module).graph_module |
| 83 | + |
| 84 | + return PassResult(graph_module, modified) |
| 85 | + |
| 86 | + def _get_candidate_groups(self, user_nodes): |
| 87 | + users_by_target: Dict[Tuple[str, Hashable], List[Node]] = {} |
| 88 | + for user in user_nodes: |
| 89 | + if user.graph is None: |
| 90 | + # User might already have been removed by a prior rewrite. |
| 91 | + continue |
| 92 | + |
| 93 | + if user.op != "call_function": |
| 94 | + continue |
| 95 | + |
| 96 | + target_key = self._get_target_key(user.target) |
| 97 | + target_signature = (user.op, target_key) |
| 98 | + users_by_target.setdefault(target_signature, []).append(user) |
| 99 | + |
| 100 | + candidate_groups = [ |
| 101 | + group for group in users_by_target.values() if len(group) > 1 |
| 102 | + ] |
| 103 | + |
| 104 | + return candidate_groups |
| 105 | + |
| 106 | + def _build_user_signature(self, node: Node) -> Tuple[Hashable, ...] | None: |
| 107 | + try: |
| 108 | + normalized_args = self._to_hashable( |
| 109 | + map_arg(node.args, self._map_leaf_to_key) |
| 110 | + ) |
| 111 | + normalized_kwargs = self._to_hashable( |
| 112 | + {k: map_arg(v, self._map_leaf_to_key) for k, v in node.kwargs.items()} |
| 113 | + ) |
| 114 | + except TypeError: |
| 115 | + return None |
| 116 | + |
| 117 | + target_key = self._get_target_key(node.target) |
| 118 | + |
| 119 | + return (node.op, target_key, normalized_args, normalized_kwargs) |
| 120 | + |
| 121 | + def _map_leaf_to_key(self, node: Node) -> Argument: |
| 122 | + return node.name |
| 123 | + |
| 124 | + def _to_hashable(self, value: Any) -> Hashable: |
| 125 | + """Convert arbitrarily nested structures into hashable tuples.""" |
| 126 | + |
| 127 | + if isinstance(value, (list, tuple)): |
| 128 | + return tuple(self._to_hashable(v) for v in value) |
| 129 | + if isinstance(value, dict): |
| 130 | + normalized_items = [(k, self._to_hashable(v)) for k, v in value.items()] |
| 131 | + return tuple(sorted(normalized_items, key=lambda item: repr(item[0]))) |
| 132 | + if isinstance(value, set): |
| 133 | + hashable_values: List[Hashable] = [self._to_hashable(v) for v in value] |
| 134 | + return tuple(sorted(hashable_values, key=repr)) |
| 135 | + if isinstance(value, slice): |
| 136 | + return ( |
| 137 | + "slice", |
| 138 | + self._to_hashable(value.start), |
| 139 | + self._to_hashable(value.stop), |
| 140 | + self._to_hashable(value.step), |
| 141 | + ) |
| 142 | + if isinstance(value, range): |
| 143 | + return ("range", value.start, value.stop, value.step) |
| 144 | + if isinstance(value, torch.Size): |
| 145 | + return ("size", tuple(value)) |
| 146 | + if isinstance(value, torch.dtype): |
| 147 | + return ("dtype", str(value)) |
| 148 | + if isinstance(value, torch.device): |
| 149 | + return ("device", str(value)) |
| 150 | + if isinstance(value, torch.memory_format): |
| 151 | + return ("memory_format", str(value)) |
| 152 | + if isinstance(value, torch.Tensor): |
| 153 | + return ( |
| 154 | + "tensor", |
| 155 | + str(value.dtype), |
| 156 | + tuple(value.size()), |
| 157 | + value.device.type, |
| 158 | + value.requires_grad, |
| 159 | + ) |
| 160 | + return value |
| 161 | + |
| 162 | + def _get_target_key(self, target: Any) -> Hashable: |
| 163 | + if isinstance(target, (EdgeOpOverload, OpOverload)): |
| 164 | + return str(target) |
| 165 | + return target |
0 commit comments