使用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 (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...