背景知识

1、GPU的并行计算能力,在过去几年里恰当地满足了深度学习的需求。在训练强化学习模型时,为了提供更好地算力和训练时间,因此需要使用GPU。
2、CUDA:是Nvidia推出的只能用于自家GPU的并行计算框架。只有安装这个框架才能够进行复杂的并行计算。主流的深度学习框架也都是基于CUDA进行GPU并行加速的,几乎无一例外。还有一个叫做cudnn,是针对深度卷积神经网络的加速库。

本文主要讲一下配置这个环境的心路历程,后面再遇到类似的问题可以回到这篇进行查阅。

一、首先安装Anaconda(含解释器python(base)、numpy等一系列包)。

二、安装编译器Pycharm。

以上1和2的安装就不再赘述。

三、查看自己的cuda是否可用。

这块主要是版本一定要对应好,否则一直显示无可用Cuda。

python
import torch
print(torch.cuda.is_available())
False
print(torch.cuda.device_count())
0

第一次查看后为False,而且可用的cuda数是0,查找原因后发现是因为安装的cuda版本和已有torch版本不对应。

于是有了接下来的操作:
1、查看之前的list包,将之前的torch和torchVision进行卸载

conda list
pip uninstall  包名

2、然后查找自己的Cuda版本,win10电脑中在搜索栏检索:Nvidia控制面板——帮助——系统信息——组件。可以发现我的Cuda版本为11.6。

如何在python使用cuda python中cuda_Cuda


3、我的Python版本为3.8,系统为windows系统,对应的Cuda应使用11.3(我也不知道为啥要用11.3,明明Cuda的版本是11.6,此前用11.6的亲测后显示无可用的cuda,看到一个博主写的是用11.3,自己尝试后发现确实不报问题,于是就果断下载了11.3)。

下载torch和torchVision GPU版本的地址如下:

https://download.pytorch.org/whl/cu113/torch_stable.html

使用Ctrl+F搜索113,直接定位到和自己版本对用的torch(2.2GB)和torchVision(6.8MB)的whl文件,下载到本地(建议用外网下载,否则比较慢)。

如何在python使用cuda python中cuda_如何在python使用cuda_02


如何在python使用cuda python中cuda_python_03


4、安装以上两个whl文件。

安装使用 pip install 文件路径 即可。如下:

pip install C:/Users/XXXXX/Downloads/torch-1.10.1+cu113-cp38-cp38-win_amd64.whl
pip install C:/Users/XXXXX/Downloads/torchvision-0.13.0+cu113-cp38-cp38-win_amd64.whl

5、再一次在python解释器下查看cuda是否可用。

python
import torch
print(torch.cuda.is_available())
print(torch.cuda.device_count())

这次显示如下:

如何在python使用cuda python中cuda_python_04


说明cuda和torch版本对应了。

四、训练模型

训练模型时发现开始可以正常训练,但是最终报错如下:

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.


查阅资料后发现是因为自己的anaconda3文件夹底下有多个libiomp5md.dll文件导致的,删除F:\Anaconda3\Library\bin路径下的这个libiomp5md.dll文件,其他的不用管。删除后还有多个libiomp5md.dll文件,如图所示,但是再次训练时已经不报错了。

如何在python使用cuda python中cuda_python_05


于是就可以正常的训练了。