gpt4 book ai didi

c++ - 如何将 cuda 驱动程序 api 与 cuda 运行时 api 混合使用?

转载 作者:行者123 更新时间:2023-12-01 14:48:46 25 4
gpt4 key购买 nike

来自 cuda document它指出:

  1. 如果上下文通过驱动程序 API 创建并成为当前上下文,则后续运行时调用将选择此上下文而不是创建新上下文。
  2. 如果运行时已初始化(隐式如 CUDA 运行时中所述),cuCtxGetCurrent() 可用于检索在初始化期间创建的上下文。此上下文可由后续驱动程序 API 调用使用。

我可以使第一点工作。我可以从 cuda 驱动程序创建上下文。然后我可以在不调用 cudaSetDevice() 的情况下使用 cuda 运行时函数,这隐式地创建了一个新的主上下文。

但是,我想通过第二个选项工作。即首先初始化运行时,然后执行 cuCtxGetCurrent() 并在 cuda 驱动程序 api 中使用它。这根本不起作用。我总是提出错误,说上下文已被破坏或无效。我做错了什么?

这是我的示例代码:

#define CUDA_DRIVER_API
#include <cuda.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <iostream>
CUcontext check_current_ctx()
{
CUcontext context{0};
unsigned int api_ver;
checkCudaErrors(cuCtxGetCurrent(&context));
fprintf(stdout, "current context=%p\n", context);
checkCudaErrors( cuCtxGetApiVersion(context, &api_ver));
fprintf(stdout, "current context api version = %d\n", api_ver);
return context;
}
auto inital_runtime_context()
{
int current_device = 0;
int device_count = 0;
int devices_prohibited = 0;
CUcontext current_ctx{0};

cudaDeviceProp deviceProp;
checkCudaErrors(cudaGetDeviceCount(&device_count));;
if (device_count == 0) {
fprintf(stderr, "CUDA error: no devices supporting CUDA.\n");
exit(EXIT_FAILURE);
}

// Find the GPU which is selected by Vulkan
while (current_device < device_count) {
cudaGetDeviceProperties(&deviceProp, current_device);
if ((deviceProp.computeMode != cudaComputeModeProhibited)) {
checkCudaErrors(cudaSetDevice(current_device));
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, current_device));
printf("GPU Device %d: \"%s\" with compute capability %d.%d\n\n",
current_device, deviceProp.name, deviceProp.major,
deviceProp.minor);
CUcontext current_ctx;
cuCtxGetCurrent(&current_ctx);
std::cout << "current_ctx=" << current_ctx << "\n";
return current_device;

} else {
devices_prohibited++;
}

current_device++;
}

if (devices_prohibited == device_count) {
fprintf(stderr,
"CUDA error:"
" No Vulkan-CUDA Interop capable GPU found.\n");
exit(EXIT_FAILURE);
}

return -1;
}
void test_runtime_driver_op()
{
inital_runtime_context();
check_current_ctx();

}

报告:

GPU Device 0: "GeForce RTX ..." with compute capability 7.5

current_ctx=0x6eb220
current context=0x6eb220
CUDA error at ... code=201(CUDA_ERROR_INVALID_CONTEXT) "cuCtxGetApiVersion(context, &api_ver)"

最佳答案

您收到错误的原因是,至少在这种情况下,当您尝试使用驱动程序 API 绑定(bind)到上下文时,尚未创建惰性运行时 API 上下文。确保您获得使用运行时创建的上下文的规范方法始终是

cudaSetDevice(current_device);
cudaFree(0);

文档在这一点上一直含糊不清,语义似乎随着时间的推移发生了微妙的变化,但这种调用对我来说一直有效。

关于c++ - 如何将 cuda 驱动程序 api 与 cuda 运行时 api 混合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com