我一直在Linux上玩Pytorch一段时间了,最近决定尝试在我的Windows桌面上使用GPU运行更多脚本 . 自从尝试这个以来,我注意到在相同的脚本上,我的GPU执行时间和CPU执行时间之间存在巨大的性能差异,因此我的GPU显着慢于CPU . 为了说明这一点,我只是在这里找到一个教程(https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-tensors)
import torch
import datetime
print(torch.__version__)
dtype = torch.double
#device = torch.device("cpu")
device = torch.device("cuda:0")
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random input and output data
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)
# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)
start = datetime.datetime.now()
learning_rate = 1e-6
for t in range(5000):
# Forward pass: compute predicted y
h = x.mm(w1)
h_relu = h.clamp(min=0)
y_pred = h_relu.mm(w2)
# Compute and print loss
loss = (y_pred - y).pow(2).sum().item()
#print(t, loss)
# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = h_relu.t().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h < 0] = 0
grad_w1 = x.t().mm(grad_h)
# Update weights using gradient descent
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
end = datetime.datetime.now()
print(end-start)
我将Epoch的数量从500增加到5000,因为我已经读到第一次CUDA调用由于初始化而非常慢 . 但是性能问题仍然存在 .
使用 device = torch.device("cpu")
打印出的最终时间是正常的3-4秒左右,并且在大约13-15秒内执行 device = torch.device("cuda:0")
我已经以多种不同的方式重新安装了Pytorch(当然卸载以前的安装)并且问题仍然存在 . 我希望有人可以帮助我,如果我可能错过了一组(没有安装其他API /程序)或者在代码中做错了什么 .
Python:v3.6
Pytorch:v0.4.1
GPU:NVIDIA GeForce GTX 1060 6GB
任何帮助将不胜感激:slight_smile:
1 回答
主要原因是您使用的是双数据类型而不是浮点数 . GPU主要针对32位浮点数的操作进行了优化 . 如果你将你的dtype更改为torch.float,你的GPU运行应该比你的CPU运行速度更快,甚至包括像CUDA初始化这样的东西 .