gpt4 book ai didi

python-3.x - PyTorch CUDA 与 Numpy 的算术运算?最快的?

转载 作者:行者123 更新时间:2023-12-05 00:11:52 25 4
gpt4 key购买 nike

我使用具有 GPU 支持的 Torch 和 Numpy 使用下面的函数执行逐元素乘法,发现 Numpy 循环比 Torch 快,我怀疑这不应该是这种情况。

我想知道如何使用 GPU 使用 Torch 执行一般算术运算。

注:我在 Google Colab notebook 中运行了这些代码片段

定义默认张量类型以启用全局 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 hat an intermediate result is being cached. 10000 loops, best of 3: 50.1 µs per loop



现在试用numpy,

使用来自 Torch 变量的相同值
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 操作。

最佳答案

GPU 操作必须另外从 GPU 获取内存

问题是你的 GPU 操作总是必须把输入放在 GPU 内存上,而且
然后从那里检索结果,这是一个非常昂贵的操作。

另一方面,NumPy 直接处理来自 CPU/主内存的数据,因此这里几乎没有延迟。此外,您的矩阵非常小,因此即使在最好的情况下,也应该只有微小的差异。

这也是在神经网络中在 GPU 上训练时使用小批量的部分原因:您现在拥有可以并行处理的“一大堆”数字,而不是几个极小的操作。
Also note that GPU clock speeds are generally way lower than CPU clocks ,所以 GPU 之所以真正闪耀,是因为它有更多的内核。如果您的矩阵没有完全利用所有这些,您也可能会在 CPU 上看到更快的结果。

TL;DR:如果你的矩阵足够大,你最终会看到加速,即使有额外的 GPU 传输成本。

关于python-3.x - PyTorch CUDA 与 Numpy 的算术运算?最快的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com