cuda_streams_py.cc 13.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
#include "paddle/fluid/pybind/cuda_streams_py.h"

17 18 19
#include <string>
#include <vector>

20
#include "paddle/fluid/platform/device_event_base.h"
21 22 23 24 25
#include "paddle/fluid/platform/event.h"

namespace py = pybind11;

namespace paddle {
L
Leo Chen 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
namespace platform {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
phi::CUDAStream *get_current_stream(int device_id) {
  if (device_id == -1) {
    device_id = phi::backends::gpu::GetCurrentDeviceId();
  }
  auto *gpu_context = static_cast<const phi::GPUContext *>(
      DeviceContextPool::Instance().Get(GPUPlace(device_id)));
  return gpu_context->cuda_stream();
}

phi::CUDAStream *set_current_stream(phi::CUDAStream *stream) {
  auto *original_stream = get_current_stream(stream->place().GetDeviceId());
  auto *gpu_context = static_cast<phi::GPUContext *>(
      DeviceContextPool::Instance().Get(stream->place()));
  gpu_context->SetCUDAStream(stream, /*clear=*/false);
  return original_stream;
}
#endif
}  // namespace platform
46 47 48 49 50
namespace pybind {
void BindCudaStream(py::module *m_ptr) {
  auto &m = *m_ptr;

  // Bind Methods
51 52 53
  m.def(
      "_get_current_stream",
      [](int deviceId) {
54
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
L
Leo Chen 已提交
55
        return platform::get_current_stream(deviceId);
56
#else
L
Leo Chen 已提交
57 58 59
        PADDLE_THROW(
            platform::errors::Unavailable("Paddle is not compiled with CUDA. "
                                          "Cannot visit device synchronize."));
60
#endif
61 62
      },
      py::return_value_policy::reference);
63

64 65
  m.def(
      "_set_current_stream",
L
Leo Chen 已提交
66
      [](phi::CUDAStream *stream) {
67
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
L
Leo Chen 已提交
68
        return platform::set_current_stream(stream);
69
#else
L
Leo Chen 已提交
70 71 72
        PADDLE_THROW(
            platform::errors::Unavailable("Paddle is not compiled with CUDA. "
                                          "Cannot visit device synchronize."));
73
#endif
74 75
      },
      py::return_value_policy::reference);
76

77 78 79 80 81 82 83 84 85
  m.def("_device_synchronize", [](int device_id) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    if (device_id == -1) {
      device_id = paddle::platform::GetCurrentDeviceId();
    }

    int curr_device_id = paddle::platform::GetCurrentDeviceId();
    paddle::platform::SetDeviceId(device_id);
#ifdef PADDLE_WITH_HIP
86
    PADDLE_ENFORCE_GPU_SUCCESS(hipDeviceSynchronize());
87
#else
88
    PADDLE_ENFORCE_GPU_SUCCESS(cudaDeviceSynchronize());
89 90 91 92 93 94 95 96
#endif
    paddle::platform::SetDeviceId(curr_device_id);
#else
    PADDLE_THROW(platform::errors::Unavailable(
        "Paddle is not compiled with CUDA. Cannot visit device synchronize."));
#endif
  });

L
Leo Chen 已提交
97
  py::class_<phi::CUDAStream>(m, "CUDAStream", R"DOC(
98 99 100
      The handle of the CUDA stream.

      Parameters:
101 102 103
        device(paddle.CUDAPlace()|int|None, optional): The device which wanted to allocate the stream.
        If device is None or negative integer, device will be the current device.
        If device is positive integer, it must less than the device count. Default: None.
104 105

        priority(int|None, optional): The priority of stream. The priority can be 1(high) or 2(normal).
106
        If priority is None, the priority is 2(normal). Default: None.
107 108 109 110 111 112 113 114 115 116 117 118

      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            s1 = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
            s2 = paddle.device.cuda.Stream(0, 1)
            s3 = paddle.device.cuda.Stream()

  )DOC")
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
119 120
      .def(
          "wait_event",
L
Leo Chen 已提交
121
          [](phi::CUDAStream &self, paddle::platform::CudaEvent &event) {
122 123 124
            self.WaitEvent(event.GetRawCudaEvent());
          },
          R"DOC(
125 126 127 128
      Makes all future work submitted to stream wait for all work captured in event.

      Parameters:
        event(CUDAEvent): The event to wait on.
129

130 131 132 133 134 135 136 137 138 139
      Examples:
        .. code-block:: python

          # required: gpu
          import paddle
          s = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
          event = paddle.device.cuda.Event()
          s.wait_event(event)

           )DOC")
140 141
      .def(
          "wait_stream",
L
Leo Chen 已提交
142
          [](phi::CUDAStream &self, phi::CUDAStream &stream) {
143 144 145 146 147
            paddle::platform::CudaEvent event;
            event.Record(stream.raw_stream());
            self.WaitEvent(event.GetRawCudaEvent());
          },
          R"DOC(
148 149 150 151
      Synchronizes with the given stream.

      Parameters:
        stream(CUDAStream): The stream to synchronize with.
152

153 154 155 156 157 158 159 160 161 162
      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            s1 = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
            s2 = paddle.device.cuda.Stream(0, 1)
            s1.wait_stream(s2)

           )DOC")
163 164
      .def(
          "query",
L
Leo Chen 已提交
165
          [](phi::CUDAStream &self) { return self.Query(); },
166
          R"DOC(
167 168 169 170 171 172 173 174 175 176 177 178 179
      Return the status whether if all operations in stream have completed.

      Returns: A boolean value.

      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            s = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
            is_done = s.query()

           )DOC")
180 181
      .def(
          "synchronize",
L
Leo Chen 已提交
182
          [](phi::CUDAStream &self) { self.Synchronize(); },
183
          R"DOC(
184 185 186 187 188 189 190 191 192 193 194
      Waits for stream tasks to complete.

      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            s = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
            s.synchronize()

           )DOC")
195 196
      .def(
          "record_event",
L
Leo Chen 已提交
197
          [](phi::CUDAStream &self, paddle::platform::CudaEvent *event) {
198 199 200 201 202 203 204
            if (event == nullptr) {
              event = new paddle::platform::CudaEvent();
            }
            event->Record(self.raw_stream());
            return event;
          },
          R"DOC(
205 206 207 208 209
      Record a CUDA event in the stream.

      Parameters:
          event(CUDAEvent, optional): The event to be record. If event is None, a new event is created.
          Default: None.
210

211 212 213 214 215 216 217 218 219 220 221 222
      Returns:
          The recored event.

      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            s = paddle.device.cuda.Stream(paddle.CUDAPlace(0), 1)
            event = s.record_event()

           )DOC",
223
          py::arg("event") = nullptr)
L
Leo Chen 已提交
224 225
      .def_property_readonly(
          "cuda_stream",
L
Leo Chen 已提交
226
          [](phi::CUDAStream &self) {
L
Leo Chen 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240
            VLOG(10) << self.raw_stream();
            return reinterpret_cast<std::uintptr_t>(self.raw_stream());
          },
          R"DOC(
      retrun the raw cuda stream of type cudaStream_t as type int.

      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            import ctypes
            cuda_stream = paddle.device.cuda.current_stream().cuda_stream
            print(cuda_stream)
241

L
Leo Chen 已提交
242 243 244 245
            ptr = ctypes.c_void_p(cuda_stream)  # convert back to void*
            print(ptr)

           )DOC")
246 247 248 249
      .def_property_readonly("place",
                             [](phi::CUDAStream &self) {
                               return platform::CUDAPlace(self.place());
                             })
250
#endif
251 252
      .def(
          "__init__",
L
Leo Chen 已提交
253
          [](phi::CUDAStream &self, platform::CUDAPlace *place, int priority) {
254
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
255 256 257 258 259
            if (priority != 1 && priority != 2) {
              PADDLE_THROW(platform::errors::InvalidArgument(
                  "Priority should be 1(high) or 2(normal) "));
            }

L
Leo Chen 已提交
260
            if (place == nullptr) {
261
              int curr_device_id = platform::GetCurrentDeviceId();
L
Leo Chen 已提交
262 263
              auto place_tmp = platform::CUDAPlace(curr_device_id);
              place = &place_tmp;
264 265
            }

266 267 268 269
            auto stream_flag = phi::CUDAStream::StreamFlag::kStreamNonBlocking;
            // seting priority 1(high) and 2(normal) correspond to the actual
            // cuda stream priority -1 and 0.
            new (&self) phi::CUDAStream(*place, priority - 2, stream_flag);
270 271 272 273
#else
            PADDLE_THROW(platform::errors::Unavailable(
        "Class CUDAStream can only be initialized on the GPU platform."));
#endif
274
          },
275 276
          py::arg("device") = nullptr,
          py::arg("priority") = 2)
277 278
      .def(
          "__init__",
L
Leo Chen 已提交
279
          [](phi::CUDAStream &self, int device, int priority) {
280 281 282 283 284 285
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
            if (priority != 1 && priority != 2) {
              PADDLE_THROW(platform::errors::InvalidArgument(
                  "Priority should be 1(high) or 2(normal) "));
            }

286
            int device_count = platform::GetGPUDeviceCount();
287 288 289 290 291 292
            if (device < 0) {
              device = platform::GetCurrentDeviceId();
            }
            if (device >= device_count) {
              PADDLE_THROW(platform::errors::InvalidArgument(
                  "The device id  must be inside [0, %d), but input device=%d.",
293 294
                  device_count,
                  device));
295 296
            }

297 298 299 300 301
            auto stream_flag = phi::CUDAStream::StreamFlag::kStreamNonBlocking;
            // seting priority 1(high) and 2(normal) correspond to the actual
            // cuda stream priority -1 and 0.
            new (&self) phi::CUDAStream(
                platform::CUDAPlace(device), priority - 2, stream_flag);
302 303 304 305 306
#else
            PADDLE_THROW(platform::errors::Unavailable(
        "Class CUDAStream can only be initialized on the GPU platform."));
#endif
          },
307 308
          py::arg("device") = -1,
          py::arg("priority") = 2)
L
Leo Chen 已提交
309
      .def("__init__", [](phi::CUDAStream &self) {
310 311
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
        int device_id = platform::GetCurrentDeviceId();
312 313 314
        auto stream_flag = phi::CUDAStream::StreamFlag::kStreamNonBlocking;
        new (&self) phi::CUDAStream(
            platform::CUDAPlace(device_id), /*priority=*/0, stream_flag);
315 316 317 318 319 320 321 322 323 324 325 326
#else
            PADDLE_THROW(platform::errors::Unavailable(
        "Class CUDAStream can only be initialized on the GPU platform."));
#endif
      });

  py::class_<paddle::platform::CudaEvent>(m, "CUDAEvent", R"DOC(
      The handle of the CUDA event.

      Parameters:
        enable_timing(bool, optional): Whether the event will measure time. Default: False.
        blocking(bool, optional): Whether the wait() func will be blocking. Default: False;
327
        interprocess(bool, optional): Whether the event can be shared between processes. Default: False.
328

329 330 331 332 333 334 335 336 337
      Examples:
        .. code-block:: python

            # required: gpu
            import paddle
            event = paddle.device.cuda.Event()

  )DOC")
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
338 339
      .def(
          "record",
L
Leo Chen 已提交
340
          [](paddle::platform::CudaEvent &self, phi::CUDAStream *stream) {
341
            if (stream == nullptr) {
L
Leo Chen 已提交
342
              stream = paddle::platform::get_current_stream(-1);
343 344 345 346
            }
            self.Record(stream->raw_stream());
          },
          R"DOC(
347 348 349 350
          Records the event in the given stream.

          Parameters:
            stream(CUDAStream, optional): The handle of CUDA stream. If None, the stream is the current stream. Default: None.
351

352 353 354 355 356 357 358
          Examples:
            .. code-block:: python

              # required: gpu
              import paddle
              event = paddle.device.cuda.Event()
              event.record()
359

360
        )DOC",
361 362 363 364 365
          py::arg("stream") = nullptr)
      .def(
          "query",
          [](paddle::platform::CudaEvent &self) { return self.Query(); },
          R"DOC(
366 367 368 369 370 371 372 373 374 375 376 377 378
          Queries the event's status.

          Returns: A boolean which indicates all work currently captured by the event has been completed.

          Examples:
            .. code-block:: python

                # required: gpu
                import paddle
                event = paddle.device.cuda.Event()
                is_done = event.query()

           )DOC")
379 380
      .def(
          "synchronize",
381 382
          [](paddle::platform::CudaEvent &self) { self.Synchronize(); },
          R"DOC(
383 384 385 386 387 388 389 390 391 392 393 394
            Waits for an event to complete.

            Examples:
              .. code-block:: python

                # required: gpu
                import paddle
                event = paddle.device.cuda.Event()
                event.synchronize()

           )DOC")
#endif
395 396
      .def(
          "__init__",
397 398 399 400
          [](paddle::platform::CudaEvent &self,
             bool enable_timing,
             bool blocking,
             bool interprocess) {
401
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
402 403 404
            unsigned int flags = platform::GenerateDeviceEventFlag(
                enable_timing, blocking, interprocess);
            new (&self) paddle::platform::CudaEvent(flags);
405
#else
406 407 408
            PADDLE_THROW(platform::errors::Unavailable(
                "Class CUDAEvent can only be initialized on the GPU "
                "platform."));
409 410

#endif
411
          },
412 413
          py::arg("enable_timing") = false,
          py::arg("blocking") = false,
414
          py::arg("interprocess") = false);
415 416 417 418
}

}  // namespace pybind
}  // namespace paddle