【问题标题】:Why would Pytorch (CUDA) be running slow on GPU为什么 Pytorch (CUDA) 在 GPU 上运行缓慢
【发布时间】:2019-02-26 17:39:59
【问题描述】:

我在 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:

【问题讨论】:

标签: python machine-learning pytorch


【解决方案1】:

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

【讨论】:

  • 这确实极大地提高了网络的性能,尽管它并没有使 cuda 比我的 cpu 快。实际上使 cuda 更快的改进是大幅增加了网络的规模。我添加了两个更大的层,这需要提高 cuda 对 cpu 的性能。
【解决方案2】:

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

**

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

**

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 2021-08-23
    • 2020-12-06
    • 2019-09-16
    • 2019-08-18
    相关资源
    最近更新 更多