#include "mat_mul.h" #include #include #define CHECK_ERROR(err) \ if (err != CL_SUCCESS) { \ printf("[%s:%d] OpenCL error %d\n", __FILE__, __LINE__, err); \ exit(EXIT_FAILURE); \ } #define Num_DEVICE 4 #define TS 32 #define WPT 8 static cl_int err; static cl_platform_id platform; static cl_device_id device[Num_DEVICE]; static cl_context context; static cl_command_queue queue[Num_DEVICE]; static cl_program program; static cl_kernel kernel[Num_DEVICE]; static cl_mem a_d[Num_DEVICE], b_d[Num_DEVICE], c_d[Num_DEVICE]; static float *A, *B, *C; static int M, N, K; static 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; int block_size; for(int i=0; i< Ndev; i++){ block_size = ( i == Ndev-1 ) ? (M-(M/Ndev*(Ndev-1))) : M/Ndev; // Setup kernel arguments err = clSetKernelArg(kernel[i], 0, sizeof(cl_mem), &a_d[i]); CHECK_ERROR(err); err = clSetKernelArg(kernel[i], 1, sizeof(cl_mem), &b_d[i]); CHECK_ERROR(err); err = clSetKernelArg(kernel[i], 2, sizeof(cl_mem), &c_d[i]); CHECK_ERROR(err); err = clSetKernelArg(kernel[i], 3, sizeof(int), &block_size); CHECK_ERROR(err); err = clSetKernelArg(kernel[i], 4, sizeof(int), &N); CHECK_ERROR(err); err = clSetKernelArg(kernel[i], 5, sizeof(int), &K); CHECK_ERROR(err); // Setup global work size and local work size //size_t gws[2] = {(size_t)M, (size_t)N}, lws[2] = {TS, TS}; size_t gws[2] = {(size_t)(block_size+WPT-1)/WPT, (size_t)N}, lws[2] = {TS/WPT, TS}; for (int j = 0; j < 2; ++j) { // 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[j] = (gws[j] + lws[j] - 1) / lws[j] * lws[j]; } // Run kernel err = clEnqueueNDRangeKernel(queue[i], kernel[i], 2, NULL, gws, lws, 0, NULL, NULL); CHECK_ERROR(err); } // DO NOT REMOVE; NEEDED FOR TIME MEASURE for(int i=0; i a_d (gpu), B (cpu) -> b_d (gpu) err = clEnqueueWriteBuffer(queue[i], a_d[i], CL_TRUE, 0, block_size*K*sizeof(float), &A[M/Ndev*K*i], 0, NULL, NULL); CHECK_ERROR(err); err = clEnqueueWriteBuffer(queue[i], b_d[i], CL_TRUE, 0, K*N*sizeof(float), B, 0, NULL, NULL); CHECK_ERROR(err); } for(int i=0; i C (cpu) for(int i=0; i