api.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the BSD-style license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. import abc
  8. import logging
  9. import threading
  10. import time
  11. from contextlib import contextmanager
  12. from inspect import getframeinfo, stack
  13. from typing import Any
  14. __all__ = [
  15. "TimerRequest",
  16. "TimerClient",
  17. "RequestQueue",
  18. "TimerServer",
  19. "configure",
  20. "expires",
  21. ]
  22. logger = logging.getLogger(__name__)
  23. class TimerRequest:
  24. """
  25. Data object representing a countdown timer acquisition and release
  26. that is used between the ``TimerClient`` and ``TimerServer``.
  27. A negative ``expiration_time`` should be interpreted as a "release"
  28. request.
  29. .. note:: the type of ``worker_id`` is implementation specific.
  30. It is whatever the TimerServer and TimerClient implementations
  31. have on to uniquely identify a worker.
  32. """
  33. __slots__ = ["worker_id", "scope_id", "expiration_time"]
  34. def __init__(self, worker_id: Any, scope_id: str, expiration_time: float):
  35. self.worker_id = worker_id
  36. self.scope_id = scope_id
  37. self.expiration_time = expiration_time
  38. def __eq__(self, other):
  39. if isinstance(other, TimerRequest):
  40. return (
  41. self.worker_id == other.worker_id
  42. and self.scope_id == other.scope_id
  43. and self.expiration_time == other.expiration_time
  44. )
  45. return False
  46. class TimerClient(abc.ABC):
  47. """
  48. Client library to acquire and release countdown timers by communicating
  49. with the TimerServer.
  50. """
  51. @abc.abstractmethod
  52. def acquire(self, scope_id: str, expiration_time: float) -> None:
  53. """
  54. Acquires a timer for the worker that holds this client object
  55. given the scope_id and expiration_time. Typically registers
  56. the timer with the TimerServer.
  57. """
  58. @abc.abstractmethod
  59. def release(self, scope_id: str):
  60. """
  61. Releases the timer for the ``scope_id`` on the worker this
  62. client represents. After this method is
  63. called, the countdown timer on the scope is no longer in effect.
  64. """
  65. class RequestQueue(abc.ABC):
  66. """
  67. Consumer queue holding timer acquisition/release requests
  68. """
  69. @abc.abstractmethod
  70. def size(self) -> int:
  71. """
  72. Returns the size of the queue at the time this method is called.
  73. Note that by the time ``get`` is called the size of the queue
  74. may have increased. The size of the queue should not decrease
  75. until the ``get`` method is called. That is, the following assertion
  76. should hold:
  77. size = q.size()
  78. res = q.get(size, timeout=0)
  79. assert size == len(res)
  80. -- or --
  81. size = q.size()
  82. res = q.get(size * 2, timeout=1)
  83. assert size <= len(res) <= size * 2
  84. """
  85. @abc.abstractmethod
  86. def get(self, size: int, timeout: float) -> list[TimerRequest]:
  87. """
  88. Gets up to ``size`` number of timer requests in a blocking fashion
  89. (no more than ``timeout`` seconds).
  90. """
  91. class TimerServer(abc.ABC):
  92. """
  93. Entity that monitors active timers and expires them
  94. in a timely fashion. This server is responsible for
  95. reaping workers that have expired timers.
  96. """
  97. def __init__(
  98. self, request_queue: RequestQueue, max_interval: float, daemon: bool = True
  99. ):
  100. """
  101. :param request_queue: Consumer ``RequestQueue``
  102. :param max_interval: max time (in seconds) to wait
  103. for an item in the request_queue
  104. :param daemon: whether to run the watchdog thread as a daemon
  105. """
  106. super().__init__()
  107. self._request_queue = request_queue
  108. self._max_interval = max_interval
  109. self._daemon = daemon
  110. self._watchdog_thread: threading.Thread | None = None
  111. self._stop_signaled = False
  112. @abc.abstractmethod
  113. def register_timers(self, timer_requests: list[TimerRequest]) -> None:
  114. """
  115. Processes the incoming timer requests and registers them with the server.
  116. The timer request can either be a acquire-timer or release-timer request.
  117. Timer requests with a negative expiration_time should be interpreted
  118. as a release-timer request.
  119. """
  120. @abc.abstractmethod
  121. def clear_timers(self, worker_ids: set[Any]) -> None:
  122. """
  123. Clears all timers for the given ``worker_ids``.
  124. """
  125. @abc.abstractmethod
  126. def get_expired_timers(self, deadline: float) -> dict[str, list[TimerRequest]]:
  127. """
  128. Returns all expired timers for each worker_id. An expired timer
  129. is a timer for which the expiration_time is less than or equal to
  130. the provided deadline.
  131. """
  132. @abc.abstractmethod
  133. def _reap_worker(self, worker_id: Any) -> bool:
  134. """
  135. Reaps the given worker. Returns True if the worker has been
  136. successfully reaped, False otherwise. If any uncaught exception
  137. is thrown from this method, the worker is considered reaped
  138. and all associated timers will be removed.
  139. """
  140. def _reap_worker_no_throw(self, worker_id: Any) -> bool:
  141. """
  142. Wraps ``_reap_worker(worker_id)``, if an uncaught exception is
  143. thrown, then it considers the worker as reaped.
  144. """
  145. try:
  146. return self._reap_worker(worker_id)
  147. except Exception:
  148. logger.exception(
  149. "Uncaught exception thrown from _reap_worker(), "
  150. "check that the implementation correctly catches exceptions",
  151. )
  152. return True
  153. def _watchdog_loop(self):
  154. while not self._stop_signaled:
  155. try:
  156. self._run_watchdog()
  157. except Exception:
  158. logger.exception("Error running watchdog")
  159. def _run_watchdog(self):
  160. batch_size = max(1, self._request_queue.size())
  161. timer_requests = self._request_queue.get(batch_size, self._max_interval)
  162. self.register_timers(timer_requests)
  163. now = time.time()
  164. reaped_worker_ids = set()
  165. for worker_id, expired_timers in self.get_expired_timers(now).items():
  166. logger.info(
  167. "Reaping worker_id=[%s]. Expired timers: %s",
  168. worker_id,
  169. self._get_scopes(expired_timers),
  170. )
  171. if self._reap_worker_no_throw(worker_id):
  172. logger.info("Successfully reaped worker=[%s]", worker_id)
  173. reaped_worker_ids.add(worker_id)
  174. else:
  175. logger.error(
  176. "Error reaping worker=[%s]. Will retry on next watchdog.", worker_id
  177. )
  178. self.clear_timers(reaped_worker_ids)
  179. def _get_scopes(self, timer_requests):
  180. return [r.scope_id for r in timer_requests]
  181. def start(self) -> None:
  182. logger.info(
  183. "Starting %s... max_interval=%s, daemon=%s",
  184. type(self).__name__,
  185. self._max_interval,
  186. self._daemon,
  187. )
  188. self._watchdog_thread = threading.Thread(
  189. target=self._watchdog_loop, daemon=self._daemon
  190. )
  191. logger.info("Starting watchdog thread...")
  192. self._watchdog_thread.start()
  193. def stop(self) -> None:
  194. logger.info("Stopping %s", type(self).__name__)
  195. self._stop_signaled = True
  196. if self._watchdog_thread:
  197. logger.info("Stopping watchdog thread...")
  198. self._watchdog_thread.join(self._max_interval)
  199. self._watchdog_thread = None
  200. else:
  201. logger.info("No watchdog thread running, doing nothing")
  202. _timer_client: TimerClient | None = None
  203. def configure(timer_client: TimerClient):
  204. """
  205. Configures a timer client. Must be called before using ``expires``.
  206. """
  207. global _timer_client
  208. _timer_client = timer_client
  209. logger.info("Timer client configured to: %s", type(_timer_client).__name__)
  210. @contextmanager
  211. def expires(after: float, scope: str | None = None, client: TimerClient | None = None):
  212. """
  213. Acquires a countdown timer that expires in ``after`` seconds from now,
  214. unless the code-block that it wraps is finished within the timeframe.
  215. When the timer expires, this worker is eligible to be reaped. The
  216. exact meaning of "reaped" depends on the client implementation. In
  217. most cases, reaping means to terminate the worker process.
  218. Note that the worker is NOT guaranteed to be reaped at exactly
  219. ``time.now() + after``, but rather the worker is "eligible" for being
  220. reaped and the ``TimerServer`` that the client talks to will ultimately
  221. make the decision when and how to reap the workers with expired timers.
  222. Usage::
  223. torch.distributed.elastic.timer.configure(LocalTimerClient())
  224. with expires(after=10):
  225. torch.distributed.all_reduce(...)
  226. """
  227. if client is None:
  228. if _timer_client is None:
  229. raise RuntimeError("Configure timer client before using countdown timers.")
  230. client = _timer_client
  231. if scope is None:
  232. # grab the caller file + lineno
  233. caller = getframeinfo(stack()[1][0])
  234. scope = f"{caller.filename}#{caller.lineno}"
  235. expiration = time.time() + after
  236. client.acquire(scope, expiration)
  237. try:
  238. yield
  239. finally:
  240. client.release(scope)