PyTorch可以指定用来存储和计算的设备,如使用内存的CPU或者使用显存的GPU。默认情况下,PyTorch会将数据创建在内存,然后利用CPU来计算。
# 用torch.cuda.is_available()查看GPU是否可用:
import torch
from torch import nn
torch.cuda.is_available()
True
# 查看GPU数量
torch.cuda.device_count()
1
# 查看当前GPU索引号,索引号从0开始:
torch.cuda.current_device()
0
# 根据索引号查看GPU名字:
torch.cuda.get_device_name(0)
'GeForce GTX 950M'
# 使用.cuda()可以将CPU上的Tensor转换(复制)到GPU上。
# 如果有多块GPU,我们用.cuda(i)来表示第 i 块GPU及相应的显存(i从0开始)且cuda(0)和cuda()等价
x = torch.rand(1, 5)
x = x.cuda(0)
x
tensor([[0.6288, 0.9454, 0.9990, 0.3611, 0.8903]], device='cuda:0')
# 可以通过Tensor的device属性来查看该Tensor所在的设备。
x.device
device(type='cuda', index=0)
# 可以直接在创建tensor时指定设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
x = torch.tensor([1, 2, 3], device=device)
# or
x = torch.tensor([1, 2, 3]).to(device)
x
tensor([1, 2, 3], device='cuda:0')
如果对在GPU上的数据进行运算,那么结果还是存放在GPU上。
需要注意的是,存储在不同位置中的数据是不可以直接进行计算的。
即存放在CPU上的数据不可以直接与存放在GPU上的数据进行运算,位于不同GPU上的数据也是不能直接进行计算的。
y = x**2
y
tensor([1, 4, 9], device='cuda:0')
z = y + x.cpu()
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
in
----> 1 z = y + x.cpu()
RuntimeError: expected device cuda:0 but got device cpu
# 可以通过检查模型的参数的device属性来查看存放模型的设备
net = nn.Linear(3,1)
list(net.parameters())[0].device
device(type='cpu')
net.cuda()
list(net.parameters())[0].device
device(type='cuda', index=0)
# 需要保证模型输入的Tensor和模型都在同一设备上,否则会报错
x = torch.rand(1,3)
net(x)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
in
1 # 需要保证模型输入的Tensor和模型都在同一设备上,否则会报错
2 x = torch.rand(1,3)
----> 3 net(x)
F:\Anaconda\envs\pytorch\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
548 result = self._slow_forward(*input, **kwargs)
549 else:
--> 550 result = self.forward(*input, **kwargs)
551 for hook in self._forward_hooks.values():
552 hook_result = hook(self, input, result)
F:\Anaconda\envs\pytorch\lib\site-packages\torch\nn\modules\linear.py in forward(self, input)
85
86 def forward(self, input):
---> 87 return F.linear(input, self.weight, self.bias)
88
89 def extra_repr(self):
F:\Anaconda\envs\pytorch\lib\site-packages\torch\nn\functional.py in linear(input, weight, bias)
1608 if input.dim() == 2 and bias is not None:
1609 # fused op is marginally faster
-> 1610 ret = torch.addmm(bias, input, weight.t())
1611 else:
1612 output = input.matmul(weight.t())
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat1' in call to _th_addmm
x = torch.rand(1,3).cuda()
net(x)
tensor([[-0.0099]], device='cuda:0', grad_fn=)
参考原文
欢迎关注【OAOA】