【发布时间】:2015-08-30 06:49:45
【问题描述】:
我正在尝试使用 anaconda 加速来快速计算矩阵。我从非常基本的示例开始:将 2 个矩阵相乘。
我的目标是以某种方式获得比通常的 numpy.dot 更好的 GPU 乘法
这是我的基本示例,基于 documentation。
from numbapro import guvectorize
from numpy import arange
@guvectorize(['void(float32[:,:], float32[:,:], float32[:,:])'], '(m,n),(n,p)->(m,p)', target='gpu')
def matmul(A, B, C):
m, n = A.shape
n, p = B.shape
for i in range(m):
for j in range(p):
C[i, j] = 0
for k in range(n):
C[i, j] += A[i, k] * B[k, j]
import numpy as np
import time
for dim in [50, 100, 200]:
rnd = np.random.RandomState(0)
a = rnd.rand(dim, dim).astype(np.float32)
b = rnd.rand(dim, dim).astype(np.float32)
resgpu = np.zeros_like(a)
start = time.time()
rescpu = np.dot(a, b)
print('CPU:', time.time() - start)
start = time.time()
resgpu = matmul(a, b)
print('GPU:', time.time() - start)
print(np.allclose(rescpu, resgpu))
print(np.allclose(resgpu, rescpu))
结果太糟糕了:GPU 比 CPU 慢得令人难以置信
CPU: 0.00011801719665527344
GPU: 0.05677294731140137
True
True
CPU: 0.00011205673217773438
GPU: 0.3881375789642334
True
True
CPU: 0.00038933753967285156
GPU: 3.018171787261963
True
True
当然我知道内部的numpy实现已经很好地优化了,但是我希望anaconda官方的例子很好。我正在使用 python 3.4.3 并在使用这两个帮助库时出错:http://www.cs.toronto.edu/~tijmen/gnumpy.html 和 https://github.com/rctn/gpupy
我应该说使用 gpupy 我在 python 2.7 上成功加速。
所以我的问题是:如何通过使用 GPU 获得比 numpy-CPU 更好的矩阵乘法? anaconda 官方示例有什么问题,是否有一个允许以 numpy 方式使用 GPU 的 python3 工作库?
===
结果
很遗憾,python 3没有简单好办法,改用2.7吧
感谢@rth 推荐了很棒的库scikits.cuda
一些基准测试(使用 anaconda mkl 进行测试,因此 numpy 也很快)
dim = 10000
rnd = np.random.RandomState(0)
a = rnd.rand(dim, dim).astype(np.float32)
b = rnd.rand(dim, dim).astype(np.float32)
a_gpu = gpuarray.to_gpu(a)
b_gpu = gpuarray.to_gpu(b)
start = time.time()
rescpu = np.dot(a, b)
print 'CPU:', time.time() - start
start = time.time()
resgpu = culinalg.dot(a_gpu, b_gpu)
print 'GPU:', time.time() - start
resgpu = resgpu.get()
print np.allclose(rescpu, resgpu)
print np.allclose(resgpu, rescpu)
结果
CPU: 16.4765479565
GPU: 0.000520944595337
【问题讨论】:
-
请注意,将数据复制到 GPU 和从 GPU 复制数据的成本很高。所以
gpuarray.to_gpu应该在timed部分里面,然后我想GPU时间会高一点。 -
查看您的时间,我怀疑 culinalg.dot 正在异步运行,即您需要 synchronize(),否则 GPU 在您的打印“GPU:”语句期间仍在计算。与您的尺寸相比,与 CPU(MKL,28 核)相比,我在 GPU(Tesla K40,运行时间为 600 毫秒,没有数据传输)上获得了约 5 倍的改进。与您的设置相反,我使用的是 numbapro.cudalib.Blas 并执行 numba.cuda.synchronize()。
标签: numpy python-3.4 anaconda numba-pro