cuda_stream.cc 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* Copyright (c) 2020 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. */

#include "paddle/fluid/platform/stream/cuda_stream.h"
#include "paddle/fluid/platform/cuda_device_guard.h"
#include "paddle/fluid/platform/enforce.h"

namespace paddle {
namespace platform {
namespace stream {

constexpr unsigned int kDefaultFlag = cudaStreamDefault;

bool CUDAStream::Init(const Place& place, const enum Priority& priority) {
  PADDLE_ENFORCE_EQ(is_gpu_place(place), true,
                    platform::errors::InvalidArgument(
                        "Cuda stream must be created using cuda place."));
  place_ = place;
  CUDADeviceGuard guard(boost::get<CUDAPlace>(place_).device);
  if (priority == Priority::kHigh) {
    PADDLE_ENFORCE_CUDA_SUCCESS(
33
        cudaStreamCreateWithPriority(&stream_, kDefaultFlag, -1));
34 35
  } else if (priority == Priority::kNormal) {
    PADDLE_ENFORCE_CUDA_SUCCESS(
36
        cudaStreamCreateWithPriority(&stream_, kDefaultFlag, 0));
37 38 39 40 41 42 43 44 45 46 47 48
  }
  callback_manager_.reset(new StreamCallbackManager(stream_));
  VLOG(3) << "CUDAStream Init stream: " << stream_
          << ", priority: " << static_cast<int>(priority);
  return true;
}

void CUDAStream::Destroy() {
  CUDADeviceGuard guard(boost::get<CUDAPlace>(place_).device);
  Wait();
  WaitCallback();
  if (stream_) {
49
    PADDLE_ENFORCE_CUDA_SUCCESS(cudaStreamDestroy(stream_));
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  }
  stream_ = nullptr;
}

void CUDAStream::Wait() const {
  cudaError_t e_sync = cudaSuccess;
#if !defined(_WIN32)
  e_sync = cudaStreamSynchronize(stream_);
#else
  while (e_sync = cudaStreamQuery(stream_)) {
    if (e_sync == cudaErrorNotReady) continue;
    break;
  }
#endif

65
  PADDLE_ENFORCE_CUDA_SUCCESS(e_sync);
66 67 68 69 70
}

}  // namespace stream
}  // namespace platform
}  // namespace paddle