使用VS代码调试CUDA内核



我正在尝试在VS Code上调试CUDA应用程序。

配置:

  • Ubuntu 20.04
  • VSCode 1.56.2
  • 库达11.3
  • gcc/g++9.3

为此,我有以下(最新的(扩展:

  • C/C++
  • Nsight Visual Studio代码版

我编译/运行程序没有问题。然而,当我进行调试时,我可以在CPU端正确使用调试器,但不能在GPU端正确使用。事实上,当我试图在内核中的任何地方添加断点时,运行程序总是将断点移到右括号,我看不到变量。

以下是文件:

添加.cu

#include <iostream>
#include <math.h>
// Kernel function to add the elements of two arrays
__global__
void add(float *x, float *y)
{
y[blockIdx.x] = x[blockIdx.x] + y[blockIdx.x];
}
int main(void)
{
const int N = 1<<20;
float *x, *y;
// Allocate Unified Memory – accessible from CPU or GPU
cudaMallocManaged(&x, N*sizeof(float));
cudaMallocManaged(&y, N*sizeof(float));
// initialize x and y arrays on the host
for (int i = 0; i < N; i++) {
x[i] = 1.0f;
y[i] = 2.0f;
}
// Run kernel on 1M elements on the GPU
add<<<N, 1>>>(x, y);
// Wait for GPU to finish before accessing on host
cudaDeviceSynchronize();
// Check for errors (all values should be 3.0f)
float maxError = 0.0f;
for (int i = 0; i < N; i++)
maxError = fmax(maxError, fabs(y[i]-3.0f));
std::cout << "Max error: " << maxError << std::endl;
// Free memory
cudaFree(x);
cudaFree(y);

return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
# set the project name
project(add CUDA)
# add the executable
add_executable(add add.cu)

.vscode/launch.json

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "CUDA C++: Launch",
"type": "cuda-gdb",
"request": "launch",
"program": "${workspaceFolder}/build/add"
}
]
}

我是这样编译的:

mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
cmake --build .

我尝试的每个程序在任何内核断点上都做完全相同的事情。

我在这里想念什么?

我最终解决了这个问题,在cmake中处于调试模式时强制使用-G标志,在add_executable之后添加以下行:

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_options(add PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-G>)
endif()

有了这个,设备上的调试就可以工作了。

感谢@RobertCrovella的提示。

Benjamin的回答有一个技术问题:对于多配置生成器,CMAKE_BUILD_TYPE没有意义。处理多重配置的正确方法是使用$<CONFIG:cfgs>生成器表达式。我认为修改后的答案是这样的:

target_compile_options(my_target PRIVATE "$<$<AND:$<CONFIG:Debug,RelWithDebInfo>,$<COMPILE_LANGUAGE:CUDA>>:-G>")

最新更新