matmul.c 14 KB

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