为什么 GPU 上的乘法比 CPU 上的慢?

dav*_*ang 2 python gpu pytorch

这是我的代码(模拟前馈神经网络):

import torch
import time

print(torch.cuda.is_available())    # True
device = torch.device('cuda:0' )

a = torch.tensor([1,2,3,4,5,6]).float().reshape(-1,1)
w1 = torch.rand(120,6)
w2 = torch.rand(1,120)
b1 = torch.rand(120,1)
b2 = torch.rand(1,1).reshape(1,1)

start = time.time()
for _ in range(100000):
    ans = torch.mm(w2, torch.mm(w1,a)+b1)+b2
end = time.time()
print(end-start)                    # 1.2725720405578613 seconds

a = a.to(device)
w1 = w1.to(device)
w2 = w2.to(device)
b1 = b1.to(device)
b2 = b2.to(device)

start = time.time()
for _ in range(100000):
    ans = torch.mm(w2, torch.mm(w1,a)+b1)+b2
end = time.time()
print(end-start)                    # 5.6569812297821045 seconds
Run Code Online (Sandbox Code Playgroud)

我不知道如果我做了错误的方式还是什么,我怎么可以改变我的代码表明,GPU IS更快然后在矩阵乘法CPU?

Kár*_*abó 6

原因可能有很多:

  1. 你的模型很简单。
  2. 对于 GPU 计算,存在与 GPU 内存之间的内存传输成本
  3. 您的计算是在小数据批次上进行的,可能有更大的数据样本,您应该会在 GPU 上看到比 CPU 更好的性能
  4. 我们不应该忘记缓存,您一遍又一遍地计算相同的操作,也许a每次运行生成随机张量会更好

这是 pytorch 论坛上的一个主题:https ://discuss.pytorch.org/t/cpu-faster-than-gpu/25343

你也应该使用更好的分析器,就像在这个线程中解释的那样:https ://discuss.pytorch.org/t/how-to-measure-time-in-pytorch/26964