callback.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. """
  2. This module provides callback management functionality for TorchDynamo's compilation process.
  3. It implements a thread-safe system for registering, managing and executing callbacks that run
  4. at the start and end of TorchDynamo compilations. Key features include:
  5. - Registration and deregistration of compilation callbacks
  6. - Thread-safe callback handling with proper locking mechanisms
  7. - Prevention of duplicate callback execution when configured
  8. - Decorator utilities for easy callback registration
  9. - Context manager for controlled callback lifecycle
  10. The module centers around the CompilationCallbackHandler class which maintains separate
  11. lists for start and end callbacks, manages their execution order, and ensures thread-safety.
  12. Utility decorators @on_compile_start and @on_compile_end provide a convenient way to
  13. register compilation hooks.
  14. Example usage:
  15. @on_compile_start
  16. def my_start_callback():
  17. print("Starting compilation")
  18. @on_compile_end
  19. def my_end_callback():
  20. print("Compilation complete")
  21. """
  22. import enum
  23. import threading
  24. from collections.abc import Callable, Generator
  25. from contextlib import contextmanager
  26. from dataclasses import dataclass, field # noqa: F811
  27. from typing import Any
  28. class CallbackTrigger(enum.Enum):
  29. # most common case, dynamo attempts to trace a new frame
  30. DYNAMO = 1
  31. # backward compilation can be deferred to runtime
  32. LAZY_BACKWARD = 2
  33. # some backends autotune at runtime
  34. TRITON_AUTOTUNING = 3 # Temporarily disabled due to spam
  35. # cudagraphs record at runtime
  36. CUDAGRAPH_RECORDING = 4
  37. @dataclass
  38. class CallbackArgs:
  39. callback_trigger: CallbackTrigger
  40. compile_id: str
  41. @dataclass
  42. class CompilationCallbackHandler:
  43. start_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list)
  44. end_callbacks: list[Callable[[CallbackArgs], None]] = field(default_factory=list)
  45. __pending_callbacks_counter: int = field(default=0, init=False, repr=False)
  46. __pending_callbacks_counter_lock: threading.Lock = field(
  47. default_factory=threading.Lock, init=False, repr=False
  48. )
  49. def register_start_callback(
  50. self, callback: Callable[[CallbackArgs], None]
  51. ) -> Callable[[CallbackArgs], None]:
  52. """
  53. Register a callback function to be called when the compilation starts.
  54. Args:
  55. - callback (Callable): The callback function to register.
  56. """
  57. self.start_callbacks.append(callback)
  58. return callback
  59. def register_end_callback(
  60. self, callback: Callable[[CallbackArgs], None]
  61. ) -> Callable[[CallbackArgs], None]:
  62. """
  63. Register a callback function to be called when the compilation ends.
  64. Args:
  65. - callback (Callable): The callback function to register.
  66. """
  67. self.end_callbacks.append(callback)
  68. return callback
  69. def remove_start_callback(self, callback: Callable[[CallbackArgs], None]) -> None:
  70. """
  71. Remove a registered start callback function.
  72. Args:
  73. - callback (Callable): The callback function to remove.
  74. """
  75. self.start_callbacks.remove(callback)
  76. def remove_end_callback(self, callback: Callable[[CallbackArgs], None]) -> None:
  77. """
  78. Remove a registered end callback function.
  79. Args:
  80. - callback (Callable): The callback function to remove.
  81. """
  82. self.end_callbacks.remove(callback)
  83. def run_start_callbacks(self, args: CallbackArgs) -> None:
  84. """
  85. Execute all registered start callbacks.
  86. """
  87. for callback in self.start_callbacks:
  88. callback(args)
  89. def run_end_callbacks(self, args: CallbackArgs) -> None:
  90. """
  91. Execute all registered end callbacks.
  92. """
  93. for callback in self.end_callbacks:
  94. callback(args)
  95. @contextmanager
  96. def install_callbacks(
  97. self, trigger: CallbackTrigger, compile_id: str
  98. ) -> Generator[None, Any, Any]:
  99. """
  100. Context manager to install the callbacks and run them when the context is exited.
  101. """
  102. args = CallbackArgs(trigger, compile_id)
  103. try:
  104. with self.__pending_callbacks_counter_lock:
  105. self.__pending_callbacks_counter += 1
  106. if self.__pending_callbacks_counter == 1:
  107. self.run_start_callbacks(args)
  108. yield
  109. finally:
  110. with self.__pending_callbacks_counter_lock:
  111. assert self.__pending_callbacks_counter > 0, (
  112. "Pending callbacks counter cannot become negative."
  113. )
  114. if self.__pending_callbacks_counter == 1:
  115. self.run_end_callbacks(args)
  116. self.__pending_callbacks_counter -= 1
  117. def clear(self) -> None:
  118. """
  119. Clear all registered callbacks.
  120. """
  121. self.start_callbacks.clear()
  122. self.end_callbacks.clear()
  123. assert self.__pending_callbacks_counter == 0
  124. callback_handler = CompilationCallbackHandler()
  125. def on_compile_start(
  126. callback: Callable[[CallbackArgs], None],
  127. ) -> Callable[[CallbackArgs], None]:
  128. """
  129. Decorator to register a callback function for the start of the compilation.
  130. """
  131. callback_handler.register_start_callback(callback)
  132. return callback
  133. def on_compile_end(
  134. callback: Callable[[CallbackArgs], None],
  135. ) -> Callable[[CallbackArgs], None]:
  136. """
  137. Decorator to register a callback function for the end of the compilation.
  138. """
  139. callback_handler.register_end_callback(callback)
  140. return callback