wrappers.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. # mypy: allow-untyped-defs
  2. import inspect
  3. from contextlib import contextmanager
  4. from functools import wraps
  5. import torch
  6. import torch._custom_ops
  7. from torch._C import DispatchKey
  8. from torch._export.utils import _maybe_find_pre_dispatch_tf_mode_for_export
  9. from torch._higher_order_ops.flat_apply import (
  10. _ConstantFunction,
  11. flat_apply,
  12. to_graphable,
  13. )
  14. from torch._higher_order_ops.strict_mode import strict_mode
  15. from torch._higher_order_ops.utils import autograd_not_implemented
  16. from torch._ops import HigherOrderOperator
  17. from torch._subclasses.fake_tensor import FakeTensorMode
  18. from torch.fx.experimental.proxy_tensor import (
  19. PreDispatchTorchFunctionMode,
  20. ProxyTorchDispatchMode,
  21. track_tensor_tree,
  22. )
  23. from torch.utils import _pytree as pytree
  24. from torch.utils._python_dispatch import is_traceable_wrapper_subclass_type
  25. class ExportTracepoint(HigherOrderOperator):
  26. def __init__(self):
  27. super().__init__("_export_tracepoint")
  28. def __call__(self, *args, **kwargs):
  29. # pyrefly: ignore [missing-attribute]
  30. return super().__call__(*args, **kwargs)
  31. _export_tracepoint = ExportTracepoint()
  32. @_export_tracepoint.py_impl(ProxyTorchDispatchMode)
  33. def export_tracepoint_dispatch_mode(mode, *args, **kwargs):
  34. p_args, p_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, (args, kwargs))
  35. proxy = mode.tracer.create_proxy(
  36. "call_function", _export_tracepoint, p_args, p_kwargs
  37. )
  38. return track_tensor_tree(args, proxy, constant=None, tracer=mode.tracer)
  39. @_export_tracepoint.py_impl(FakeTensorMode)
  40. def export_tracepoint_fake_tensor_mode(mode, *args, **kwargs):
  41. with mode:
  42. return args
  43. @_export_tracepoint.py_functionalize_impl
  44. def export_tracepoint_functional(ctx, *args, **kwargs):
  45. unwrapped_args = ctx.unwrap_tensors(args)
  46. unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
  47. with ctx.redispatch_to_next():
  48. _export_tracepoint(*unwrapped_args, **unwrapped_kwargs)
  49. return args
  50. _export_tracepoint.py_impl(DispatchKey.Autograd)(
  51. autograd_not_implemented(_export_tracepoint, deferred_error=True)
  52. )
  53. @_export_tracepoint.py_impl(DispatchKey.CPU)
  54. def export_tracepoint_cpu(*args, **kwargs):
  55. return args
  56. def _wrap_submodule(mod, path, module_call_specs):
  57. if not isinstance(mod, torch.nn.Module):
  58. raise AssertionError(f"expected torch.nn.Module, got {type(mod)}")
  59. if path == "":
  60. raise AssertionError("path must not be empty")
  61. submodule = torch.fx.graph_module._get_attr(mod, path)
  62. def update_module_call_signatures(path, in_spec, out_spec):
  63. if path in module_call_specs:
  64. if module_call_specs[path]["in_spec"] != in_spec:
  65. raise AssertionError(
  66. f"in_spec mismatch for {path}: {module_call_specs[path]['in_spec']} != {in_spec}"
  67. )
  68. if module_call_specs[path]["out_spec"] != out_spec:
  69. raise AssertionError(
  70. f"out_spec mismatch for {path}: {module_call_specs[path]['out_spec']} != {out_spec}"
  71. )
  72. module_call_specs[path] = {"in_spec": in_spec, "out_spec": out_spec}
  73. def check_flattened(flat_args):
  74. for a in flat_args:
  75. if not (isinstance(a, (torch.Tensor, str, int, float, bool)) or a is None):
  76. raise AssertionError(
  77. f"Only Tensors or scalars are supported as pytree flattened inputs, got: {a}"
  78. )
  79. def pre_hook(module, args, kwargs):
  80. flat_args, in_spec = pytree.tree_flatten((args, kwargs))
  81. check_flattened(flat_args)
  82. flat_args = _export_tracepoint(*flat_args, kind="module_call_inputs", path=path)
  83. args, kwargs = pytree.tree_unflatten(flat_args, in_spec)
  84. return args, kwargs
  85. def post_hook(module, args, kwargs, res):
  86. _, in_spec = pytree.tree_flatten((args, kwargs))
  87. flat_res, out_spec = pytree.tree_flatten(res)
  88. check_flattened(flat_res)
  89. flat_res = _export_tracepoint(*flat_res, kind="module_call_outputs", path=path)
  90. update_module_call_signatures(path, in_spec, out_spec)
  91. return pytree.tree_unflatten(flat_res, out_spec)
  92. pre_handle = submodule.register_forward_pre_hook(pre_hook, with_kwargs=True)
  93. post_handle = submodule.register_forward_hook(post_hook, with_kwargs=True)
  94. return pre_handle, post_handle
  95. @contextmanager
  96. def _wrap_submodules(f, preserve_signature, module_call_signatures):
  97. handles = []
  98. try:
  99. for path in preserve_signature:
  100. handles.extend(_wrap_submodule(f, path, module_call_signatures))
  101. yield
  102. finally:
  103. for handle in handles:
  104. handle.remove()
  105. def _mark_strict_experimental(cls):
  106. def call(self, *args):
  107. return strict_mode(self, args)
  108. cls.__call__ = call
  109. return cls
  110. def _register_func_spec_proxy_in_tracer(tracer, name, spec):
  111. """
  112. This is a wrapper utility method on top of tracer to cache the
  113. already registered subclass spec attribute. This is useful because
  114. Subclass.__init__ will be same for each subclass. By default, fx will
  115. create multiple attributes/proxies for given attribute.
  116. """
  117. fx_name = name + "0"
  118. if hasattr(tracer.root, fx_name):
  119. if getattr(tracer.root, fx_name) != spec:
  120. raise AssertionError(f"spec mismatch for {fx_name}")
  121. return tracer.create_proxy("get_attr", fx_name, (), {})
  122. qualname = tracer.get_fresh_qualname(name)
  123. setattr(tracer.root, qualname, spec)
  124. return tracer.create_proxy("get_attr", qualname, (), {})
  125. def _emit_flat_apply_call(
  126. *,
  127. tracer,
  128. spec_name: str,
  129. const_target_for_apply,
  130. graphable_args,
  131. track_value,
  132. call_spec_cache_key: str,
  133. ):
  134. # Flatten to graphable form and record the spec on the FX root
  135. flat_args, in_spec = to_graphable(graphable_args)
  136. qualname = tracer.get_fresh_qualname(spec_name) # type: ignore[union-attr]
  137. setattr(tracer.root, qualname, in_spec) # type: ignore[union-attr]
  138. spec_proxy = tracer.create_proxy("get_attr", qualname, (), {})
  139. # Reuse/cached ConstantFunction spec on the root
  140. _, func_spec = pytree.tree_flatten(_ConstantFunction(const_target_for_apply))
  141. func_spec_proxy = _register_func_spec_proxy_in_tracer(
  142. tracer, f"{call_spec_cache_key}_const_func_spec", func_spec
  143. )
  144. # Map runtime args -> proxies (always via tracer.unwrap_proxy now)
  145. flat_proxy_args = pytree.tree_map(tracer.unwrap_proxy, flat_args)
  146. # Emit flat_apply and track result structure
  147. out_proxy = tracer.create_proxy(
  148. "call_function", flat_apply, (func_spec_proxy, spec_proxy, *flat_proxy_args), {}
  149. )
  150. track_tensor_tree(track_value, out_proxy, constant=None, tracer=tracer)
  151. def _is_init(fn):
  152. return callable(fn) and fn.__name__ == "__init__"
  153. def mark_subclass_constructor_exportable_experimental(constructor_subclass):
  154. """
  155. Experimental decorator that makes subclass to be traceable in export
  156. with pre-dispatch IR. To make your subclass traceble in export, you need to:
  157. 1. Implement __init__ method for your subclass (Look at DTensor implementation)
  158. 2. Decorate your __init__ method with _mark_constructor_exportable_experimental
  159. 3. Put torch._dynamo_disable decorator to prevent dynamo from peeking into its' impl
  160. Example:
  161. class FooTensor(torch.Tensor):
  162. @staticmethod
  163. def __new__(cls, elem, *, requires_grad=False):
  164. # ...
  165. return torch.Tensor._make_subclass(cls, elem, requires_grad=requires_grad)
  166. @torch._dynamo_disable
  167. @mark_subclass_constructor_exportable_experimental
  168. def __init__(self, elem, ...):
  169. # ...
  170. """
  171. if not _is_init(constructor_subclass):
  172. raise RuntimeError(
  173. f"torch._export.wrappers.mark_constructor_exportable_experimental can only be applied on subclass tensor.__init__"
  174. f"But, you are adding it on {constructor_subclass.__name__} which is not supported. "
  175. f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example"
  176. )
  177. def wrapper(*args, **kwargs):
  178. constructor_subclass(*args, **kwargs)
  179. if not torch.compiler.is_exporting():
  180. return
  181. if not is_traceable_wrapper_subclass_type(type(args[0])):
  182. if not constructor_subclass.__qualname__.endswith("__init__"):
  183. raise AssertionError(
  184. f"expected __qualname__ to end with '__init__', got {constructor_subclass.__qualname__}"
  185. )
  186. obj_name = constructor_subclass.__qualname__[: -len("__init__")]
  187. raise RuntimeError(
  188. f"Can't intercept {obj_name} in export because this object is not a traceable "
  189. f"tensor subclass. Please look at DTensor.__init__ implementation as an example of proper usage of this API."
  190. )
  191. mode = _maybe_find_pre_dispatch_tf_mode_for_export()
  192. if mode is None:
  193. return
  194. if not isinstance(mode, PreDispatchTorchFunctionMode):
  195. raise AssertionError(
  196. f"expected PreDispatchTorchFunctionMode, got {type(mode)}"
  197. )
  198. tracer = mode.tracer
  199. subclass = args[0]
  200. graphable = (tuple(args[1:]), kwargs)
  201. spec_name = "_".join(constructor_subclass.__qualname__.lower().split("."))
  202. call_spec_cache_key = type(subclass).__name__.lower()
  203. _emit_flat_apply_call(
  204. tracer=tracer,
  205. spec_name=spec_name,
  206. const_target_for_apply=type(subclass),
  207. graphable_args=graphable,
  208. track_value=subclass, # track the constructed subclass instance
  209. call_spec_cache_key=call_spec_cache_key,
  210. )
  211. return
  212. return wrapper
  213. def allow_in_pre_dispatch_graph(func):
  214. """
  215. Experimental decorator that adds user function to export pre-dispatch graph. Note that
  216. we only support custom autograd function/subclass constructors today. To use this function:
  217. 1. For subclasses:
  218. 1. refer to instructions in mark_subclass_constructor_exportable_experimental
  219. 2. Define apply method on your custom autograd function and apply this decorator.
  220. Example:
  221. class MyCoolCustomAutogradFunc(autograd.Function):
  222. @classmethod
  223. @torch._export.wrappers.allow_in_pre_dispatch_graph
  224. def apply(cls, *args, **kwargs):
  225. return super(MyCoolCustomAutogradFunc, cls).apply(*args, **kwargs)
  226. """
  227. if _is_init(func):
  228. return mark_subclass_constructor_exportable_experimental(func)
  229. if not (_is_init(func) or func.__name__ == "apply"):
  230. raise RuntimeError(
  231. f"torch._export.wrappers.allow_in_pre_dispatch_graph can only be applied on subclass tensor.__init_ "
  232. f"or custom_autograd_function.apply. "
  233. f"But, you are adding it on {func.__name__} which is not supported. "
  234. f"If __init__ doesn't exist on your subclass, please add it. Look at DTensor.__init__ implementation for example. "
  235. f"If you are adding it on custom autograd function, please add it on apply method. "
  236. f"If anything else, file an issue on github and we may consider extending our support. "
  237. )
  238. @wraps(func)
  239. def wrapper(*args, **kwargs):
  240. if not torch.compiler.is_exporting():
  241. return func(*args, **kwargs)
  242. if not inspect.isclass(args[0]):
  243. return func(*args, **kwargs)
  244. if not issubclass(args[0], torch.autograd.Function):
  245. return func(*args, **kwargs)
  246. from torch._ops import _get_dispatch_mode_pre_dispatch
  247. mode = _get_dispatch_mode_pre_dispatch(torch._C._TorchDispatchModeKey.PROXY)
  248. if mode is None:
  249. return func(*args, **kwargs)
  250. # Sometimes custom autograd functions can call into HOPs that don't have proxy impl
  251. # at PreDispatch level, so we just dispatch it below to get the concrete result.
  252. include_to_set = torch._C._dispatch_tls_local_include_set().remove(
  253. torch._C.DispatchKey.PreDispatch
  254. )
  255. exclude_to_set = (
  256. torch._C._dispatch_tls_local_exclude_set()
  257. | torch._C.DispatchKeySet(torch._C.DispatchKey.PreDispatch)
  258. )
  259. with torch._C._ForceDispatchKeyGuard(include_to_set, exclude_to_set):
  260. out = func(*args, **kwargs)
  261. if not mode.pre_dispatch:
  262. raise AssertionError("Should only do this in predispatch")
  263. tracer = mode.tracer
  264. function_cls_name = f"{args[0].__module__}.{args[0].__qualname__}"
  265. graphable = ((function_cls_name, *args[1:]), kwargs)
  266. from torch.export.custom_ops import (
  267. _call_custom_autograd_function_in_pre_dispatch,
  268. )
  269. spec_name = "_".join(function_cls_name.split("."))
  270. call_spec_cache_key = type(
  271. _call_custom_autograd_function_in_pre_dispatch
  272. ).__name__.lower()
  273. _emit_flat_apply_call(
  274. tracer=tracer,
  275. spec_name=spec_name,
  276. const_target_for_apply=_call_custom_autograd_function_in_pre_dispatch,
  277. graphable_args=graphable,
  278. track_value=out,
  279. call_spec_cache_key=call_spec_cache_key,
  280. )
  281. return out
  282. return wrapper