cuda_streams_py.cc 13.2 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 26 27 28 29 30 31
#include "paddle/fluid/platform/event.h"
#include "paddle/fluid/platform/stream/cuda_stream.h"

namespace py = pybind11;

namespace paddle {
namespace pybind {
void BindCudaStream(py::module *m_ptr) {
  auto &m = *m_ptr;

  // Bind Methods
32 33 34
  m.def(
      "_get_current_stream",
      [](int deviceId) {
35
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
36
        return paddle::platform::stream::get_current_stream(deviceId);
37
#else
38 39 40
        PADDLE_THROW(platform::errors::Unavailable(
            "Paddle is not compiled with CUDA. Cannot visit cuda current"
            "stream."));
41
#endif
42 43
      },
      py::return_value_policy::reference);
44

45 46 47
  m.def(
      "_set_current_stream",
      [](paddle::platform::stream::CUDAStream &stream) {
48
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
49
        return paddle::platform::stream::set_current_stream(&stream);
50
#else
51 52 53
        PADDLE_THROW(platform::errors::Unavailable(
            "Paddle is not compiled with CUDA. Cannot set cuda current "
            "stream."));
54
#endif
55 56
      },
      py::return_value_policy::reference);
57

58 59 60 61 62 63 64 65 66
  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
67
    PADDLE_ENFORCE_GPU_SUCCESS(hipDeviceSynchronize());
68
#else
69
    PADDLE_ENFORCE_GPU_SUCCESS(cudaDeviceSynchronize());
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#endif
    paddle::platform::SetDeviceId(curr_device_id);
#else
    PADDLE_THROW(platform::errors::Unavailable(
        "Paddle is not compiled with CUDA. Cannot visit device synchronize."));
#endif
  });

  py::class_<paddle::platform::stream::CUDAStream>(m, "CUDAStream", R"DOC(
      The handle of the CUDA stream.

      Parameters:
        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. 

        priority(int|None, optional): The priority of stream. The priority can be 1(high) or 2(normal).
87
        If priority is None, the priority is 2(normal). Default: None. 
88 89 90 91 92 93 94 95 96 97 98 99

      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)
100 101 102 103 104 105 106
      .def(
          "wait_event",
          [](paddle::platform::stream::CUDAStream &self,
             paddle::platform::CudaEvent &event) {
            self.WaitEvent(event.GetRawCudaEvent());
          },
          R"DOC(
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
      Makes all future work submitted to stream wait for all work captured in event.

      Parameters:
        event(CUDAEvent): The event to wait on.
      
      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")
122 123 124 125 126 127 128 129 130 131
      .def(
          "wait_stream",
          [](paddle::platform::stream::CUDAStream &self,
             paddle::platform::stream::CUDAStream &stream) {
            paddle::platform::CudaEvent event;
            event.Record(stream.raw_stream());

            self.WaitEvent(event.GetRawCudaEvent());
          },
          R"DOC(
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
      Synchronizes with the given stream.

      Parameters:
        stream(CUDAStream): The stream to synchronize with.
      
      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")
147 148 149 150 151 152
      .def(
          "query",
          [](paddle::platform::stream::CUDAStream &self) {
            return self.Query();
          },
          R"DOC(
153 154 155 156 157 158 159 160 161 162 163 164 165
      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")
166 167 168 169 170 171
      .def(
          "synchronize",
          [](paddle::platform::stream::CUDAStream &self) {
            self.Synchronize();
          },
          R"DOC(
172 173 174 175 176 177 178 179 180 181 182
      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")
183 184 185 186 187 188 189 190 191 192 193
      .def(
          "record_event",
          [](paddle::platform::stream::CUDAStream &self,
             paddle::platform::CudaEvent *event) {
            if (event == nullptr) {
              event = new paddle::platform::CudaEvent();
            }
            event->Record(self.raw_stream());
            return event;
          },
          R"DOC(
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
      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.
      
      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",
212
          py::arg("event") = nullptr)
L
Leo Chen 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
      .def_property_readonly(
          "cuda_stream",
          [](paddle::platform::stream::CUDAStream &self) {
            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)
            
            ptr = ctypes.c_void_p(cuda_stream)  # convert back to void*
            print(ptr)

           )DOC")
235
#endif
236 237 238
      .def(
          "__init__",
          [](paddle::platform::stream::CUDAStream &self,
239 240
             platform::CUDAPlace *device,
             int priority) {
241
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
242 243 244 245 246 247 248 249 250 251 252 253 254 255
            if (priority != 1 && priority != 2) {
              PADDLE_THROW(platform::errors::InvalidArgument(
                  "Priority should be 1(high) or 2(normal) "));
            }
            auto prio = paddle::platform::stream::Priority(priority);
            auto stream_flag =
                paddle::platform::stream::StreamFlag::kStreamNonBlocking;

            if (device == nullptr) {
              int curr_device_id = platform::GetCurrentDeviceId();
              auto device_tmp = platform::CUDAPlace(curr_device_id);
              device = &device_tmp;
            }

256 257
            new (&self) paddle::platform::stream::CUDAStream(
                *device, prio, stream_flag);
258 259 260 261
#else
            PADDLE_THROW(platform::errors::Unavailable(
        "Class CUDAStream can only be initialized on the GPU platform."));
#endif
262
          },
263 264
          py::arg("device") = nullptr,
          py::arg("priority") = 2)
265 266
      .def(
          "__init__",
267 268
          [](paddle::platform::stream::CUDAStream &self,
             int device,
269 270 271 272 273 274 275
             int priority) {
#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) "));
            }
            auto prio = paddle::platform::stream::Priority(priority);
276 277
            auto stream_flag =
                paddle::platform::stream::StreamFlag::kStreamNonBlocking;
278

279
            int device_count = platform::GetGPUDeviceCount();
280 281 282 283 284 285
            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.",
286 287
                  device_count,
                  device));
288 289 290
            }

            new (&self) paddle::platform::stream::CUDAStream(
291
                platform::CUDAPlace(device), prio, stream_flag);
292 293 294 295 296
#else
            PADDLE_THROW(platform::errors::Unavailable(
        "Class CUDAStream can only be initialized on the GPU platform."));
#endif
          },
297 298
          py::arg("device") = -1,
          py::arg("priority") = 2)
299 300 301
      .def("__init__", [](paddle::platform::stream::CUDAStream &self) {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
        auto prio = paddle::platform::stream::Priority::kNormal;
302 303
        auto stream_flag =
            paddle::platform::stream::StreamFlag::kStreamNonBlocking;
304 305 306 307

        int device_id = platform::GetCurrentDeviceId();

        new (&self) paddle::platform::stream::CUDAStream(
308
            platform::CUDAPlace(device_id), prio, stream_flag);
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
#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;
        interprocess(bool, optional): Whether the event can be shared between processes. Defalut: False.
      
      Examples:
        .. code-block:: python

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

  )DOC")
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
332 333 334 335 336 337 338 339 340 341
      .def(
          "record",
          [](paddle::platform::CudaEvent &self,
             paddle::platform::stream::CUDAStream *stream) {
            if (stream == nullptr) {
              stream = paddle::platform::stream::get_current_stream(-1);
            }
            self.Record(stream->raw_stream());
          },
          R"DOC(
342 343 344 345 346 347 348 349 350 351 352 353 354 355
          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.
          
          Examples:
            .. code-block:: python

              # required: gpu
              import paddle
              event = paddle.device.cuda.Event()
              event.record()
    
        )DOC",
356 357 358 359 360
          py::arg("stream") = nullptr)
      .def(
          "query",
          [](paddle::platform::CudaEvent &self) { return self.Query(); },
          R"DOC(
361 362 363 364 365 366 367 368 369 370 371 372 373
          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")
374 375
      .def(
          "synchronize",
376 377
          [](paddle::platform::CudaEvent &self) { self.Synchronize(); },
          R"DOC(
378 379 380 381 382 383 384 385 386 387 388 389
            Waits for an event to complete.

            Examples:
              .. code-block:: python

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

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

#endif
406
          },
407 408
          py::arg("enable_timing") = false,
          py::arg("blocking") = false,
409
          py::arg("interprocess") = false);
410 411 412 413 414
}

}  // namespace pybind

}  // namespace paddle