extract_compiled_graph.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import copy
  2. import dataclasses
  3. import itertools
  4. import os
  5. from typing import Any, Callable, Dict, List
  6. import torch
  7. import torch._lazy as lazy
  8. import torch._lazy.metrics as metrics
  9. from torch import fx
  10. from torch._lazy import computation, debug as lazy_debug
  11. from torch._lazy.tensor_factory_functions import tensor_factory_functions
  12. debug = os.environ.get("debug_extract_compiled_graph") is not None
  13. @dataclasses.dataclass
  14. class GraphInputMatcher:
  15. """
  16. The GraphInputMatcher class setup the graph inputs for future calls after lazy tracing.
  17. Specifically, those graph inputs corresponding to method parameters should be replaced with the
  18. arguments for the current call.
  19. tensor_id_to_arg_idx maps the tensor id to the parameter index.
  20. graph_input_tensor_ids, graph_input_ivalues list the tensor_id and ivalue for each of the
  21. TS/XLA graph inputs.
  22. """
  23. tensor_id_to_arg_idx: Dict[int, int]
  24. graph_input_tensor_ids: List[int]
  25. # there are 2 categories of graph_input_tensors.
  26. # Category 1: those whose id are not found in tensor_id_to_arg_idx. These are
  27. # most likely const tensors and we can get its content from graph_input_tensors
  28. # Category 2: those whose id are found in tensor_id_to_arg_idx. We should get
  29. # the tensor from method arguments
  30. graph_input_ivalues: List[Any]
  31. # get the real graph input tensors
  32. def __call__(self, args):
  33. real_input = []
  34. for tensor_id, traced_ivalue in zip(
  35. self.graph_input_tensor_ids, self.graph_input_ivalues
  36. ):
  37. arg_idx = self.tensor_id_to_arg_idx.get(tensor_id, None)
  38. if arg_idx is None:
  39. inp = traced_ivalue
  40. else:
  41. inp = args[arg_idx]
  42. real_input.append(inp)
  43. return real_input
  44. class ReturnValueHandler:
  45. r"""
  46. When ltc_sync_multi is called on multi tensors, the compiled graph
  47. will contain output only for unique tensors - if a tensor appears multiple
  48. times in the input to _ltc_sync_multi, only the first occurance matters.
  49. However from python level, we still expect multi tensors returned with duplciation
  50. even if the TS graph dedup the output. e.g. for method:
  51. def forward(self, a):
  52. return a, a
  53. the TS graph captured by LTC will return a single tensor, but Python method expects 2.
  54. This class dedup the lazy tensors first to get the index that will be used
  55. to duplicate the eager tensors later.
  56. """
  57. def __init__(self, lazy_out_list):
  58. self.index: List[List[int]] = []
  59. self.total_count = len(lazy_out_list)
  60. tensor_id_to_idx: Dict[int, int] = {}
  61. for dup_idx, lazy_tensor in enumerate(lazy_out_list):
  62. uniq_idx = tensor_id_to_idx.get(id(lazy_tensor), None)
  63. if uniq_idx is not None:
  64. self.index[uniq_idx].append(dup_idx)
  65. else:
  66. uniq_idx = len(self.index)
  67. self.index.append([dup_idx])
  68. tensor_id_to_idx[id(lazy_tensor)] = uniq_idx
  69. def duplicate_eager_tensors(self, eager_tensor_list):
  70. duplicated_list = [None] * self.total_count
  71. assert len(eager_tensor_list) == len(self.index)
  72. for uniq_idx, eager_tensor in enumerate(eager_tensor_list):
  73. for dup_idx in self.index[uniq_idx]:
  74. duplicated_list[dup_idx] = eager_tensor
  75. return duplicated_list
  76. def force_lazy_device(model: fx.GraphModule):
  77. """
  78. Factory methods in a Fx graph may create tensors for a specific eager devices.
  79. If we take no actions, those eager tensors will be mixed with lazy tensors and
  80. cause crash. This method overwrite those eager device to lazy device.
  81. """
  82. def tolazydevice(dev):
  83. if isinstance(dev, torch.device):
  84. return torch.device("lazy", index=dev.index)
  85. return dev
  86. def hasDeviceArg(args, kwargs):
  87. return any(
  88. isinstance(arg, torch.device)
  89. for arg in itertools.chain(args, kwargs.values())
  90. )
  91. for nd in model.graph.nodes:
  92. nd.args = tuple(tolazydevice(arg) for arg in nd.args)
  93. nd.kwargs = {k: tolazydevice(v) for k, v in nd.kwargs.items()}
  94. # For torchbench like yolov3, hf_Bart, dynamo generates Fx graph that return
  95. # eager tensors on the default device
  96. # (check https://gist.github.com/shunting314/eabdf6c769c59bc384469717b8f9bb7f for yolove,
  97. # and https://gist.github.com/shunting314/8d5e2d9348a3258959d3954186c48814 for hf_Bart).
  98. # To force those tensors on the lazy device, we can not simply override
  99. # the device argument since there is no explicit device argument.
  100. # What we are doing here is, for the list of covered tensor factory methods
  101. # we add a lazy device argument explicity.
  102. #
  103. # TODO: This solution is no ideal since we may miss some factory methods. In future
  104. # when we support lazy mode, this method can be replaced by that.
  105. if nd.target in tensor_factory_functions and not hasDeviceArg(
  106. nd.args, nd.kwargs
  107. ):
  108. kwargs = dict(nd.kwargs) # nd.kwargs is immutable. make a mutable copy.
  109. kwargs["device"] = torch.device("lazy")
  110. nd.kwargs = kwargs
  111. model.recompile()
  112. def get_fallback_ops():
  113. fallback_ops = []
  114. for opname in metrics.counter_names():
  115. if "aten::" not in opname:
  116. continue
  117. val = int(metrics.counter_value(opname))
  118. if val > 0:
  119. fallback_ops.append(f"{opname}={val}")
  120. return fallback_ops
  121. def extract_compiled_graph(model: fx.GraphModule, example_inputs) -> Callable:
  122. """
  123. Optimize an eager model with LTC and returns a wrapper to execute the
  124. compiled graph directly without retracing. It depends on other mechanisms
  125. like TorchDynamo guards to guarantee the returned wrapper is only called
  126. when it's safe.
  127. """
  128. lazy_args = [arg.to(device="lazy") for arg in example_inputs]
  129. args_tensor_ids = [lazy.get_tensor_id(lazy_arg) for lazy_arg in lazy_args]
  130. tensor_id_to_arg_idx = {tensor_id: i for i, tensor_id in enumerate(args_tensor_ids)}
  131. lazy_model = copy.deepcopy(model).to(device=torch.device("lazy"))
  132. force_lazy_device(lazy_model)
  133. # This line executes lazy tracing and enable us extracting compiled graph later
  134. metrics.reset()
  135. lazy_out = lazy_model(*lazy_args)
  136. fallback_ops = get_fallback_ops()
  137. metrics.reset()
  138. if len(fallback_ops) > 0:
  139. raise RuntimeError(
  140. f"Fail to extact the compiled graph because of fallback: {','.join(fallback_ops)}"
  141. )
  142. if not isinstance(lazy_out, (tuple, list)):
  143. lazy_out = (lazy_out,)
  144. args_and_out = tuple(lazy_args) + tuple(lazy_out)
  145. return_value_handler = ReturnValueHandler(args_and_out)
  146. if debug:
  147. print("Fx code:\n", model.code)
  148. print("LTC IR:", lazy_debug.dump_ir(args_and_out, "text"))
  149. # TODO: this part is TS backend specific for now and will be generalized to
  150. # support XLA
  151. (
  152. graph_input_tensor_ids,
  153. graph_input_ivalues,
  154. ) = computation.get_tensors_ts_device_data_node(args_and_out)
  155. assert len(graph_input_tensor_ids) == len(graph_input_ivalues)
  156. graph_input_matcher = GraphInputMatcher(
  157. tensor_id_to_arg_idx, graph_input_tensor_ids, graph_input_ivalues
  158. )
  159. graph_hash = computation.get_graph_hash(args_and_out)
  160. if debug:
  161. print("graph_hash", graph_hash)
  162. print(f"args_tensor_ids {args_tensor_ids}")
  163. print("tensor ids from device data:", graph_input_tensor_ids)
  164. # sync the list of output tensors so the computation graph for these
  165. # tensors will be cached. Those computation graphs can be retrieved
  166. # by graph hash later.
  167. lazy.sync_multi(args_and_out, [])
  168. def optimized_mod(*args):
  169. if len(args_and_out) == 0:
  170. return ()
  171. graph_input = graph_input_matcher(args)
  172. res = return_value_handler.duplicate_eager_tensors(
  173. computation.run_cached_graph(graph_hash, graph_input)
  174. )
  175. assert len(res) == len(args_and_out)
  176. for i, arg in enumerate(args):
  177. # only copy those tensors that get inplace updated
  178. if arg is not res[i]:
  179. arg.copy_(res[i])
  180. # skip the args
  181. return res[len(args) :]
  182. return optimized_mod