注意:30系列显卡只支持CUDA11.0及以上版本加速,因此本文CUDA选择v11.5
软件包搭配:win11 + RTX3060 + CUDA=11.5 + CuDnn=8.3.2 + python=3.10.14 + pytorch=1.12.1
0. CUDA及CuDNN安装省略
1. 先创建一个环境
conda create -n Pytorch_0 python=3.6
创建成功,如下:
2. 安装对应版本的Pytorch,代码:
conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=11.3 -c pytorch
结果显示,Python版本不合适(本版本的Pytorch,需要python=3.10-3.11版本之间)
重新安装其他版本的python
conda install python=3.10
过程如下:
更新python版本之后,再次安装:
conda install pytorch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1 cudatoolkit=11.3 -c pytorch
结果显示安装成功:
3. 测试pytorch是否安装成功
在Pycharm中应用此环境
测试代码:
import torch
flag = torch.cuda.is_available()
if flag:
print("CUDA可使用")
else:
print("CUDA不可用")
ngpu= 1
# Decide which device we want to run on
device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu")
print("驱动为:",device)
print("GPU型号: ",torch.cuda.get_device_name(0))
结果显示,pytorch可以正常使用:
4. 测试性能
import time
import torch
# 测试gpu计算耗时
A = torch.ones(5000, 5000).to('cuda')
B = torch.ones(5000, 5000).to('cuda')
startTime2 = time.time()
for i in range(100):
C = torch.matmul(A, B)
endTime2 = time.time()
print('gpu计算总时长:', round((endTime2 - startTime2) * 1000, 2), 'ms')
# 测试cpu计算耗时
A = torch.ones(5000, 5000)
B = torch.ones(5000, 5000)
startTime1 = time.time()
for i in range(100):
C = torch.matmul(A, B)
endTime1 = time.time()
print('cpu计算总时长:', round((endTime1 - startTime1) * 1000, 2), 'ms')
结果显示:
证明通过GPU计算实现加速。