matmul.c 15 KB

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