_fuser.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import torch
  4. @contextlib.contextmanager
  5. def optimized_execution(should_optimize):
  6. """Context manager that controls whether the JIT's executor will run optimizations before executing a function."""
  7. stored_flag = torch._C._get_graph_executor_optimize()
  8. torch._C._set_graph_executor_optimize(should_optimize)
  9. try:
  10. yield
  11. finally:
  12. torch._C._set_graph_executor_optimize(stored_flag)
  13. @contextlib.contextmanager
  14. def fuser(name):
  15. """Context manager that facilitates switching between backend fusers.
  16. Valid names:
  17. * ``fuser0`` - enables only legacy fuser
  18. * ``fuser1`` - enables only NNC
  19. * ``fuser2`` - enables only nvFuser
  20. * ``fuser3`` - enables oneDNN Graph
  21. """
  22. old_cpu_fuse = torch._C._jit_can_fuse_on_cpu()
  23. old_gpu_fuse = torch._C._jit_can_fuse_on_gpu()
  24. old_texpr_fuser_state = torch._C._jit_texpr_fuser_enabled()
  25. old_nvfuser_state = torch._C._jit_nvfuser_enabled()
  26. old_llga_state = torch._C._jit_llga_enabled()
  27. if name == "fuser0": # legacy fuser
  28. torch._C._jit_override_can_fuse_on_cpu(True)
  29. torch._C._jit_override_can_fuse_on_gpu(True)
  30. torch._C._jit_set_texpr_fuser_enabled(False)
  31. torch._C._jit_set_nvfuser_enabled(False)
  32. torch._C._jit_set_llga_enabled(False)
  33. elif name == "fuser1": # NNC
  34. old_profiling_executor = torch._C._jit_set_profiling_executor(True)
  35. old_profiling_mode = torch._C._get_graph_executor_optimize(True)
  36. torch._C._jit_override_can_fuse_on_cpu(True)
  37. torch._C._jit_override_can_fuse_on_gpu(True)
  38. torch._C._jit_set_texpr_fuser_enabled(True)
  39. torch._C._jit_set_nvfuser_enabled(False)
  40. torch._C._jit_set_llga_enabled(False)
  41. elif name == "fuser2": # nvFuser
  42. torch._C._jit_override_can_fuse_on_cpu(False)
  43. torch._C._jit_override_can_fuse_on_gpu(False)
  44. torch._C._jit_set_texpr_fuser_enabled(False)
  45. torch._C._jit_set_nvfuser_enabled(True)
  46. torch._C._jit_set_llga_enabled(False)
  47. elif name == "fuser3": # oneDNN Graph
  48. old_profiling_executor = torch._C._jit_set_profiling_executor(True)
  49. old_profiling_mode = torch._C._get_graph_executor_optimize(True)
  50. torch._C._jit_override_can_fuse_on_cpu(True)
  51. torch._C._jit_override_can_fuse_on_gpu(False)
  52. torch._C._jit_set_texpr_fuser_enabled(True)
  53. torch._C._jit_set_nvfuser_enabled(False)
  54. torch._C._jit_set_llga_enabled(True)
  55. elif name == "none": # Turn Pytorch fuser off
  56. torch._C._jit_override_can_fuse_on_cpu(False)
  57. torch._C._jit_override_can_fuse_on_gpu(False)
  58. torch._C._jit_set_texpr_fuser_enabled(False)
  59. torch._C._jit_set_nvfuser_enabled(False)
  60. torch._C._jit_set_llga_enabled(False)
  61. else:
  62. raise Exception(f"unrecognized fuser option (name: {name})") # noqa: TRY002
  63. try:
  64. yield
  65. finally:
  66. if name in ["fuser1", "fuser3"]: # NNC or oneDNN Graph
  67. torch._C._jit_set_profiling_executor(old_profiling_executor) # type: ignore[possibly-undefined]
  68. torch._C._get_graph_executor_optimize(old_profiling_mode) # type: ignore[possibly-undefined]
  69. # recover the previous values
  70. torch._C._jit_override_can_fuse_on_cpu(old_cpu_fuse)
  71. torch._C._jit_override_can_fuse_on_gpu(old_gpu_fuse)
  72. torch._C._jit_set_texpr_fuser_enabled(old_texpr_fuser_state)
  73. torch._C._jit_set_nvfuser_enabled(old_nvfuser_state)
  74. torch._C._jit_set_llga_enabled(old_llga_state)
  75. last_executed_optimized_graph = torch._C._last_executed_optimized_graph
  76. def _get_differentiable_graph_node(node, diff_node):
  77. if node.kind() == "prim::DifferentiableGraph":
  78. diff_node.append(node)
  79. else:
  80. for block in node.blocks():
  81. for n in block.nodes():
  82. _get_differentiable_graph_node(n, diff_node)
  83. def _graph_for(self, *args, **kwargs):
  84. return _script_method_graph_for(self, self, *args, **kwargs)
  85. def _script_method_graph_for(self, parent, *args, **kwargs):
  86. try:
  87. dbs = parent.get_debug_state()
  88. eps = list(dbs.execution_plans.values())
  89. assert len(eps) == 1
  90. graph = eps[0].graph.copy()
  91. # graph_executor_states for differentiable node
  92. fw_states = eps[0].code.differentiable_op_executor_states()
  93. diff_nodes: list[torch._C.Node] = []
  94. for n in graph.nodes():
  95. _get_differentiable_graph_node(n, diff_nodes)
  96. assert len(fw_states) == len(diff_nodes)
  97. # swap each differentiable graph with optimized graph in their execution plan
  98. for n, state in zip(diff_nodes, fw_states):
  99. fw_execution_plans = list(state.execution_plans.values())
  100. # we can only update the subgraph when there's a unique execution
  101. # plan. Avoid assert here so we would skip the ones that can't be
  102. # updated while try the best effort to update other nodes.
  103. if len(fw_execution_plans) == 1:
  104. n.g_("Subgraph", fw_execution_plans[0].graph)
  105. return graph
  106. except Exception:
  107. # fallback approach, we just ran the graph and return the recorded optimized
  108. # graph
  109. self(*args, **kwargs)
  110. return last_executed_optimized_graph()
  111. def set_fusion_strategy(strategy: list[tuple[str, int]]):
  112. """Set the type and number of specializations that can occur during fusion.
  113. Usage: provide a list of pairs (type, depth) where type is one of "STATIC" or "DYNAMIC"
  114. and depth is an integer.
  115. Behavior - static vs dynamic:
  116. In STATIC fusion, fused ops are compiled to have fixed input shapes. The shape is determined
  117. based on some initial profiling runs.
  118. In DYNAMIC fusion, fused ops are compiled to have variable input shapes, so that multiple
  119. shapes are possible.
  120. In both cases, we also recompile on new striding behavior, device, or dtype.
  121. Behavior - fallback functions & depth:
  122. When an input doesn't match the format required by the specialized compiled op, it will run
  123. a fallback function. Fallback functions are recursively be compiled and specialized based
  124. on the observed tensor shapes. Since compilation can be slow, the "depth" parameter is provided to
  125. limit the number of specializations that can be compiled, before giving up on recompiling and
  126. falling back to a completely un-fused, un-specialized implementation.
  127. The list of (type, depth) pairs controls the type of specializations and the number of
  128. specializations. For example: [("STATIC", 2), ("DYNAMIC", 2)] indicates that the first
  129. two specializations will use static fusions, the following two specializations will use
  130. dynamic fusion, and any inputs that satisfy none of the 4 options will run an
  131. unfused implementation.
  132. NB: in the future, if more as more fusion backends are added there may be more granular
  133. apis for specific fusers.
  134. """
  135. return torch._C._jit_set_fusion_strategy(strategy)