CUDAEvent.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #pragma once
  2. #include <ATen/cuda/ATenCUDAGeneral.h>
  3. #include <ATen/cuda/CUDAContext.h>
  4. #include <c10/core/impl/GPUTrace.h>
  5. #include <c10/cuda/CUDAStream.h>
  6. #include <c10/cuda/CUDAGuard.h>
  7. #include <ATen/cuda/Exceptions.h>
  8. #include <c10/util/Exception.h>
  9. #include <cuda_runtime_api.h>
  10. #include <cstdint>
  11. #include <utility>
  12. namespace at { namespace cuda {
  13. /*
  14. * CUDAEvents are movable not copyable wrappers around CUDA's events.
  15. *
  16. * CUDAEvents are constructed lazily when first recorded unless it is
  17. * reconstructed from a cudaIpcEventHandle_t. The event has a device, and this
  18. * device is acquired from the first recording stream. However, if reconstructed
  19. * from a handle, the device should be explicitly specified; or if ipc_handle() is
  20. * called before the event is ever recorded, it will use the current device.
  21. * Later streams that record the event must match this device.
  22. */
  23. struct TORCH_CUDA_CPP_API CUDAEvent {
  24. // Constructors
  25. // Default value for `flags` is specified below - it's cudaEventDisableTiming
  26. CUDAEvent() noexcept = default;
  27. CUDAEvent(unsigned int flags) noexcept : flags_{flags} {}
  28. CUDAEvent(
  29. DeviceIndex device_index, const cudaIpcEventHandle_t* handle) {
  30. device_index_ = device_index;
  31. CUDAGuard guard(device_index_);
  32. AT_CUDA_CHECK(cudaIpcOpenEventHandle(&event_, *handle));
  33. is_created_ = true;
  34. }
  35. // Note: event destruction done on creating device to avoid creating a
  36. // CUDA context on other devices.
  37. ~CUDAEvent() {
  38. try {
  39. if (is_created_) {
  40. CUDAGuard guard(device_index_);
  41. const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
  42. if (C10_UNLIKELY(interp)) {
  43. (*interp)->trace_gpu_event_deletion(reinterpret_cast<uintptr_t>(event_));
  44. }
  45. cudaEventDestroy(event_);
  46. }
  47. } catch (...) { /* No throw */ }
  48. }
  49. CUDAEvent(const CUDAEvent&) = delete;
  50. CUDAEvent& operator=(const CUDAEvent&) = delete;
  51. CUDAEvent(CUDAEvent&& other) noexcept { moveHelper(std::move(other)); }
  52. CUDAEvent& operator=(CUDAEvent&& other) noexcept {
  53. if (this != &other) {
  54. moveHelper(std::move(other));
  55. }
  56. return *this;
  57. }
  58. operator cudaEvent_t() const { return event(); }
  59. // Less than operator (to allow use in sets)
  60. friend bool operator<(const CUDAEvent& left, const CUDAEvent& right) {
  61. return left.event_ < right.event_;
  62. }
  63. optional<at::Device> device() const {
  64. if (is_created_) {
  65. return at::Device(at::kCUDA, device_index_);
  66. } else {
  67. return {};
  68. }
  69. }
  70. bool isCreated() const { return is_created_; }
  71. DeviceIndex device_index() const {return device_index_;}
  72. cudaEvent_t event() const { return event_; }
  73. // Note: cudaEventQuery can be safely called from any device
  74. bool query() const {
  75. if (!is_created_) {
  76. return true;
  77. }
  78. cudaError_t err = cudaEventQuery(event_);
  79. if (err == cudaSuccess) {
  80. return true;
  81. } else if (err != cudaErrorNotReady) {
  82. C10_CUDA_CHECK(err);
  83. } else {
  84. // ignore and clear the error if not ready
  85. cudaGetLastError();
  86. }
  87. return false;
  88. }
  89. void record() { record(getCurrentCUDAStream()); }
  90. void recordOnce(const CUDAStream& stream) {
  91. if (!was_recorded_) record(stream);
  92. }
  93. // Note: cudaEventRecord must be called on the same device as the event.
  94. void record(const CUDAStream& stream) {
  95. if (!is_created_) {
  96. createEvent(stream.device_index());
  97. }
  98. TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_,
  99. " does not match recording stream's device ", stream.device_index(), ".");
  100. CUDAGuard guard(device_index_);
  101. AT_CUDA_CHECK(cudaEventRecord(event_, stream));
  102. const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
  103. if (C10_UNLIKELY(interp)) {
  104. (*interp)->trace_gpu_event_record(
  105. reinterpret_cast<uintptr_t>(event_),
  106. reinterpret_cast<uintptr_t>(stream.stream())
  107. );
  108. }
  109. was_recorded_ = true;
  110. }
  111. // Note: cudaStreamWaitEvent must be called on the same device as the stream.
  112. // The event has no actual GPU resources associated with it.
  113. void block(const CUDAStream& stream) {
  114. if (is_created_) {
  115. CUDAGuard guard(stream.device_index());
  116. AT_CUDA_CHECK(cudaStreamWaitEvent(stream, event_, 0));
  117. const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
  118. if (C10_UNLIKELY(interp)) {
  119. (*interp)->trace_gpu_event_wait(
  120. reinterpret_cast<uintptr_t>(event_),
  121. reinterpret_cast<uintptr_t>(stream.stream())
  122. );
  123. }
  124. }
  125. }
  126. // Note: cudaEventElapsedTime can be safely called from any device
  127. float elapsed_time(const CUDAEvent& other) const {
  128. TORCH_CHECK(is_created_ && other.isCreated(),
  129. "Both events must be recorded before calculating elapsed time.");
  130. float time_ms = 0;
  131. // raise cudaErrorNotReady if either event is recorded but not yet completed
  132. AT_CUDA_CHECK(cudaEventElapsedTime(&time_ms, event_, other.event_));
  133. return time_ms;
  134. }
  135. // Note: cudaEventSynchronize can be safely called from any device
  136. void synchronize() const {
  137. if (is_created_) {
  138. const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
  139. if (C10_UNLIKELY(interp)) {
  140. (*interp)->trace_gpu_event_synchronization(reinterpret_cast<uintptr_t>(event_));
  141. }
  142. AT_CUDA_CHECK(cudaEventSynchronize(event_));
  143. }
  144. }
  145. // Note: cudaIpcGetEventHandle must be called on the same device as the event
  146. void ipc_handle(cudaIpcEventHandle_t * handle) {
  147. if (!is_created_) {
  148. // this CUDAEvent object was initially constructed from flags but event_
  149. // is not created yet.
  150. createEvent(getCurrentCUDAStream().device_index());
  151. }
  152. CUDAGuard guard(device_index_);
  153. AT_CUDA_CHECK(cudaIpcGetEventHandle(handle, event_));
  154. }
  155. private:
  156. unsigned int flags_ = cudaEventDisableTiming;
  157. bool is_created_ = false;
  158. bool was_recorded_ = false;
  159. DeviceIndex device_index_ = -1;
  160. cudaEvent_t event_{};
  161. void createEvent(DeviceIndex device_index) {
  162. device_index_ = device_index;
  163. CUDAGuard guard(device_index_);
  164. AT_CUDA_CHECK(cudaEventCreateWithFlags(&event_, flags_));
  165. const c10::impl::PyInterpreter* interp = c10::impl::GPUTrace::get_trace();
  166. if (C10_UNLIKELY(interp)) {
  167. (*interp)->trace_gpu_event_creation(reinterpret_cast<uintptr_t>(event_));
  168. }
  169. is_created_ = true;
  170. }
  171. void moveHelper(CUDAEvent&& other) {
  172. std::swap(flags_, other.flags_);
  173. std::swap(is_created_, other.is_created_);
  174. std::swap(was_recorded_, other.was_recorded_);
  175. std::swap(device_index_, other.device_index_);
  176. std::swap(event_, other.event_);
  177. }
  178. };
  179. } // namespace cuda
  180. } // namespace at