我使用具有GPU支持的Torch和下面的函数对Numpy进行了元素逐个乘法运算,我发现Numpy的循环速度要比Torch快,我对此感到怀疑。
我想知道如何使用GPU使用Torch进行常规算术运算。
注意:我在Google Colab笔记本中运行了这些代码段
定义默认张量类型以启用全局GPU标志
torch.set_default_tensor_type(torch.cuda.FloatTensor if
torch.cuda.is_available() else torch.FloatTensor)
初始化Torch变量
x = torch.Tensor(200, 100) # Is FloatTensor
y = torch.Tensor(200,100)
def mul(d,f):
g = torch.mul(d,f).cuda() # I explicitly called cuda() which is not necessary
return g
当以
%timeit mul(x,y)
返回:
The slowest run took 10.22 times longer than the fastest. This could mean that
an intermediate result is being cached.
10000 loops, best of 3: 50.1 µs per loop
现在使用numpy试用
使用了与割炬变量相同的值
x_ = x.data.cpu().numpy()
y_ = y.data.cpu().numpy()
def mul_(d,f):
g = d*f
return g
%timeit mul_(x_,y_)
返回
The slowest run took 12.10 times longer than the fastest. This could mean that
an intermediate result is being cached.
100000 loops, best of 3: 7.73 µs per loop
需要一些帮助来了解启用GPU的Torch操作。
答案 0 :(得分:2)
问题是您的GPU操作始终必须将输入放到GPU内存上,并且 然后从那里检索结果,这是一个非常昂贵的操作。
另一方面,NumPy直接处理来自CPU /主存储器的数据,因此这里几乎没有延迟。另外,您的矩阵非常小,因此即使在最佳情况下,它们之间的差异也应该很小。
这也是在神经网络的GPU上进行训练时使用小批处理的部分原因:现在,您可以进行并行处理,而不是进行一些非常小的操作,而是拥有大量的数字。
Also note that GPU clock speeds are generally way lower than CPU clocks,因此GPU的确发光,因为它具有更多的内核。如果矩阵未充分利用所有矩阵,那么您也可能会在CPU上看到更快的结果。
TL; DR:如果矩阵足够大,那么即使GPU传输成本增加,您最终也会看到速度提高。