首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么毕火炬(CUDA)在GPU上运行缓慢?

为什么毕火炬(CUDA)在GPU上运行缓慢?
EN

Stack Overflow用户
提问于 2018-09-22 16:15:40
回答 2查看 10.7K关注 0票数 3

我已经在Linux上玩了一段时间了,最近我决定尝试在我的Windows桌面上使用我的GPU运行更多的脚本。自从尝试之后,我注意到在相同的脚本上,我的GPU执行时间和我的CPU执行时间之间存在着巨大的性能差异,因此我的GPU比CPU慢得多。为了说明这一点,我只是在这里找到了一个教程程序(examples.html#pytorch-tensors)

代码语言:javascript
复制
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秒左右执行。

我已经重新安装了许多不同的方式(当然,卸载之前的安装),问题仍然存在。我希望有人能帮助我,如果我可能错过了一套(没有安装其他API/程序),或者代码中做错了什么。

Python: v3.6

火炬:v0.4.1

GPU: NVIDIA GeForce GTX 1060 6GB

如果能提供任何帮助,:slight_smile将不胜感激:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-07-02 09:31:03

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

**

代码语言:javascript
复制
N, D_in, H, D_out = 128, 1000, 500, 10
dtype = torch.float32

**

票数 2
EN

Stack Overflow用户

发布于 2018-09-23 19:00:35

主要原因是您使用的是双数据类型,而不是浮点数。GPU大多是针对32位浮点数的操作而优化的.如果您将dtype更改为torch.float,您的GPU运行应该比您的CPU运行更快,甚至包括CUDA初始化之类的内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52458508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档