_python_dispatcher.py 7.0 KB

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