用cudamat做矩阵运算的GPU加速

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
谢谢阅读!转载请注明出处。

原文地址:https://www.cnblogs.com/yunheyj/p/6262378.html