tools_common.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. from typing import List, Tuple, Union, Dict, Any, Set, Mapping
  2. import collections
  3. from dataclasses import dataclass
  4. import torch
  5. import torch.fx
  6. from torch.fx.node import _get_qualified_name
  7. from torch.fx._compatibility import compatibility
  8. __all__ = ['get_acc_ops_name', 'get_node_target', 'is_node_output_tensor', 'FxNetAccFusionsFinder', 'legalize_graph']
  9. Tensors = Union[Tuple[torch.Tensor], List[torch.Tensor]]
  10. TensorOrTensors = Union[torch.Tensor, Tensors]
  11. NodeList = List[torch.fx.Node]
  12. NodeSet = Set[torch.fx.Node]
  13. Names = List[str]
  14. CALLABLE_NODE_OPS = {"call_module", "call_function", "call_method"}
  15. @compatibility(is_backward_compatible=False)
  16. def get_acc_ops_name(k):
  17. if isinstance(k, str):
  18. return k
  19. elif k.__module__ and "acc_ops" in k.__module__:
  20. return f"acc_ops.{k.__name__}"
  21. else:
  22. module = k.__module__.replace('torch._ops', 'torch.ops') # WAR for bug in how torch.ops assigns module
  23. return f"{module if module else ''}.{k.__name__}"
  24. @compatibility(is_backward_compatible=False)
  25. def get_node_target(submodules: Mapping[str, torch.nn.Module], node: torch.fx.Node) -> str:
  26. """
  27. Given a `node` returns its target typename.
  28. For "call_method" node, return node.target which is the name of that method being called.
  29. This could potential lead to conflict but should be okay because normally it's on a tensor.
  30. For "call_function" node, return typename of node.target.
  31. For "call_module" node, return typename of the module that node.target point to.
  32. If seeing "_VariableFunctionsClass" in the target name string, it will be replaced by
  33. "torch". e.g. _VariableFunctionsClass.relu would become torch.relu.
  34. """
  35. assert node.op in CALLABLE_NODE_OPS, (
  36. "Expect op types of " + ", ".join(CALLABLE_NODE_OPS) + f", but found {node.op}"
  37. )
  38. if node.op == "call_module":
  39. assert isinstance(node.target, str)
  40. submod = submodules[node.target]
  41. submod_type = getattr(submod, "_base_class_origin", type(submod))
  42. return get_acc_ops_name(submod_type)
  43. elif node.op == "call_function":
  44. target: Any = node.target
  45. return (
  46. f"acc_ops.{target.__name__}"
  47. if target.__module__ is not None and "acc_ops" in target.__module__
  48. else _get_qualified_name(target)
  49. )
  50. else:
  51. assert isinstance(node.target, str)
  52. return node.target
  53. @compatibility(is_backward_compatible=False)
  54. def is_node_output_tensor(node: torch.fx.Node) -> bool:
  55. """Checks if the node output produces a Tensor or not.
  56. NOTE: This requires to run `ShapeProp` on the containing fx graph before
  57. calling this function. This is because it works by checking the `type`
  58. metadata on the node. This metadata is produced by the `ShapeProp`.
  59. """
  60. type_ = node.meta.get("type", None)
  61. return type_ is not None and issubclass(type_, torch.Tensor)
  62. @compatibility(is_backward_compatible=False)
  63. class FxNetAccFusionsFinder:
  64. """
  65. Finds groups of connected ACC nodes that pass non-tensor data between each other.
  66. Such groups are called fusion groups.
  67. """
  68. def __init__(self, module: torch.fx.GraphModule, acc_nodes: NodeSet):
  69. self.module = module
  70. self.nodes = list(module.graph.nodes)
  71. self.acc_nodes = acc_nodes
  72. @dataclass
  73. class FusionGroup:
  74. # The smallest idx of nodes in the fusion group after topological sorting all the nodes in the model.
  75. top_node_idx: int
  76. # Nodes in this fusion group.
  77. nodes: NodeSet
  78. # Inputs to this fusion group.
  79. inputs: NodeSet
  80. # Nodes that in the fusion group that haven't been processed yet.
  81. nodes_need_process: NodeSet
  82. def add_node(self, node):
  83. """
  84. Add a node to fusion group.
  85. """
  86. if node in self.nodes:
  87. return
  88. self.nodes_need_process.add(node)
  89. self.nodes.add(node)
  90. self.inputs.discard(node)
  91. self.inputs.update(
  92. {
  93. n
  94. for n in node.all_input_nodes
  95. if n.op in CALLABLE_NODE_OPS and n not in self.nodes
  96. }
  97. )
  98. def recursive_add_node(
  99. self,
  100. fusion_group: "FxNetAccFusionsFinder.FusionGroup",
  101. inputs: Union[NodeSet, NodeList],
  102. ):
  103. """
  104. Start from inputs and going reverse topological order. If any upstream node
  105. is in the fusion group, add all the nodes in this path to fusion group.
  106. """
  107. for arg in inputs:
  108. # Skip placeholder and get_attr because they won't be in the fusion group.
  109. if arg.op not in CALLABLE_NODE_OPS:
  110. continue
  111. # If the node has smaller idx, it's already an upstream node of the fusion
  112. # group. We don't need to check it anymore.
  113. if self.nodes.index(arg) < fusion_group.top_node_idx:
  114. continue
  115. # If the node is in the fusion group, return True.
  116. if arg in fusion_group.nodes:
  117. return True
  118. # Check the upstream nodes of the node, if any of them is in the fusion group
  119. # we'll add this node to fusion group and return True.
  120. if self.recursive_add_node(fusion_group, arg.all_input_nodes):
  121. fusion_group.add_node(arg)
  122. return True
  123. return False
  124. def __call__(self) -> Dict[torch.fx.Node, NodeSet]:
  125. result: Dict[torch.fx.Node, NodeSet] = {}
  126. acc_nodes = list(self.acc_nodes)
  127. for node in acc_nodes:
  128. if node in result:
  129. continue
  130. if node.op not in CALLABLE_NODE_OPS:
  131. continue
  132. if "tensor_meta" in node.meta:
  133. continue
  134. if node not in self.acc_nodes:
  135. continue
  136. fusion_group: "FxNetAccFusionsFinder.FusionGroup" = self.FusionGroup(
  137. top_node_idx=self.nodes.index(node),
  138. nodes={node},
  139. inputs=set(node.all_input_nodes),
  140. nodes_need_process={node},
  141. )
  142. while fusion_group.nodes_need_process:
  143. node = fusion_group.nodes_need_process.pop()
  144. self.recursive_add_node(fusion_group, fusion_group.inputs)
  145. # Optionally add downstream nodes
  146. if "tensor_meta" not in node.meta:
  147. for user in node.users:
  148. if user.op not in CALLABLE_NODE_OPS:
  149. continue
  150. if user in fusion_group.nodes:
  151. continue
  152. fusion_group.add_node(user)
  153. self.recursive_add_node(fusion_group, fusion_group.inputs)
  154. # Add some upstream nodes
  155. for arg in node.all_input_nodes:
  156. if arg.op not in CALLABLE_NODE_OPS:
  157. continue
  158. if "tensor_meta" in arg.meta:
  159. continue
  160. if arg in fusion_group.nodes:
  161. continue
  162. fusion_group.add_node(arg)
  163. fusion_group.top_node_idx = min(
  164. fusion_group.top_node_idx, self.nodes.index(arg)
  165. )
  166. self.recursive_add_node(fusion_group, fusion_group.inputs)
  167. if not (set(fusion_group.nodes) <= self.acc_nodes):
  168. self.acc_nodes -= fusion_group.nodes
  169. else:
  170. for n in fusion_group.nodes:
  171. result[n] = fusion_group.nodes
  172. return result
  173. @compatibility(is_backward_compatible=False)
  174. def legalize_graph(gm: torch.fx.GraphModule) -> torch.fx.GraphModule:
  175. """
  176. Replace the graph of the given GraphModule with one that contains the same nodes as the
  177. original, but in topologically sorted order.
  178. This is used by the merge_matmul transformation below, which disturbs the topologically sorted
  179. order of its input GraphModule, so that this order is restored before further transformation.
  180. Arguments:
  181. gm: The graph module to topologically sort. It is modified in-place.
  182. Returns:
  183. The graph module in-place sorted
  184. """
  185. indeg = {node: 0 for node in gm.graph.nodes}
  186. new_graph = torch.fx.Graph()
  187. # Track how many unfulfilled dependencies each node has
  188. for node in gm.graph.nodes:
  189. for user in node.users:
  190. indeg[user] += 1
  191. queue: collections.deque = collections.deque()
  192. # Add all nodes with no dependencies to the queue
  193. for node in gm.graph.nodes:
  194. if indeg[node] == 0:
  195. queue.append(node)
  196. env: Dict[torch.fx.Node, torch.fx.Node] = {}
  197. # Pop nodes from the queue, and add nodes that have had all their
  198. # dependencies fulfilled
  199. while len(queue) > 0:
  200. cur = queue.popleft()
  201. env[cur] = new_graph.node_copy(cur, lambda x: env[x])
  202. for user in cur.users:
  203. indeg[user] -= 1
  204. if indeg[user] == 0:
  205. queue.append(user)
  206. # If the new graph's size is not as large as the old one, then there must be
  207. # a cycle (i.e. some node's dependencies were not satisfied.)
  208. if len(new_graph.nodes) < len(gm.graph.nodes):
  209. raise RuntimeError(f"Input graph has cycles, unable to add {[node for node in indeg if indeg[node] != 0]}")
  210. new_graph._codegen = gm.graph._codegen
  211. gm.graph = new_graph
  212. return gm