pytorch允许把在GPU上训练的模型加载到CPU上,也允许把在CPU上训练的模型加载到GPU上。
在Pytorch中,只要在输入,输出,模型等后加.cuda()即可将模型由cpu上的运算调到gpu上运算。
首先需要确定自己的pytorch版本能否进行gpu计算。
print(torch.cuda.is_available())
如果结果是True,则可以进行gpu计算,如果是False,就需要安装gpu版本的torch或是CUDA了。还可以通过来识别可以使用的gpu个数。
print(torch.cuda.device_count())
将CPU上的Tensor或变量放到GPU上
x.cuda()
将GPU上的Tensor或Variable放到CPU上
x.data.cpu().numpy()
将CPU上的神经网络模型放到GPU上
net= model()
net.cuda()
深度学习中我们默认使用的是CPU,如果我们要使用GPU,需要使用.cuda将计算或者数据从CPU移动至GPU,
如果当我们需要在CPU上进行运算时,比如使用plt可视化绘图, 我们可以使用.cpu将计算或者数据转移至CPU.
#!/usr/bin/python# -*- coding: UTF-8 -*-import torchfrom torch.autogradimport Variable# 将变量或者数据移到GPU
gpu_info= Variable(torch.randn(3,3)).cuda()# 将变量或者数据移到CPU
cpu_info= gpu_info.cpu()
torch.cuda会记录当前选择的GPU,并且分配的所有CUDA张量将在上面创建。可以使用torch.cuda.device上下文管理器更改所选设备。
但是,一旦张量被分配,您可以直接对其进行操作,而不考虑所选择的设备,结果将始终放在与张量相同的设备上。
默认情况下,不支持跨GPU操作,唯一的例外是copy_()。 除非启用对等存储器访问,否则对分布不同设备上的张量任何启动操作的尝试都将会引发错误。
下面你可以找到一个展示如下的小例子:
x= torch.cuda.FloatTensor(1)# x.get_device() == 0
y= torch.FloatTensor(1).cuda()# y.get_device() == 0with torch.cuda.device(1):# allocates a tensor on GPU 1
a= torch.cuda.FloatTensor(1)# transfers a tensor from CPU to GPU 1
b= torch.FloatTensor(1).cuda()# a.get_device() == b.get_device() == 1
c= a+ b# c.get_device() == 1
z= x+ y# z.get_device() == 0# even within a context, you can give a GPU id to the .cuda call
d= torch.randn(2).cuda(2)# d.get_device() == 2
未完待续。。。。。。。。。。。。。。