1. cudamat簡介
cudamat是一個python語言下,利用NVIDIA的cuda sdk 進行矩陣運算加速的庫。對於不熟悉cuda編程的程序員來說,這是一個非常方便的GPU加速方案。很多工程和項目中都使用了cudamat,例如gnumpy,deepnet等。
2. 安裝
cudamat的github地址如下:https://github.com/cudamat/cudamat。
下載完成后,運行命令 python setup.py install來進行安裝。
windows下安裝需要將“cl.exe”加入path之中,另外會提示你安裝vc的python編譯器,依照提示下載安裝即可。
3. 基本矩陣運算
import numpy as np
import cudamat as cm
cm.cublas_init()
# create two random matrices and copy them to the GPU
a = cm.CUDAMatrix(np.random.rand(32, 256))
b = cm.CUDAMatrix(np.random.rand(256, 32))
# perform calculations on the GPU
c = cm.dot(a, b)
d = c.sum(axis = 0)
# copy d back to the host (CPU) and print
print(d.asarray())
如以上代碼所示,cudamat的基本使用方法是利用cm.CUDAMatrix(A)來講矩陣A轉換成GPU里的矩陣,進而進行各種運算。cudamat提供了多種矩陣運算的接口,可參考文檔:http://www.cs.toronto.edu/~vmnih/docs/cudamat_tr.pdf。或者可閱讀源代碼里的cudamat/cudamat.py或test/test_cudamat.py來查看其各種接口。
4. where等其他運算
接下來介紹一個矩陣里的where運算,示例代碼如下:
def func(temp,threshold):
temp_cpu1=temp.asarray()
res_d = cm.empty(temp.shape)
temp.greater_than(threshold, res_d)
temp.free_device_memory()
x=np.ones_like(temp_cpu1)
z = np.zeros_like(temp_cpu1)
x_d=cm.CUDAMatrix(x)
z_d = cm.CUDAMatrix(z)
# > threhold ? 1 : 0
cm.where(res_d, x_d, z_d)
temp_cpu=res_d.asarray()
return temp_cpu
如代碼所示,該函數的輸入是一個CUDAMatrix temp,一個double值threshold。通過great_than函數,可將temp與threshold進行比較,比較的結果放入res_d中,x_d,z_d是與temp同樣大小的1,0矩陣,最后通過where操作,即可將res_d中的正值設為1,負值設為0,最后得到的結果也就是將矩陣temp中大於threshold的值設為1,否則設為0
5. 大型矩陣相乘的分塊加速算法
對於非常大型的矩陣相乘,如果顯存不足以放下矩陣的話,可以嘗試分塊送入GPU進行計算,再將得到的結果進行匯總。
作者yunhe
謝謝閱讀!轉載請注明出處。