做一些类似的事情
import numpy as np
a = np.random.rand(10**4, 10**4)
b = np.dot(a, a)
使用多核,运行良好。在
但是,a
中的元素是64位浮点(或者在32位平台中是32位?),我想乘以8位整数数组。不过,尝试以下方法:
结果是dot产品不使用多核,因此在我的电脑上运行速度慢了约1000倍
array: np.random.randint(2, size=shape).astype(dtype)
dtype shape %time (average)
float32 (2000, 2000) 62.5 ms
float32 (3000, 3000) 219 ms
float32 (4000, 4000) 328 ms
float32 (10000, 10000) 4.09 s
int8 (2000, 2000) 13 seconds
int8 (3000, 3000) 3min 26s
int8 (4000, 4000) 12min 20s
int8 (10000, 10000) It didn't finish in 6 hours
float16 (2000, 2000) 2min 25s
float16 (3000, 3000) Not tested
float16 (4000, 4000) Not tested
float16 (10000, 10000) Not tested
我知道NumPy使用BLAS,它不支持整数,但是如果我使用SciPy BLAS包装器,即
import scipy.linalg.blas as blas
a = np.random.randint(2, size=(n, n)).astype(np.int8)
b = blas.sgemm(alpha=1.0, a=a, b=a)
计算是多线程的。现在,blas.sgemm
的运行时间与float32的np.dot
完全相同,但是对于非float,它将所有内容转换为float32
并输出float,这是np.dot
不能做到的。(另外,b
现在是F_CONTIGUOUS
顺序,这是一个较小的问题)。在
所以,如果我想做整数矩阵乘法,我必须做以下一个:
np.dot
并很高兴我能保留8位整数。在sgemm
并使用4倍内存。在np.float16
并且只占用2倍的内存,但要注意的是,np.dot
在float16数组上比在float32数组上慢得多,比int8更慢。在我可以选择4吗?这样的图书馆存在吗?在
免责声明:我实际上运行的是NumPy+MKL,但是我在vanillynumpy上做了一个类似的测试,结果相似。在
numpy.dot
计算,这将释放全局解释器锁。因此,可以使用相对轻量级的threads,它可以从主线程访问数组以提高内存效率。在实施:
通过这个实现,我得到了大约x4的加速,这是我机器中核心的物理数量:
^{pr2}$“Why is it faster to perform float by float matrix multiplication compared to int by int?”解释了为什么整数这么慢:首先,cpu有高吞吐量的浮点管道。其次,BLAS没有整数类型。在
解决方法:将矩阵转换为
float32
值可以获得很大的加速。2015款MacBook Pro的90x加速性能如何?(使用float64
效果是一半。)相关问题 更多 >
编程相关推荐