Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C API: Cache CUDA availability so it's not re-evaluated every API call #10801

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions src/c_api/c_api.cu
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,14 @@
#include <nccl.h>
#endif

#include <atomic>

namespace xgboost {

namespace {
std::atomic_bool MIGHT_HAVE_CUDA(true);
}

void XGBBuildInfoDevice(Json *p_info) {
auto &info = *p_info;

Expand Down Expand Up @@ -59,15 +66,27 @@ void XGBBuildInfoDevice(Json *p_info) {
}

void XGBoostAPIGuard::SetGPUAttribute() {
// Not calling `safe_cuda` to avoid unnecessary exception handling overhead.
// If errors, do nothing, assuming running on CPU only machine.
cudaGetDevice(&device_id_);
try {
if (MIGHT_HAVE_CUDA.load(std::memory_order_relaxed)) {
// Not calling `safe_cuda` to avoid unnecessary exception handling overhead.
// If errors, do nothing, assuming running on CPU only machine.
cudaGetDevice(&device_id_);
}
} catch (dmlc::Error const&) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this error being raised if safe_cuda is not used?

MIGHT_HAVE_CUDA.store(false, std::memory_order_relaxed);
}
}

void XGBoostAPIGuard::RestoreGPUAttribute() {
// Not calling `safe_cuda` to avoid unnecessary exception handling overhead.
// If errors, do nothing, assuming running on CPU only machine.
cudaSetDevice(device_id_);
try {
if (MIGHT_HAVE_CUDA.load(std::memory_order_relaxed)) {
// Not calling `safe_cuda` to avoid unnecessary exception handling overhead.
// If errors, do nothing, assuming running on CPU only machine.
cudaSetDevice(device_id_);
}
} catch (dmlc::Error const&) {
MIGHT_HAVE_CUDA.store(false, std::memory_order_relaxed);
}
}

void CopyGradientFromCUDAArrays(Context const *ctx, ArrayInterface<2, false> const &grad,
Expand Down
Loading