streams.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # mypy: allow-untyped-defs
  2. import ctypes
  3. import torch
  4. from torch._streambase import _EventBase, _StreamBase
  5. from .._utils import _dummy_type
  6. if not hasattr(torch._C, "_CudaStreamBase"):
  7. # Define dummy base classes
  8. torch._C.__dict__["_CudaStreamBase"] = _dummy_type("_CudaStreamBase")
  9. torch._C.__dict__["_CudaEventBase"] = _dummy_type("_CudaEventBase")
  10. class Stream(torch._C._CudaStreamBase, _StreamBase):
  11. r"""Wrapper around a CUDA stream.
  12. A CUDA stream is a linear sequence of execution that belongs to a specific
  13. device, independent from other streams. See :ref:`cuda-semantics` for
  14. details.
  15. Args:
  16. device(torch.device or int, optional): a device on which to allocate
  17. the stream. If :attr:`device` is ``None`` (default) or a negative
  18. integer, this will use the current device.
  19. priority(int, optional): priority of the stream, should be 0 or
  20. negative, where negative numbers indicate higher priority. By default,
  21. streams have priority 0.
  22. """
  23. def __new__(cls, device=None, priority=0, **kwargs):
  24. # setting device manager is expensive, so we avoid it unless necessary
  25. if device is None or ("stream_id" in kwargs and "device_index" in kwargs):
  26. return super().__new__(cls, priority=priority, **kwargs)
  27. else:
  28. with torch.cuda.device(device):
  29. return super().__new__(cls, priority=priority, **kwargs)
  30. def wait_event(self, event) -> None:
  31. r"""Make all future work submitted to the stream wait for an event.
  32. Args:
  33. event (torch.cuda.Event): an event to wait for.
  34. .. note:: This is a wrapper around ``cudaStreamWaitEvent()``: see
  35. `CUDA Stream documentation`_ for more info.
  36. This function returns without waiting for :attr:`event`: only future
  37. operations are affected.
  38. .. _CUDA Stream documentation:
  39. https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__STREAM.html
  40. """
  41. event.wait(self)
  42. def wait_stream(self, stream) -> None:
  43. r"""Synchronize with another stream.
  44. All future work submitted to this stream will wait until all kernels
  45. submitted to a given stream at the time of call complete.
  46. Args:
  47. stream (Stream): a stream to synchronize.
  48. .. note:: This function returns without waiting for currently enqueued
  49. kernels in :attr:`stream`: only future operations are affected.
  50. """
  51. self.wait_event(stream.record_event())
  52. def record_event(self, event=None):
  53. r"""Record an event.
  54. Args:
  55. event (torch.cuda.Event, optional): event to record. If not given, a new one
  56. will be allocated.
  57. Returns:
  58. Recorded event.
  59. """
  60. if event is None:
  61. event = Event()
  62. event.record(self)
  63. return event
  64. def query(self) -> bool:
  65. r"""Check if all the work submitted has been completed.
  66. Returns:
  67. A boolean indicating if all kernels in this stream are completed.
  68. """
  69. return super().query()
  70. def synchronize(self) -> None:
  71. r"""Wait for all the kernels in this stream to complete.
  72. .. note:: This is a wrapper around ``cudaStreamSynchronize()``: see
  73. `CUDA Stream documentation`_ for more info.
  74. """
  75. super().synchronize()
  76. @property
  77. def _as_parameter_(self):
  78. return ctypes.c_void_p(self.cuda_stream)
  79. def __eq__(self, o) -> bool:
  80. if isinstance(o, Stream):
  81. return super().__eq__(o)
  82. return False
  83. def __hash__(self):
  84. return hash((self.cuda_stream, self.device))
  85. def __repr__(self):
  86. return f"<torch.cuda.Stream device={self.device} cuda_stream={self.cuda_stream:#x}>"
  87. class ExternalStream(Stream):
  88. r"""Wrapper around an externally allocated CUDA stream.
  89. This class is used to wrap streams allocated in other libraries in order
  90. to facilitate data exchange and multi-library interactions.
  91. .. note:: This class doesn't manage the stream life-cycle, it is the user
  92. responsibility to keep the referenced stream alive while this class is
  93. being used.
  94. Args:
  95. stream_ptr(int): Integer representation of the `cudaStream_t` value.
  96. allocated externally.
  97. device(torch.device or int, optional): the device where the stream
  98. was originally allocated. If device is specified incorrectly,
  99. subsequent launches using this stream may fail.
  100. """
  101. def __new__(cls, stream_ptr, device=None, **kwargs):
  102. with torch.cuda.device(device):
  103. return super().__new__(cls, stream_ptr=stream_ptr, **kwargs)
  104. class Event(torch._C._CudaEventBase, _EventBase):
  105. r"""Wrapper around a CUDA event.
  106. CUDA events are synchronization markers that can be used to monitor the
  107. device's progress, to accurately measure timing, and to synchronize CUDA
  108. streams.
  109. The underlying CUDA events are lazily initialized when the event is first
  110. recorded or exported to another process. After creation, only streams on the
  111. same device may record the event. However, streams on any device can wait on
  112. the event.
  113. Args:
  114. enable_timing (bool, optional): indicates if the event should measure time
  115. (default: ``False``)
  116. blocking (bool, optional): if ``True``, :meth:`wait` will be blocking (default: ``False``)
  117. interprocess (bool): if ``True``, the event can be shared between processes
  118. (default: ``False``)
  119. .. _CUDA Event Documentation:
  120. https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__EVENT.html
  121. """
  122. def __new__(cls, enable_timing=False, blocking=False, interprocess=False):
  123. return super().__new__(
  124. cls,
  125. enable_timing=enable_timing,
  126. blocking=blocking,
  127. interprocess=interprocess,
  128. )
  129. @classmethod
  130. def from_ipc_handle(cls, device, handle):
  131. r"""Reconstruct an event from an IPC handle on the given device."""
  132. return super().from_ipc_handle(device, handle)
  133. def record(self, stream=None):
  134. r"""Record the event in a given stream.
  135. Uses ``torch.cuda.current_stream()`` if no stream is specified. The
  136. stream's device must match the event's device.
  137. """
  138. if stream is None:
  139. stream = torch.cuda.current_stream()
  140. super().record(stream)
  141. def wait(self, stream=None) -> None:
  142. r"""Make all future work submitted to the given stream wait for this event.
  143. Use ``torch.cuda.current_stream()`` if no stream is specified.
  144. .. note:: This is a wrapper around ``cudaStreamWaitEvent()``: see
  145. `CUDA Event documentation`_ for more info.
  146. """
  147. if stream is None:
  148. stream = torch.cuda.current_stream()
  149. super().wait(stream)
  150. def query(self):
  151. r"""Check if all work currently captured by event has completed.
  152. Returns:
  153. A boolean indicating if all work currently captured by event has
  154. completed.
  155. """
  156. return super().query()
  157. def elapsed_time(self, end_event):
  158. r"""Return the time elapsed.
  159. Time reported in milliseconds after the event was recorded and
  160. before the end_event was recorded.
  161. """
  162. return super().elapsed_time(end_event)
  163. def synchronize(self) -> None:
  164. r"""Wait for the event to complete.
  165. Waits until the completion of all work currently captured in this event.
  166. This prevents the CPU thread from proceeding until the event completes.
  167. .. note:: This is a wrapper around ``cudaEventSynchronize()``: see
  168. `CUDA Event documentation`_ for more info.
  169. """
  170. super().synchronize()
  171. def ipc_handle(self):
  172. r"""Return an IPC handle of this event.
  173. If not recorded yet, the event will use the current device.
  174. """
  175. return super().ipc_handle()
  176. @property
  177. def _as_parameter_(self):
  178. return ctypes.c_void_p(self.cuda_event)
  179. def __repr__(self) -> str:
  180. if self.cuda_event:
  181. return f"<torch.cuda.Event {self._as_parameter_.value:#x}>"
  182. else:
  183. return "<torch.cuda.Event uninitialized>"