matmul.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. /* StarPU --- Runtime system for heterogeneous multicore architectures.
  2. *
  3. * Copyright (C) 2010,2011, 2015 University of Bordeaux
  4. *
  5. * StarPU is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License as published by
  7. * the Free Software Foundation; either version 2.1 of the License, or (at
  8. * your option) any later version.
  9. *
  10. * StarPU is distributed in the hope that it will be useful, but
  11. * WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. *
  14. * See the GNU Lesser General Public License in COPYING.LGPL for more details.
  15. */
  16. #ifdef __APPLE_CC__
  17. #include <OpenCL/opencl.h>
  18. #else
  19. #include <CL/cl.h>
  20. #endif
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include <stdlib.h>
  24. #include <stdint.h>
  25. #include <unistd.h>
  26. #include <assert.h>
  27. #include <math.h>
  28. #include <sys/time.h>
  29. #define error(...) do { fprintf(stderr, "Error: " __VA_ARGS__); exit(EXIT_FAILURE); } while(0)
  30. #define check(exp) do { err = exp; if(err != CL_SUCCESS) { fprintf(stderr, "OpenCL Error (%d): " #exp "\n", err); exit(EXIT_FAILURE); }} while(0)
  31. #define check2(exp) exp; if(err != CL_SUCCESS) { fprintf(stderr, "OpenCL Error (%d): " #exp "\n", err); exit(EXIT_FAILURE); }
  32. // Thread block size
  33. #define BLOCK_SIZE 16 // Kernel thread-block size
  34. #define WORK_SIZE 64 // Kernel global size in lines of A (or C)
  35. #define TYPE float
  36. // Basic Matrix dimensions
  37. #define WA (128L * BLOCK_SIZE) // Matrix A width
  38. #ifdef STARPU_QUICK_CHECK
  39. #define HA (128L * BLOCK_SIZE) // Matrix A height
  40. #else
  41. #define HA (512L * BLOCK_SIZE) // Matrix A height
  42. #endif
  43. #define WB (128L * BLOCK_SIZE) // Matrix B width
  44. #define HB WA // Matrix B height
  45. #define WC WB // Matrix C width
  46. #define HC HA // Matrix C height
  47. #define BLOCKS (HA / WORK_SIZE)
  48. ////////////////////////////////////////////////////////////////////////////////
  49. // declaration, forward
  50. void printDiff(TYPE*, TYPE*, int, int, int, TYPE);
  51. void computeReference(TYPE*, const TYPE*, const TYPE*, unsigned int, unsigned int, unsigned int);
  52. #define str(x) #x
  53. #define CODE "\
  54. #define TYPE float\n\
  55. __kernel void sgemmNN(int wa, int ha, int wb, __global TYPE* A, __global TYPE* B, __global TYPE* C) {\n\
  56. #define BS 16\n\
  57. #define BLOCK_SIZE 16\n\
  58. int bx = get_group_id(0);\n\
  59. int by = get_group_id(1);\n\
  60. \n\
  61. int tx = get_local_id(0);\n\
  62. int ty = get_local_id(1);\n\
  63. \n\
  64. int gx = get_global_id(0);\n\
  65. int gy = get_global_id(1);\n\
  66. __local float As[BS][BS+1];\
  67. __local float Bs[BS][BS+1];\
  68. \n\
  69. unsigned int block_w = min(wb - bx * BLOCK_SIZE, BLOCK_SIZE);\n\
  70. unsigned int block_h = min(ha - by * BLOCK_SIZE, BLOCK_SIZE);\n\
  71. \n\
  72. int valid = (gx < wb && gy < ha);\n\
  73. \n\
  74. TYPE Csub = (TYPE)0.0;\n\
  75. \n\
  76. int pos = 0;\n\
  77. while (pos < wa) {\n\
  78. unsigned int size = min(wa-pos, BLOCK_SIZE);\n\
  79. if (tx < size && gy < ha)\n\
  80. As[tx][ty] = A[pos + tx + wa * gy];\n\
  81. if (ty < size && gx < wb)\n\
  82. Bs[tx][ty] = B[gx + wb * (pos+ty)];\n\
  83. \n\
  84. barrier(CLK_LOCAL_MEM_FENCE);\n\
  85. \n\
  86. if (valid) {\n\
  87. for (int k = 0; k < size; ++k)\n\
  88. Csub += As[k][ty] * Bs[tx][k];\n\
  89. }\n\
  90. pos += size;\n\
  91. barrier(CLK_LOCAL_MEM_FENCE);\n\
  92. }\n\
  93. \n\
  94. if (valid)\n\
  95. C[wb * gy + gx] = Csub;\n\
  96. }"
  97. static char * code = CODE;
  98. int check = 0;
  99. static void __attribute__((unused)) parse_args(int argc, const char **argv)
  100. {
  101. int i;
  102. for (i = 1; i < argc; i++)
  103. {
  104. if (strcmp(argv[i], "-check") == 0)
  105. {
  106. check = 1;
  107. }
  108. if (strcmp(argv[i], "-h") == 0)
  109. {
  110. printf("usage : %s [-check]\n", argv[0]);
  111. }
  112. }
  113. }
  114. // Round Up Division function
  115. size_t roundUp(int group_size, int global_size) {
  116. int r = global_size % group_size;
  117. if(r == 0) {
  118. return global_size;
  119. } else {
  120. return global_size + group_size - r;
  121. }
  122. }
  123. void fillArray(TYPE* data, int size) {
  124. int i;
  125. const TYPE fScale = (TYPE)(1.0f / (float)RAND_MAX);
  126. for (i = 0; i < size; ++i) {
  127. data[i] = fScale * rand();
  128. }
  129. }
  130. void printArray(float* data, int size) {
  131. int i;
  132. for (i = 0; i < size; ++i) {
  133. printf("%d: %.3f\n", i, data[i]);
  134. }
  135. }
  136. /**
  137. * Compare two float arrays using L2-norm with an epsilon tolerance for equality
  138. * @return shrTRUE if \a reference and \a data are identical, otherwise shrFALSE
  139. * @param reference handle to the reference data / gold image
  140. * @param data handle to the computed data
  141. * @param len number of elements in reference and data
  142. * @param epsilon epsilon to use for the comparison
  143. */
  144. int shrCompareL2fe( const float* reference, const float* data, const unsigned int len, const float epsilon ) {
  145. assert(epsilon >= 0);
  146. float error = 0;
  147. float ref = 0;
  148. unsigned int i;
  149. for(i = 0; i < len; ++i) {
  150. float diff = reference[i] - data[i];
  151. error += diff * diff;
  152. ref += reference[i] * reference[i];
  153. }
  154. float normRef = sqrtf(ref);
  155. if (fabs(ref) < 1e-7) {
  156. #ifdef _DEBUG
  157. fprintf(stderr, "ERROR, reference l2-norm is 0\n");
  158. #endif
  159. return 0;
  160. }
  161. float normError = sqrtf(error);
  162. error = normError / normRef;
  163. int result = error < epsilon;
  164. #ifdef _DEBUG
  165. if( !result) {
  166. fprintf(stderr, "ERROR, l2-norm error %d is greater than epsilon %lf \n", error, epsilon);
  167. }
  168. #endif
  169. return result;
  170. }
  171. int main(int argc, const char** argv) {
  172. cl_uint platform_count;
  173. cl_platform_id platforms[5];
  174. cl_int err = CL_SUCCESS;
  175. unsigned int i, p;
  176. cl_device_type dev_type = CL_DEVICE_TYPE_ALL;
  177. void * ptrs[BLOCKS];
  178. cl_command_queue cqs[BLOCKS];
  179. cl_mem d_A[BLOCKS];
  180. cl_mem d_C[BLOCKS];
  181. cl_mem d_B[BLOCKS];
  182. cl_event GPUDone[BLOCKS];
  183. cl_event GPUExecution[BLOCKS];
  184. struct timeval start, end;
  185. int workOffset[BLOCKS];
  186. int workSize[BLOCKS];
  187. unsigned int sizePerGPU = HC / BLOCKS;
  188. unsigned int sizeMod = HC % BLOCKS;
  189. size_t A_size = WA * HA;
  190. size_t A_mem_size = sizeof(TYPE) * A_size;
  191. TYPE* A_data;
  192. size_t B_size = WB * HB;
  193. size_t B_mem_size = sizeof(TYPE) * B_size;
  194. TYPE* B_data;
  195. size_t C_size = WC * HC;
  196. size_t C_mem_size = sizeof(TYPE) * C_size;
  197. TYPE* C_data;
  198. parse_args(argc, argv);
  199. check(clGetPlatformIDs(5, platforms, &platform_count));
  200. if (platform_count == 0) {
  201. printf("No platform found\n");
  202. exit(77);
  203. }
  204. cl_uint device_count;
  205. cl_uint devs[platform_count];
  206. cl_device_id * devices[platform_count];
  207. cl_context ctx[platform_count];
  208. cl_command_queue * commandQueue[platform_count];
  209. device_count = 0;
  210. for (p=0; p<platform_count; p++) {
  211. cl_platform_id platform = platforms[p];
  212. err = clGetDeviceIDs(platform, dev_type, 0, NULL, &devs[p]);
  213. if (err == CL_DEVICE_NOT_FOUND) {
  214. devs[p] = 0;
  215. continue;
  216. }
  217. if (devs[p] == 0) {
  218. printf("No OpenCL device found\n");
  219. exit(77);
  220. }
  221. if (err != CL_SUCCESS) {
  222. fprintf(stderr, "OpenCL Error (%d) in clGetDeviceIDs()\n", err);
  223. exit(EXIT_FAILURE);
  224. }
  225. if (devs[p] == 0)
  226. continue;
  227. devices[p] = (cl_device_id*)malloc(sizeof(cl_device_id) * devs[p]);
  228. commandQueue[p] = (cl_command_queue*)malloc(sizeof(cl_command_queue) * devs[p]);
  229. check(clGetDeviceIDs(platform, dev_type, devs[p], devices[p], NULL));
  230. cl_context_properties properties[] = {CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
  231. check2(ctx[p] = clCreateContext(properties, devs[p], devices[p], NULL, NULL, &err));
  232. for(i = 0; i < devs[p]; ++i)
  233. {
  234. cl_device_id device = devices[p][i];
  235. char name[2048];
  236. name[0] = '\0';
  237. clGetDeviceInfo(device, CL_DEVICE_NAME, 2048, name, NULL);
  238. printf("Device %d: %s\n", i, name);
  239. check2(commandQueue[p][i] = clCreateCommandQueue(ctx[p], device, CL_QUEUE_PROFILING_ENABLE | CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err));
  240. }
  241. device_count += devs[p];
  242. }
  243. if (device_count == 0)
  244. error("No device found\n");
  245. cl_kernel multiplicationKernel[platform_count];
  246. printf("\nUsing Matrix Sizes: A(%lu x %lu), B(%lu x %lu), C(%lu x %lu)\n",
  247. (unsigned long)WA, (unsigned long)HA, (unsigned long)WB, (unsigned long)HB, (unsigned long)WC, (unsigned long)HC);
  248. // allocate host memory for matrices A, B and C
  249. A_data = (TYPE*)malloc(A_mem_size);
  250. if (A_data == NULL) {
  251. perror("malloc");
  252. }
  253. B_data = (TYPE*)malloc(B_mem_size);
  254. if (B_data == NULL) {
  255. perror("malloc");
  256. }
  257. C_data = (TYPE*) malloc(C_mem_size);
  258. if (C_data == NULL) {
  259. perror("malloc");
  260. }
  261. cl_program program[platform_count];
  262. for (p=0; p<platform_count; p++) {
  263. if (devs[p] == 0)
  264. continue;
  265. check2(program[p] = clCreateProgramWithSource(ctx[p], 1, (const char **)&code, NULL, &err));
  266. check(clBuildProgram(program[p], 0, NULL, NULL, NULL, NULL));
  267. check2(multiplicationKernel[p] = clCreateKernel(program[p], "sgemmNN", &err));
  268. }
  269. printf("Initializing data...\n");
  270. srand(2008);
  271. fillArray(A_data, A_size);
  272. fillArray(B_data, B_size);
  273. memset(C_data, 0, C_size);
  274. printf("Computing...\n");
  275. workOffset[0] = 0;
  276. gettimeofday(&start, NULL);
  277. size_t localWorkSize[] = {BLOCK_SIZE, BLOCK_SIZE};
  278. int c = 0;
  279. for (p=0; p<platform_count;p++) {
  280. for (i=0; i<devs[p]; i++) {
  281. check2(d_B[c] = clCreateBuffer(ctx[p], CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, HB * WB * sizeof(TYPE), B_data, &err));
  282. c++;
  283. }
  284. }
  285. for(i=0; i < BLOCKS; ++i)
  286. {
  287. int d = i % device_count;
  288. cl_uint platform = 0;
  289. // determine device platform
  290. int dev = d;
  291. for (platform = 0; platform < platform_count; platform++) {
  292. if ((cl_int)(dev - devs[platform]) < 0)
  293. break;
  294. dev -= devs[platform];
  295. }
  296. workSize[i] = (i < sizeMod) ? sizePerGPU+1 : sizePerGPU;
  297. check2(d_A[i] = clCreateBuffer(ctx[platform], CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, workSize[i] * WA * sizeof(TYPE), &A_data[workOffset[i] * WA], &err));
  298. check2(d_C[i] = clCreateBuffer(ctx[platform], CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, workSize[i] * WC * sizeof(TYPE), &C_data[workOffset[i] * WC], &err));
  299. check(clSetKernelArg(multiplicationKernel[platform], 0, sizeof(cl_int), &workSize[i]));
  300. check(clSetKernelArg(multiplicationKernel[platform], 1, sizeof(cl_int), &workSize[i]));
  301. check(clSetKernelArg(multiplicationKernel[platform], 2, sizeof(cl_int), &workSize[i]));
  302. check(clSetKernelArg(multiplicationKernel[platform], 3, sizeof(cl_mem), (void *) &d_A[i]));
  303. check(clSetKernelArg(multiplicationKernel[platform], 4, sizeof(cl_mem), (void *) &d_B[d]));
  304. check(clSetKernelArg(multiplicationKernel[platform], 5, sizeof(cl_mem), (void *) &d_C[i]));
  305. size_t globalWorkSize[] = {roundUp(BLOCK_SIZE,WC), roundUp(BLOCK_SIZE,workSize[i])};
  306. check(clEnqueueNDRangeKernel(commandQueue[platform][dev], multiplicationKernel[platform], 2, NULL, globalWorkSize, localWorkSize, 0, NULL, &GPUExecution[i]));
  307. // Non-blocking copy of result from device to host
  308. cqs[i] = commandQueue[platform][dev];
  309. check2(ptrs[i] = clEnqueueMapBuffer(cqs[i], d_C[i], CL_FALSE, CL_MAP_READ, 0, WC * sizeof(TYPE) * workSize[i], 1, &GPUExecution[i], &GPUDone[i], &err));
  310. if(i+1 < BLOCKS)
  311. workOffset[i + 1] = workOffset[i] + workSize[i];
  312. }
  313. // CPU sync with GPU
  314. for (p=0; p<platform_count;p++) {
  315. cl_uint dev;
  316. for (dev=0; dev<devs[p]; dev++) {
  317. clFinish(commandQueue[p][dev]);
  318. }
  319. }
  320. gettimeofday(&end, NULL);
  321. double timing = (double)((end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec));
  322. double dSeconds = timing/1000/1000;
  323. double dNumOps = 2.0 * (double)WA * (double)HA * (double)WB;
  324. double gflops = 1.0e-9 * dNumOps/dSeconds;
  325. printf("Throughput = %.4f GFlops/s, Time = %.5f s, Size = %.0f, NumDevsUsed = %d, Blocks = %ld, Workgroup = %zu\n",
  326. gflops, dSeconds, dNumOps, device_count, BLOCKS, localWorkSize[0] * localWorkSize[1]);
  327. // compute reference solution
  328. if (check) {
  329. printf("Comparing results with CPU computation... ");
  330. TYPE* reference = (TYPE*)malloc(C_mem_size);
  331. computeReference(reference, A_data, B_data, HA, WA, WB);
  332. // check result
  333. int res = shrCompareL2fe(reference, C_data, C_size, 1.0e-6f);
  334. if (res == 0) {
  335. printf("\n\n");
  336. printDiff(reference, C_data, WC, HC, 100, 1.0e-5f);
  337. }
  338. else printf("PASSED\n\n");
  339. free(reference);
  340. }
  341. for(i = 0; i < BLOCKS; i++)
  342. {
  343. clEnqueueUnmapMemObject(cqs[i], d_C[i], ptrs[i], 0, NULL, NULL);
  344. }
  345. for(i = 0; i < BLOCKS; i++)
  346. {
  347. clFinish(cqs[i]);
  348. }
  349. for (i=0; i<device_count; i++) {
  350. clReleaseMemObject(d_B[i]);
  351. }
  352. for(i = 0; i < BLOCKS; i++)
  353. {
  354. clReleaseMemObject(d_A[i]);
  355. clReleaseMemObject(d_C[i]);
  356. clReleaseEvent(GPUExecution[i]);
  357. clReleaseEvent(GPUDone[i]);
  358. }
  359. for (p=0; p<platform_count;p++) {
  360. if (devs[p] == 0)
  361. continue;
  362. check(clReleaseKernel(multiplicationKernel[p]));
  363. check(clReleaseProgram(program[p]));
  364. check(clReleaseContext(ctx[p]));
  365. cl_uint k;
  366. for(k = 0; k < devs[p]; ++k)
  367. {
  368. check(clReleaseCommandQueue(commandQueue[p][k]));
  369. }
  370. }
  371. free(A_data);
  372. free(B_data);
  373. free(C_data);
  374. return 0;
  375. }
  376. void printDiff(TYPE *data1, TYPE *data2, int width, int height, int listLength, TYPE listTol) {
  377. printf("Listing first %d Differences > %.6f...\n", listLength, listTol);
  378. int i,j,k;
  379. int error_count=0;
  380. for (j = 0; j < height; j++) {
  381. if (error_count < listLength) {
  382. printf("\n Row %d:\n", j);
  383. }
  384. for (i = 0; i < width; i++) {
  385. k = j * width + i;
  386. float diff = fabs(data1[k] - data2[k]);
  387. if (diff > listTol) {
  388. if (error_count < listLength) {
  389. printf(" Loc(%d,%d)\tCPU=%.5f\tGPU=%.5f\tDiff=%.6f\n", i, j, data1[k], data2[k], diff);
  390. }
  391. error_count++;
  392. }
  393. }
  394. }
  395. printf(" \n Total Errors = %d\n\n", error_count);
  396. }
  397. /**
  398. * Compute reference data set
  399. * C = A * B
  400. * @param C reference data, computed but preallocated
  401. * @param A matrix A as provided to device
  402. * @param B matrix B as provided to device
  403. * @param hA height of matrix A
  404. * @param wB width of matrix B
  405. */
  406. void computeReference(TYPE* C, const TYPE* A, const TYPE* B, unsigned int hA, unsigned int wA, unsigned int wB) {
  407. unsigned int i,j,k;
  408. for (i = 0; i < hA; ++i)
  409. for (j = 0; j < wB; ++j) {
  410. double sum = 0;
  411. for (k = 0; k < wA; ++k) {
  412. double a = A[i * wA + k];
  413. double b = B[k * wB + j];
  414. sum += a * b;
  415. }
  416. C[i * wB + j] = (TYPE)sum;
  417. }
  418. }