为什么Pytorch(CUDA)在GPU上运行缓慢

时间:2018-09-22 16:15:41

标签: python machine-learning pytorch

我在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秒左右,而device = torch.device("cuda:0")的执行时间为13-15秒左右

我以多种不同的方式重新安装了Pytorch(当然,卸载了先前的安装),问题仍然存在。如果我可能错过了一套(未安装其他API /程序)或代码做错了事,我希望有人能为我提供帮助。

Python:v3.6

Pytorch:v0.4.1

GPU:NVIDIA GeForce GTX 1060 6GB

任何帮助将不胜感激:slight_smile:

2 个答案:

答案 0 :(得分:2)

主要原因是您使用的是double数据类型而不是float。 GPU主要针对32位浮点数进行了优化。如果将dtype更改为torch.float,则即使包括CUDA初始化之类的内容,GPU的运行速度也应比CPU的运行速度快。

答案 1 :(得分:1)

以较小的批处理量运行时,在gpu上运行可能会很昂贵。如果将更多数据放入gpu,这意味着增加批处理大小,则可以观察到数据显着增加。是的,在float32上,gpu的运行效果比double更好。 试试这个

**

N, D_in, H, D_out = 128, 1000, 500, 10
dtype = torch.float32

**