【Tensorflow】gpu&pytorch(GPU) 安装、使用教程

想要用gpu加速得先安装CUDA和cuDNN。
NVIDIA的显卡驱动程序和CUDA完全是两个不同的概念哦!CUDA是NVIDIA推出的用于自家GPU的并行计算框架,也就是说CUDA只能在NVIDIA的GPU上运行,而且只有当要解决的计算问题是可以大量并行计算的时候才能发挥CUDA的作用。
CUDA的本质是一个工具包(ToolKit);但是二者虽然不一样的。

1.到官网查找版本关系

pytorch-cuda版本对应

torch 1.1.0 -> CUDA 9.2
torch 1.2.0 -> CUDA 10.0
torch 1.3.0 -> CUDA 10.1
torch 1.4.0 -> CUDA 10.2
torch 1.5.0 -> CUDA 10.2

tensorflow-cuda版本对应

https://tensorflow.google.cn/install/source_windows

确定好要下载的cuda版本后——

2.下载安装CUDA

下载网址:https://developer.nvidia.com/cuda-downloads

下载完之后打开安装,一路确认到底
在这里插入图片描述

3.下载安装cuDNN

下载地址:https://developer.nvidia.com/rdp/cudnn-archive
cuDNN的版本是根据CUDA来选择的,如果我的cuda是10.0,那么选择这个:
在这里插入图片描述
下载后将其解压缩
在这里插入图片描述

​在C盘根目录下新建个tools文件夹,将解压后的“cuda”文件夹放入其中

4.添加环境变量

搜索“高级系统设置”:
进入系统变量的“Path”,添加"c:\tools\cuda\bin"与”C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin”后点击确认

在这里插入图片描述

5.查看安装好的cuda版本以及显卡

打开命令——》输入nvidia-smi
在这里插入图片描述

6.检查能否运行:

tensorflow:
查看gpu信息:
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

pytorch:

import torch
print(torch.cuda.is_available())
# 结果
#>>>True

7.torch.backends.cudnn.benchmark加速

torch.backends.cudnn.benchmark 这个 GPU 相关的 flag,可能有人会感到比较陌生。在一般场景下,只要简单地在 PyTorch 程序开头将其值设置为 True,就可以大大提升卷积神经网络的运行速度。
设置 torch.backends.cudnn.benchmark=True 将会让程序在开始时花费一点额外时间,为整个网络的每个卷积层搜索最适合它的卷积实现算法,进而实现网络的加速。适用场景是网络结构固定(不是动态变化的),网络的输入形状(包括 batch size,图片大小,输入的通道)是不变的,其实也就是一般情况下都比较适用。反之,如果卷积层的设置一直变化,将会导致程序不停地做优化,反而会耗费更多的时间。
这行代码要加在哪里?:

if torch.cuda.is_available():
    cudnn.benchmark = True
	...

做了个小实验,分别计算了用CPU、GPU+benchmark、GPU不加benchmark三种情况下训练一个 网络的时间(代码在附录):

7.1 使用CPU

out:

Warning! Using CPU.
iteration 0 time: 6.13
iteration 1 time: 5.55
iteration 2 time: 5.24
iteration 3 time: 5.30
iteration 4 time: 5.27
iteration 5 time: 5.19
iteration 6 time: 5.20
iteration 7 time: 5.25
iteration 8 time: 5.23
iteration 9 time: 5.18

7.2 GPU

out:

Using GPU:  GeForce GTX 1050
iteration 0 time: 1.18
iteration 1 time: 0.33
iteration 2 time: 0.27
iteration 3 time: 0.26
iteration 4 time: 0.27
iteration 5 time: 0.27
iteration 6 time: 0.27
iteration 7 time: 0.28
iteration 8 time: 0.27
iteration 9 time: 0.27

7.3 GPU+benchmark

out:

Using GPU:  GeForce GTX 1050
Using cudnn.benchmark.
iteration 0 time: 1.36
iteration 1 time: 0.23
iteration 2 time: 0.26
iteration 3 time: 0.26
iteration 4 time: 0.26
iteration 5 time: 0.26
iteration 6 time: 0.26
iteration 7 time: 0.27
iteration 8 time: 0.26
iteration 9 time: 0.26

好像确实快了一点~

8 释放GPU缓存

在这里插入图片描述
当程序运行后,就算运行停止了,GPU占比还会很高,就像左边那一段,如果我要进行新的调试。就会报错,说GPU内存不够了,因此使用一行代码就可以清除缓存了:

torch.cuda.empty_cache()

就变成右边那一段,可以看到从80%左右降到50%了

参考:
https://www.jb51.net/article/192506.htm
http://blog.sina.com.cn/s/blog_14935c5880102wu86.html
torch.backends.cudnn.benchmark加速

附录:

7.torch.backends.cudnn.benchmark加速测试代码:

import time
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
import numpy as np

parser = argparse.ArgumentParser(description='Test for cudnn.benchmark')
parser.add_argument('--run_num', type=int, default=10, help='number of runs')
parser.add_argument('--batch_size', type=int, default=8, help='batch size')
parser.add_argument('--use_gpu', dest='use_gpu', action='store_true', default=False, help='use gpu')
parser.add_argument('--use_benchmark', dest='use_benchmark', action='store_true', default=False, help='use benchmark')
parser.add_argument('--exp_name', type=str, default='cudnn_test', help='output file name')
args = parser.parse_args()

if args.use_gpu and torch.cuda.is_available():
    device = torch.device('cuda')
    print('Using GPU: ', torch.cuda.get_device_name(0))
    if args.use_benchmark:
        torch.backends.cudnn.benchmark = True
        print('Using cudnn.benchmark.')
else:
    device = torch.device('cpu')
    print('Warning! Using CPU.')

images = torch.randn(args.batch_size, 3, 224, 224)
labels = torch.empty(args.batch_size, dtype=torch.long).random_(1000)

model = models.resnet101()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
criterion = nn.CrossEntropyLoss()

model = model.to(device)
images = images.to(device)
labels = labels.to(device)

time_list = []

model.train()
for itr in range(args.run_num):
    start = time.time()
    outputs = model(images)

    loss = criterion(outputs, labels)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    end = time.time()
    print('iteration %d time: %.2f' % (itr, end-start))
    time_list.append(end-start)

with open(args.exp_name, 'w') as f:
    f.write('Device: ' + device.type + '\n')
    f.write('Use CUDNN Benchmark: ' + str(torch.backends.cudnn.benchmark) + '\n')
    f.write('Number of runs: ' + str(args.run_num) + '\n')
    f.write('Batch size: ' + str(args.batch_size) + '\n')
    f.write('Average time: %.2f s\n\n' % (np.mean(time_list)))

    for each in time_list:
        f.write(str(each))
        f.write('\n')
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一起来学深度学习鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值