首页 > 解决方案 > 如何将 cuda 驱动程序 api 与 cuda 运行时 api 混合使用?

问题描述

cuda 文档中可以看出:

  1. 如果通过驱动程序 API 创建上下文并使其成为当前上下文,则后续运行时调用将获取此上下文,而不是创建新上下文。
  2. 如果运行时已初始化(如 CUDA 运行时中提到的那样),cuCtxGetCurrent() 可用于检索在初始化期间创建的上下文。后续驱动程序 API 调用可以使用此上下文。

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

但是,我想通过第二个选项工作。那就是先初始化运行时,然后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)" 

标签: c++cuda

解决方案


您收到错误的原因是,至少在这种情况下,当您尝试使用驱动程序 API 绑定到上下文时,没有发生延迟运行时 API 上下文创建。确保您获得使用运行时创建的上下文的规范方法一直是

cudaSetDevice(current_device);
cudaFree(0);

文档在这一点上一直模棱两可,语义似乎随着时间的推移发生了微妙的变化,但这种调用一直对我有用。


推荐阅读