如何解决使用pyopencl的朴素2D方阵乘法
我正在尝试使用OpenCL和 pyopencl python库为两个平方矩阵实现一个简单的朴素MVM内核,但是结果并不理想。我使用的OpenCL和Python代码如下:
朴素的OpenCL内核:
__kernel void MM(const int M,const int N,const int K,const __global float* A,const __global float* B,__global float* C) {
const int row = get_global_id(0); // Row ID of C (0..M)
const int col = get_global_id(1); // Column ID of C (0...N)
float acc = 0.0f;
for (int i=0; i < K; i++) {
acc += A[i*M + row] * B[col*K + i];
}
C[col*M + row] = acc;
}
相应的python脚本:
import numpy as np
import pyopencl as cl
ctx - cl.create_some_context()
queue = cl.CommandQueue(ctx)
mf = cl.mem_flags
kernelsource = open('MM.cl').read()
program = cl.Program(ctx,kernelsource).build()
dim = 25
a = np.random.rand(dim,dim).astype(np.float32)
b = np.random.rand(dim,dim).astype(np.float32)
a_cl = cl.Buffer(ctx,mf.READ_ONLY | mf.COPY_HOST_PTR,hostbuf=a.flatten())
b_cl = cl.Buffer(ctx,hostbuf=b.flatten())
result = np.zeros(shape=dim*dim).astype(np.float32)
result_cl = cl.Buffer(ctx,mf.WRITE_ONLY,result.nbytes)
program.MM(queue,(dim,dim),None,np.int32(dim),a_cl,b_cl,result_cl)
cl.enqueue_copy(queue,result,result_cl)
print(result.reshape(dim,dim))
print(np.matmul(a,b))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。