听说可以免费薅 colab 的 GPU 运行 CUDA 代码,这两天试了一下,还真是可以。但是要顺利的用起来还是遇到了一些问题,今天这篇博客就是分享一下我遇到的问题,以及如何正确的用起来。
首先,按照其他教程里边的用法把 GPU 选好(写这篇博客的时候 GPU 是 T4),把 hello world 代码写好,这部分其他教程分享得很多了,我就不多废话了。
!nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2024 NVIDIA Corporation
Built on Thu_Jun__6_02:18:23_PDT_2024
Cuda compilation tools, release 12.5, V12.5.82
Build cuda_12.5.r12.5/compiler.34385749_0
!pip install nvcc4jupyter
Collecting nvcc4jupyter
Downloading nvcc4jupyter-1.2.1-py3-none-any.whl.metadata (5.1 kB)
Downloading nvcc4jupyter-1.2.1-py3-none-any.whl (10 kB)
Installing collected packages: nvcc4jupyter
Successfully installed nvcc4jupyter-1.2.1
%load_ext nvcc4jupyter
Detected platform "Colab". Running its setup...
Source files will be saved in "/tmp/tmppm3c_j8h".
%%cuda
#include <stdio.h>
__global__ void hellocuda() {
printf("hello cuda \n");
}
int main() {
hellocuda<<<1, 32>>>();
cudaDeviceSynchronize();
return 0;
}
这里在运行的时候就出问题了,在我的版本是没有任何输出的。
然后我就加了一句代码尝试获取一下 cuda 的报错:
int main() {
hellocuda<<<1, 32>>>();
cudaDeviceSynchronize();
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
return 0;
}
再运行,就看到了下面的错误信息:
the provided PTX was compiled with an unsupported toolchain.
经过了一些调查,发现可能当前 GPU 架构与当前 CUDA 的版本不匹配。
修改方法就是:CUDA 代码写到 .cu 文件里,然后用 nvcc 手动指定 sm 版本,再运行就可以正常执行了。
%%writefile test.cu
#include <stdio.h>
__global__ void hellocuda() {
printf("hello cuda \n");
}
int main() {
hellocuda<<<1, 32>>>();
cudaDeviceSynchronize();
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
return 0;
}
!nvcc test.cu -arch=sm_75
!./a.out
hello cuda
hello cuda
hello cuda
hello cuda
hello cuda
hello cuda
hello cuda
……
那么还有一个问题需要解决一下,如何确定 sm 的版本是多少呢?
首先要根据 GPU 的型号确定 GPU 的架构,比如 T4 GPU 是 Turing 架构,然后去查一下 Turing 架构对应的 sm 版本就可以了。可以在这个地址查(https://arnon.dk/matching-sm-architectures-arch-and-gencode-for-various-nvidia-cards/),也可以去问问 AI。
最后 AI 给了我一段代码,也可以用来确定 sm 版本:
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
运行这段代码的输出中会有这样一句:
physical_device_desc: "device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5"
这里的 7.5 就是当前设备的 sm 版本。
参考资料:
https://stackoverflow.com/questions/63675040/cuda-11-kernel-doesnt-run
https://arnon.dk/matching-sm-architectures-arch-and-gencode-for-various-nvidia-cards/