_python_dispatcher.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import re
  2. import torch._C as C
  3. """
  4. PythonDispatcher class is a thin python-binding to C++ dispatcher and it
  5. is designed to show how dispatcher precompute works. In particular,
  6. it shows for a certain op `foo`, what the computed dispatch table looks
  7. like after user register their kernels to certains dispatch keys.
  8. In the real C++ dispatcher we support many dispatch keys for different
  9. functionalities. For simplicity PythonDispatcher only supports dispatch
  10. keys for a single example of each use case. These use cases are listed below:
  11. - CPU/AutogradCPU: represents in-tree backends which we usually have dedicated inference &
  12. autograd kernel in pytorch core library.
  13. E.g. CPU, CUDA
  14. - FPGA/AutogradOther: represents in-tree backends which we usually have backend specific
  15. inference kernels, but they share the same autograd kernel specified in AutogradOther.
  16. E.g. FPGA, SparseCsrCPU
  17. - XLA/AutogradXLA: represents out-of-tree backends which we don't have either inference or autograd
  18. kernel defined in pytorch core library. Backend owner is responsible for registering both
  19. inference & autograd kernels in their extensions(e.g. torch-xla) for the operators they support.
  20. E.g. XLA, XPU, MPS
  21. - CompositeExplicitAutograd: alias key mapped to inference kernels of all backends like CPU, CUDA, XLA etc.
  22. Kernels registered to this key MUST work for inference for all backends.
  23. - Autograd: alias key mapped to autograd of all backends like AutogradCPU, AutogradXLA, AutogradOther.
  24. Kernels registered to this key MUST work for autograd for all backends.
  25. - CompositeImplicitAutograd: alias key CompositeImplicitAutograd = CompositeExplicitAutograd + Autograd
  26. Kernels registered to this key MUST work for both inference + autograd for all backends.
  27. Note we only allow registrations to alias keys inside pytorch core library. E.g
  28. you shouldn't register a CompositeImplicitAutograd or CompositeExplicitAutograd
  29. kernel from torch-xla extension, instead you should upstream the kernel into
  30. pytorch/pytorch repo so that it's available for all backends and continuously
  31. tested even without the extension.
  32. Usage:
  33. dispatcher = PythonDispatcher()
  34. dispatcher.register(["CPU", "XLA", "CompositeImplicitAutograd"])
  35. print(dispatcher.dispatchTable()) # This tells you exactly which kernel is used for certain backend.
  36. # For more debugging information
  37. # print(dispatcher.keys())
  38. # print(dispatcher.registrations())
  39. # print(dispatcher.rawRegistrations())
  40. # print(dispatcher.rawDispatchTable())
  41. PythonDispatcher calls C++ dispatcher under the hood for to precompute dispatch table.
  42. This file only provides the simplified API for developers, relevant test code is located in
  43. test/test_dispatch.py
  44. """
  45. class PythonDispatcher:
  46. namespace = "__test__"
  47. name = "foo"
  48. # fmt: off
  49. runtime_keys = [
  50. "CPU", "AutogradCPU",
  51. "FPGA", "AutogradOther",
  52. "XLA", "AutogradXLA",
  53. "Lazy", "AutogradLazy",
  54. ]
  55. # fmt: on
  56. alias_keys = [
  57. "CompositeExplicitAutograd",
  58. "Autograd",
  59. "CompositeImplicitAutograd",
  60. ]
  61. supported_keys = runtime_keys + alias_keys
  62. def __init__(self):
  63. C._dispatch_check_invariants(self.name) # type: ignore[attr-defined]
  64. self.ref = C._dispatch_library("FRAGMENT", self.namespace, "")
  65. self.ref.def_("foo(Tensor x) -> Tensor")
  66. """
  67. Returns a list of dispatch keys supported by PythonDispatcher.
  68. You can register kernels to these keys.
  69. """
  70. def keys(self):
  71. return self.supported_keys
  72. """
  73. Register kernels to the target dispatchKeys.
  74. dispatchKeys(list[str]): a list of dispatch keys that you want to register
  75. your own kernel. Note that you don't need to write the kernel yourself in
  76. this PythonDispatcher.E.g. for CPU key, a kernel(e.g fn_CPU for CPU) is
  77. automatically generated and registered.
  78. """
  79. def register(self, dispatchKeys):
  80. # Overriden is not supported and triggers a warning in C++ dispatcher.
  81. if len(set(dispatchKeys)) != len(dispatchKeys):
  82. raise RuntimeError(
  83. f"Overriden is not allowed but found duplicates in {dispatchKeys}."
  84. )
  85. # We currently forbid this in codegen instead of C++ dispatcher.
  86. if (
  87. "CompositeImplicitAutograd" in dispatchKeys
  88. and "CompositeExplicitAutograd" in dispatchKeys
  89. ):
  90. raise RuntimeError(
  91. "Registration to both CompositeImplicitAutograd and CompositeExplicitAutograd is not allowed."
  92. )
  93. for key in dispatchKeys:
  94. if key not in self.supported_keys:
  95. raise RuntimeError(
  96. f"{key} is not supported, please select a dispatch key in {self.supported_keys}."
  97. )
  98. self.ref.impl_t_t("foo", dispatch=key, debug="fn_" + key)
  99. """
  100. Helper function to format (key, kernel).
  101. """
  102. def _format_line(self, key, kernel):
  103. return "{:<15} {}\n".format(key, kernel)
  104. """
  105. Helper function to print a table header.
  106. """
  107. def _format_header(self, header):
  108. s = f"""
  109. {header}
  110. """
  111. s += self._format_line("key", "kernel")
  112. s += "---------------------------\n"
  113. return s
  114. """
  115. Returns raw output of all registration info for debugging only.
  116. Use registrations() for a simplified version.
  117. """
  118. def rawRegistrations(self):
  119. return C._dispatch_dump("{}::{}".format(self.namespace, self.name)) # type: ignore[attr-defined]
  120. """
  121. Returns raw output of computed dispatch table for debugging only.
  122. Use dispatchTable() for a simplified version.
  123. """
  124. def rawDispatchTable(self):
  125. return C._dispatch_dump_table("{}::{}".format(self.namespace, self.name)) # type: ignore[attr-defined]
  126. """
  127. Returns a table(str) including all the registrations from users.
  128. Note this includes registrations to both runtime keys and alias keys.
  129. """
  130. def registrations(self):
  131. output = self._format_header("Registered Kernels")
  132. state = self.rawRegistrations()
  133. state_entries = state.split("\n")
  134. for line in state_entries:
  135. first = line.split(":")[0]
  136. if any(first.startswith(k) for k in self.supported_keys):
  137. kernel = line.split("::")[0].split(" ")[1]
  138. output += self._format_line(first, kernel)
  139. return output
  140. """
  141. Returns the computed dispatch table(str). Note this only include
  142. runtime keys, registrations to alias keys have been decoded to their
  143. mapped runtime keys.
  144. """
  145. def dispatchTable(self):
  146. output = self._format_header("Computed Dispatch Table")
  147. table = self.rawDispatchTable()
  148. table_entries = table.split("\n")
  149. regex = re.compile(r"registered at .*FallbackKernel\.cpp.*(\[)")
  150. for line in table_entries:
  151. k = line.split(":")[0]
  152. if k in self.runtime_keys:
  153. entry = regex.sub("[", line)
  154. output += self._format_line(k, entry.split(": ")[1])
  155. return output