_fuser.py 5.8 KB

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