closure.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # mypy: allow-untyped-defs
  2. import os
  3. import threading
  4. from queue import Empty as EmptyQueue, Queue
  5. from torch._lazy.device_context import get_device_context
  6. class ClosureHandler:
  7. def __init__(self) -> None:
  8. pass
  9. def run(self, closure):
  10. """Run closure function
  11. Args:
  12. closure: callable function to run
  13. """
  14. closure()
  15. def __call__(self, closures):
  16. for closure in closures:
  17. self.run(closure)
  18. class AsyncClosureHandler(ClosureHandler):
  19. """Handler for Asynchronous Step Closures
  20. Args:
  21. max_queue_size: The maximum length of the closure queue after which
  22. the training loop will block until closures are evaluated.
  23. By default, a reasonable limit of a maximum of 100 on the queue.
  24. This value can be set using the `XLA_MAX_ASYNC_QUEUE` environment
  25. variable.
  26. """
  27. def __init__(self, max_queue_size=100):
  28. super().__init__()
  29. self._closure_queue: Queue = Queue(
  30. int(os.environ.get("LTC_MAX_ASYNC_QUEUE", max_queue_size))
  31. )
  32. self._closure_exception: Queue = Queue()
  33. self._closure_lock = threading.Lock()
  34. self._closure_event_loop_finished = threading.Event()
  35. self._closure_event_loop = None
  36. def start_event_loop(self):
  37. """Start closure event loop if not started"""
  38. if self._closure_event_loop is None:
  39. def event_loop():
  40. # Run loop until closure event is set and closure queue is empty
  41. while True:
  42. try:
  43. closure = self._closure_queue.get(block=True, timeout=3)
  44. closure()
  45. self._closure_queue.task_done()
  46. except EmptyQueue:
  47. with self._closure_lock:
  48. if self._closure_queue.empty():
  49. self._closure_event_loop_finished.set()
  50. return
  51. except Exception as e:
  52. self._closure_exception.put(e)
  53. return
  54. # pyrefly: ignore [bad-assignment]
  55. self._closure_event_loop = threading.Thread(
  56. target=event_loop
  57. ) # pyrefly: ignore [bad-assignment]
  58. self._closure_event_loop.start() # pyrefly: ignore [missing-attribute]
  59. def run(self, closure):
  60. with self._closure_lock:
  61. self._closure_queue.put(closure, block=True)
  62. if (
  63. self._closure_event_loop is None
  64. or not self._closure_event_loop.is_alive()
  65. ):
  66. try:
  67. e = self._closure_exception.get(block=False)
  68. raise RuntimeError(
  69. "Cannot run asynchronous closure due to previously raised exception"
  70. ) from e
  71. except EmptyQueue:
  72. self._closure_event_loop = None
  73. self.start_event_loop()
  74. def add_step_closure(closure, args=(), run_async=False):
  75. """Adds a closure to the list of the ones to be run at the end of the step.
  76. Many times during model training there is the need to print/report (print to
  77. console, post to tensorboard, etc...) information which require the content of
  78. intermediary tensors to be inspected.
  79. Inspecting different tensors content in different points of the model code
  80. requires many executions and typically causes performance issues.
  81. Adding a step closure will ensure that it will be run after the barrier, when
  82. all the live tensors will be already materialized to device data.
  83. Live tensors which will include the ones captured by the closure arguments.
  84. So using `add_step_closure()` will ensure a single execution will be
  85. performed, even when multiple closures are queued, requiring multiple tensors
  86. to be inspected.
  87. Step closures will be run sequentially in the order they have been queued.
  88. Note that even though using this API the execution will be optimized, it is
  89. advised to throttle the printing/reporting events once every N steps.
  90. Args:
  91. closure (callable): The function to be called.
  92. args (tuple): The arguments to be passed to the closure.
  93. run_async: If True, run the closure asynchronously.
  94. """
  95. devctx = get_device_context()
  96. closures_type = "async_step_closures" if run_async else "step_closures"
  97. step_closures = getattr(devctx, closures_type, None)
  98. if step_closures is None:
  99. step_closures = []
  100. setattr(devctx, closures_type, step_closures)
  101. step_closures.append(lambda a=args: closure(*a))
  102. def run_step_closures():
  103. devctx = get_device_context()
  104. async_step_closures = getattr(devctx, "async_step_closures", None)
  105. if async_step_closures is not None:
  106. devctx.async_step_closures = [] # type: ignore[attr-defined]
  107. async_closure_handler = getattr(devctx, "async_closure_handler", None)
  108. if async_closure_handler is None:
  109. async_closure_handler = AsyncClosureHandler()
  110. devctx.async_closure_handler = async_closure_handler # type: ignore[attr-defined]
  111. async_closure_handler(async_step_closures)
  112. step_closures = getattr(devctx, "step_closures", None)
  113. if step_closures is not None:
  114. devctx.step_closures = [] # type: ignore[attr-defined]
  115. closure_handler = getattr(devctx, "closure_handler", None)
  116. if closure_handler is None:
  117. closure_handler = ClosureHandler()
  118. devctx.closure_handler = closure_handler # type: ignore[attr-defined]
  119. closure_handler(step_closures)
  120. return devctx