#include "mat_mul.h" #include #include #define MAX_DEV 4 #define CHECK_ERROR(err) \ if (err != CL_SUCCESS) { \ printf("[%s:%d] OpenCL error %d\n", __FILE__, __LINE__, err); \ exit(EXIT_FAILURE); \ } static cl_int err; static cl_platform_id platform; static cl_device_id device[MAX_DEV]; static cl_context context; static cl_command_queue queue[MAX_DEV]; static cl_program program[MAX_DEV]; static cl_kernel kernel[MAX_DEV]; static cl_mem a_d[MAX_DEV], b_d[MAX_DEV], c_d[MAX_DEV]; static float *A, *B, *C; static int M, N, K; int ndev; void mat_mul(float *_A, float *_B, float *_C, int _M, int _N, int _K) { A = _A, B = _B, C = _C; M = _M, N = _N, K = _K; for(int j = 0; j < ndev; j++){ int delta = j == (ndev -1) ? (M -( M/ndev*(ndev -1))) : M/ndev; // Setup kernel arguments err = clSetKernelArg(kernel[j], 0, sizeof(cl_mem), &a_d[j]); CHECK_ERROR(err); err = clSetKernelArg(kernel[j], 1, sizeof(cl_mem), &b_d[j]); CHECK_ERROR(err); err = clSetKernelArg(kernel[j], 2, sizeof(cl_mem), &c_d[j]); CHECK_ERROR(err); err = clSetKernelArg(kernel[j], 3, sizeof(int), &delta); CHECK_ERROR(err); err = clSetKernelArg(kernel[j], 4, sizeof(int), &N); CHECK_ERROR(err); err = clSetKernelArg(kernel[j], 5, sizeof(int), &K); CHECK_ERROR(err); // Setup global work size and local work size size_t gws[2] = {(size_t)(delta+7)/8, (size_t)N}, lws[2] = {4,32}; for (int i = 0; i < 2; ++i) { // By OpenCL spec, global work size should be MULTIPLE of local work size // Formula below achieve it // e.g., gws = 25, lws = 16, then (25 + 16 - 1) / 16 * 16 = 40 / 16 * 16 = 2 * 16 = 32 gws[i] = (gws[i] + lws[i] - 1) / lws[i] * lws[i]; } // Run kernel err = clEnqueueNDRangeKernel(queue[j], kernel[j], 2, NULL, gws, lws, 0, NULL, NULL); CHECK_ERROR(err); } for(int j=0; j a_d (gpu), B (cpu) -> b_d (gpu) int offset = M/ndev*j*K; err = clEnqueueWriteBuffer(queue[j], a_d[j], CL_FALSE, 0 , delta*K*sizeof(float), &A[offset], 0, NULL, NULL); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queue[j], b_d[j], CL_FALSE, 0, K * N * sizeof(float), B, 0, NULL, NULL); CHECK_ERROR(err); } for(j=0; j C (cpu) for(j=0; j