计算设备
PyTorch可以指定用来存储和计算的设备,如使用内存的CPU或者使用显存的GPU。默认情况下,PyTorch会将数据创建在内存,然后利用CPU来计算。
讲真,到现在为止还没拿自己显卡训练过实际项目
import torchfrom torch import nnprint(torch.cuda.device_count())print(torch.cuda.current_device())print(torch.cuda.get_device_name(0))结果:10GeForce RTX 2060
Tensor的GPU计算
默认情况下,
Tensor会被存在内存上。因此,之前我们每次打印Tensor的时候看不到GPU相关标识。使用.cuda()可以将CPU上的Tensor转换(复制)到GPU上。如果有多块GPU,我们用.cuda(i)来表示第 i 块GPU及相应的显存(i从0开始)且cuda(0)和cuda()等价。
x = torch.tensor([1, 2, 3])x = x.cuda()print(x)# 也可以直接指定存储tensor的设备x = torch.tensor([1, 2, 3], device='cuda')print(x)# 通过divice属性查看该Tensor所在的设备print(x.device)结果:tensor([1, 2, 3], device='cuda:0')tensor([1, 2, 3], device='cuda:0')cuda:0
我们还可以使用Tensor.to(device)方法,将Tensor转移到其他设备上:
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')x = torch.tensor([1, 2, 3], device=device)# orx = torch.tensor([1, 2, 3]).to(device)print(x)y = x**2print(y)结果:tensor([1, 2, 3], device='cuda:0')tensor([1, 4, 9], device='cuda:0')
可以发现,如果对在GPU上的数据进行运算,那么结果还是存放在GPU上。而且要注意,存储在不同位置中的数据是不可以直接进行计算的。
模型的GPU运算
同
Tensor类似,PyTorch模型也可以通过.cuda转换到GPU上。我们可以通过检查模型的参数的device属性来查看存放模型的设备。
net = nn.Linear(3, 1)print(list(net.parameters()))print(list(net.parameters())[0].device)结果:tensor([[-0.0826, 0.4849, 0.1278]], requires_grad=True), Parameter containing:tensor([-0.5701], requires_grad=True)]cpu
同样的,我么需要保证模型输入的
Tensor和模型都在同一设备上,否则会报错。转换到GPU上:
net.cuda()print(list(net.parameters())[0].device)print(net(torch.rand(3, 3).cuda()))结果:cuda:0
