executor.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from typing import Any, Callable, Optional, TypeVar
  2. from typing_extensions import ParamSpec, TypeVarTuple, Unpack
  3. from torch._prims.context import TorchRefsMode
  4. from torch.fx import GraphModule
  5. from torch.fx.experimental.proxy_tensor import make_fx, wrapper_and_args_for_make_fx
  6. T = TypeVar("T")
  7. P = ParamSpec("P")
  8. Ts = TypeVarTuple("Ts")
  9. def execute(
  10. gm: GraphModule,
  11. *args: Unpack[Ts],
  12. executor: str = "aten",
  13. executor_parameters: Optional[dict] = None,
  14. ) -> Any:
  15. """
  16. Prototype ATen executor.
  17. Just executes the context's graph.
  18. """
  19. if executor == "aten":
  20. return gm.forward(*args)
  21. msg = f"Received unexpected value for 'executor': {executor}. Allowed values are: aten."
  22. raise ValueError(msg)
  23. def make_traced(fn: Callable[P, T]) -> Callable[P, T]:
  24. """
  25. Returns a function that, when called, will
  26. trace its torch operations to prims and then
  27. execute those prims on the requested trace executor
  28. (possibly lowering them to that trace executor first).
  29. Only supports the torch operations defined in _torch_to_reference_map
  30. in context.py and operations with positional args. All args must
  31. be tensors.
  32. In the near future all these restrictions will be lifted.
  33. Example usage:
  34. def foo(a, b):
  35. return torch.add(a, b)
  36. traced_foo = make_traced(foo)
  37. a = torch.randn((1, 2, 3, 4, 5), device='cuda')
  38. b = torch.randn((1, 2, 3, 4, 5), device='cuda')
  39. result = traced_foo(a, b, executor='aten')
  40. """
  41. def _traced(*args: P.args, **kwargs: P.kwargs) -> T:
  42. executor = str(kwargs.pop("executor", "aten"))
  43. # TODO: caching
  44. wrapped, all_args = wrapper_and_args_for_make_fx(fn, args, kwargs)
  45. with TorchRefsMode():
  46. gm = make_fx(wrapped)(all_args)
  47. return execute(gm, all_args, executor=executor)
  48. return _traced # type: ignore[return-value]