OpenCL的学习---计算直方图的理解

之前的理解device上每个compute unit:


看到《OpenCL编程指南》第14章---计算直方图,有点难理解,我对内存中抽象的东西。所以kernel函数那里看了很久。感谢北邮的大神 http://www.mrobotit.cn/~shanxinyan  他很懂OpenCL,我们学校和中南湖大我没听到有搞OpenCL的人,甚至网上也少,所以学习讨论较困难。书上的不能在我电脑上直接运行 我修改了kernel的几个地方:amd24以及read_imagef那里  整个工程在 http://download.csdn.net/detail/wd1603926823/9813986 这里。

其中host端:


 
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <string.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <fstream>
  8. #include <CL/cl.h>
  9. #include <iostream>
  10. #include <sstream>
  11. #include "FreeImage.h"
  12. #include "gFreeImage.h"
  13. const int num_pixels_per_work_item = 32;
  14. static int num_iterations = 1000;
  15. cl_mem LoadImage(cl_context context, char *fileName, int &width, int &height);
  16. static int read_kernel_from_file(const char *filename, char **source, size_t *len);
  17. static int verify_histogram_results(const char *str, unsigned int *histogram_results, unsigned int *ref_histogram_results, int num_entries);
  18. static void * generate_reference_histogram_results_fp32(void *image_data, int w, int h);
  19. static void * create_image_data_fp32(int w, int h);
  20. static void * generate_reference_histogram_results_unorm8(void *image_data, int w, int h);
  21. static void * create_image_data_unorm8(int w, int h);
  22. int main()
  23. {
  24. cl_uint platformNum;
  25. cl_int err;
  26. err=clGetPlatformIDs(0,NULL,&platformNum);
  27. if(err!=CL_SUCCESS){
  28. printf("cannot get platforms number.\n");
  29. return -1;
  30. }
  31. cl_platform_id* platforms;
  32. platforms=(cl_platform_id*)alloca(sizeof(cl_platform_id)*platformNum);
  33. err=clGetPlatformIDs(platformNum,platforms,NULL);
  34. if(err!=CL_SUCCESS){
  35. printf("cannot get platforms addresses.\n");
  36. return -1;
  37. }
  38. cl_platform_id platformInUse=platforms[0];
  39. cl_device_id device;
  40. clGetDeviceIDs(platformInUse,CL_DEVICE_TYPE_GPU,1,&device,NULL);
  41. cl_context context=clCreateContext(NULL,1,&device,NULL,NULL,NULL);
  42. cl_command_queue queue=clCreateCommandQueue(context,device,CL_QUEUE_PROFILING_ENABLE, &err);
  43. const char cl_kernel_histogram_filename[] = "/home/jumper/OpenCL_projects/Book_ch14_Histogram/partial_histogram.cl";
  44. size_t src_len[1];
  45. char *source[1];
  46. err = read_kernel_from_file(cl_kernel_histogram_filename, &source[0], &src_len[0]);
  47. cl_program program = clCreateProgramWithSource(context, 1, (const char **)source, (size_t *)src_len, &err);
  48. err = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
  49. if(err!=CL_SUCCESS){
  50. printf("cannot build program.\n");
  51. size_t log_size;
  52. clGetProgramBuildInfo(program,device,CL_PROGRAM_BUILD_LOG,0,NULL,&log_size);
  53. char *log=(char*)alloca(log_size);
  54. clGetProgramBuildInfo(program,device,CL_PROGRAM_BUILD_LOG,log_size,log,NULL);
  55. printf("%s\n",log);
  56. return -1;
  57. }
  58. cl_kernel histogram_rgba_unorm8 = clCreateKernel(program, "histogram_local", &err);
  59. if(err!=CL_SUCCESS){
  60. printf("cannot build kernel.\n");
  61. return -1;
  62. }
  63. std::ifstream srcFile2("/home/jumper/OpenCL_projects/Book_ch14_Histogram/sum_histogram.cl");
  64. std::string srcProg2(std::istreambuf_iterator <char>(srcFile2),(std::istreambuf_iterator <char>()));
  65. const char * src2 = srcProg2.c_str();
  66. size_t length2 = srcProg2.length();
  67. cl_program program2=clCreateProgramWithSource(context,1,&src2,&length2,&err);
  68. err=clBuildProgram(program2,1,&device,NULL,NULL,NULL);
  69. if(err!=CL_SUCCESS){
  70. printf("cannot build program2.\n");
  71. return -1;
  72. }
  73. cl_kernel histogram_sum_partial_results_unorm8 = clCreateKernel(program2, "histogram_global", &err);
  74. if(err!=CL_SUCCESS)
  75. {
  76. printf("clCreateKernel() failed creating kernel void histogram_sum_partial_results_unorm8(). (%d)\n", err);
  77. return EXIT_FAILURE;
  78. }
  79. //Create Input Image Object
  80. char file[]={"/home/jumper/OpenCL_projects/Book_ch14_Histogram/lenna.jpg"};
  81. int imgwidth,imgheight;
  82. cl_mem image=LoadImage(context,file,imgwidth,imgheight);
  83. cl_mem histogram_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, 256*3*sizeof(unsigned int), NULL, &err);
  84. if (!histogram_buffer || err)
  85. {
  86. printf("clCreateBuffer() failed. (%d)\n", err);
  87. return EXIT_FAILURE;
  88. }
  89. cl_image_format image_format;
  90. image_format.image_channel_order = CL_RGBA;
  91. image_format.image_channel_data_type = CL_UNORM_INT8;
  92. void *image_data_unorm8;
  93. cl_mem input_image_unorm8;
  94. void *image_data_fp32;
  95. cl_mem input_image_fp32;
  96. image_data_unorm8 = create_image_data_unorm8(imgwidth, imgheight);
  97. input_image_unorm8 = clCreateImage2D(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,&image_format, imgwidth, imgheight, 0, image_data_unorm8, &err);
  98. if (!input_image_unorm8 || err)
  99. {
  100. printf("clCreateImage2D() failed. (%d)\n", err);
  101. return EXIT_FAILURE;
  102. }
  103. image_format.image_channel_order = CL_RGBA;
  104. image_format.image_channel_data_type = CL_FLOAT;
  105. image_data_fp32 = create_image_data_fp32(imgwidth, imgheight);
  106. input_image_fp32 = clCreateImage2D(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,&image_format, imgwidth, imgheight, 0, image_data_fp32, &err);
  107. if (!input_image_fp32 || err)
  108. {
  109. printf("clCreateImage2D() failed. (%d)\n", err);
  110. return EXIT_FAILURE;
  111. }
  112. /************ Testing RGBA 8-bit histogram **********/
  113. size_t workgroup_size;
  114. size_t local_work_size[2],global_work_size[2];
  115. size_t num_groups;
  116. clGetKernelWorkGroupInfo(histogram_rgba_unorm8, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL);
  117. {
  118. size_t gsize[2];
  119. int w;
  120. if (workgroup_size <= 256)
  121. {
  122. gsize[0] = 16;
  123. gsize[1] = workgroup_size / 16;
  124. }
  125. else if (workgroup_size <= 1024)
  126. {
  127. gsize[0] = workgroup_size / 16;
  128. gsize[1] = 16;
  129. }
  130. else
  131. {
  132. gsize[0] = workgroup_size / 32;
  133. gsize[1] = 32;
  134. }
  135. local_work_size[0] = gsize[0];
  136. local_work_size[1] = gsize[1];
  137. w = (imgwidth + num_pixels_per_work_item - 1) / num_pixels_per_work_item;
  138. global_work_size[0] = ((w + gsize[0] - 1) / gsize[0]);
  139. global_work_size[1] = ((imgheight + gsize[1] - 1) / gsize[1]);
  140. num_groups = global_work_size[0] * global_work_size[1];
  141. global_work_size[0] *= gsize[0];
  142. global_work_size[1] *= gsize[1];
  143. }
  144. cl_mem partial_histogram_buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, num_groups*256*3*sizeof(unsigned int), NULL, &err);
  145. if (!partial_histogram_buffer || err)
  146. {
  147. printf("clCreateBuffer() failed. (%d)\n", err);
  148. return EXIT_FAILURE;
  149. }
  150. //clSetKernelArg(histogram_rgba_unorm8, 0, sizeof(cl_mem), &input_image_unorm8);
  151. clSetKernelArg(histogram_rgba_unorm8, 0, sizeof(cl_mem), &image);
  152. clSetKernelArg(histogram_rgba_unorm8, 1, sizeof(int), &num_pixels_per_work_item);
  153. clSetKernelArg(histogram_rgba_unorm8, 2, sizeof(cl_mem), &partial_histogram_buffer);
  154. clSetKernelArg(histogram_sum_partial_results_unorm8, 0, sizeof(cl_mem), &partial_histogram_buffer);
  155. clSetKernelArg(histogram_sum_partial_results_unorm8, 1, sizeof(int), &num_groups);
  156. clSetKernelArg(histogram_sum_partial_results_unorm8, 2, sizeof(cl_mem), &histogram_buffer);
  157. // verify that the kernel works correctly. also acts as a warmup
  158. err = clEnqueueNDRangeKernel(queue, histogram_rgba_unorm8, 2, NULL, global_work_size, local_work_size, 0, NULL, NULL);
  159. unsigned int *partial_histogram_results = (unsigned int *)malloc(num_groups*256*3*sizeof(unsigned int));
  160. err = clEnqueueReadBuffer(queue, partial_histogram_buffer, CL_TRUE, 0, num_groups*256*3*sizeof(unsigned int), partial_histogram_results, 0, NULL, NULL);
  161. for(int j=0;j<num_groups;j++){
  162. int ind=j*256*3;
  163. for(int i=0;i<256*3;i++){
  164. printf("the %dth work-group: R:%d G:%d B:%d \n",j+1,partial_histogram_results[ind+i],partial_histogram_results[ind+256+i],partial_histogram_results[ind+512+i]);
  165. }
  166. }
  167. // verify that the kernel works correctly. also acts as a warmup
  168. clGetKernelWorkGroupInfo(histogram_sum_partial_results_unorm8, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), &workgroup_size, NULL);
  169. size_t partial_global_work_size[2],partial_local_work_size[2];
  170. partial_global_work_size[0] = 256*3;
  171. partial_local_work_size[0] = (workgroup_size > 256) ? 256 : workgroup_size;
  172. err = clEnqueueNDRangeKernel(queue, histogram_sum_partial_results_unorm8, 1, NULL, partial_global_work_size, partial_local_work_size, 0, NULL, NULL);
  173. unsigned int *ref_histogram_results = (unsigned int *)generate_reference_histogram_results_unorm8(image_data_unorm8, imgwidth, imgheight);
  174. unsigned int *histogram_results = (unsigned int *)malloc(256*3*sizeof(unsigned int));
  175. err = clEnqueueReadBuffer(queue, histogram_buffer, CL_TRUE, 0, 256*3*sizeof(unsigned int), histogram_results, 0, NULL, NULL);
  176. if (err)
  177. {
  178. printf("clEnqueueReadBuffer() failed. (%d)\n", err);
  179. return EXIT_FAILURE;
  180. }
  181. verify_histogram_results("Image Histogram for image type = CL_RGBA, CL_UNORM_INT8", histogram_results, ref_histogram_results, 256*3);
  182. // for(int i=0;i <256*3;i++){
  183. // printf("R:%d G:%d B:%d \n",histogram_results[i],histogram_results[256+i],histogram_results[512+i]);
  184. // }
  185. // now measure performance
  186. cl_event events[2];
  187. err = clEnqueueMarker(queue, &events[0]);
  188. if (err)
  189. {
  190. printf("clEnqeueMarker() failed for histogram_rgba_unorm8 kernel. (%d)\n", err);
  191. return EXIT_FAILURE;
  192. }
  193. for (int i=0; i<num_iterations; i++)
  194. {
  195. err = clEnqueueNDRangeKernel(queue, histogram_rgba_unorm8, 2, NULL, global_work_size, local_work_size, 0, NULL, NULL);
  196. if (err)
  197. {
  198. printf("clEnqueueNDRangeKernel() failed for histogram_rgba_unorm8 kernel. (%d)\n", err);
  199. return EXIT_FAILURE;
  200. }
  201. err = clEnqueueNDRangeKernel(queue, histogram_sum_partial_results_unorm8, 1, NULL, partial_global_work_size, partial_local_work_size, 0, NULL, NULL);
  202. if (err)
  203. {
  204. printf("clEnqueueNDRangeKernel() failed for histogram_sum_partial_results_unorm8 kernel. (%d)\n", err);
  205. return EXIT_FAILURE;
  206. }
  207. }
  208. err = clEnqueueMarker(queue, &events[1]);
  209. if (err)
  210. {
  211. printf("clEnqeueMarker() failed for histogram_rgba_unorm8 kernel. (%d)\n", err);
  212. return EXIT_FAILURE;
  213. }
  214. err = clWaitForEvents(1, &events[1]);
  215. if (err)
  216. {
  217. printf("clWaitForEvents() failed for histogram_rgba_unorm8 kernel. (%d)\n", err);
  218. return EXIT_FAILURE;
  219. }
  220. cl_ulong time_start,time_end;
  221. err = clGetEventProfilingInfo(events[0], CL_PROFILING_COMMAND_QUEUED, sizeof(cl_long), &time_start, NULL);
  222. err |= clGetEventProfilingInfo(events[1], CL_PROFILING_COMMAND_END, sizeof(cl_long), &time_end, NULL);
  223. if (err)
  224. {
  225. printf("clGetEventProfilingInfo() failed for histogram_rgba_unorm8 kernel. (%d)\n", err);
  226. return EXIT_FAILURE;
  227. }
  228. printf("Image dimensions: %d x %d pixels, Image type = CL_RGBA, CL_UNORM_INT8\n", imgwidth, imgheight);
  229. printf("Time to compute histogram = %g ms\n", (double)(time_end - time_start) * 1e-9 * 1000.0 / (double)num_iterations);
  230. clReleaseEvent(events[0]);
  231. clReleaseEvent(events[1]);
  232. free(ref_histogram_results);
  233. free(histogram_results);
  234. free(image_data_unorm8);
  235. free(image_data_fp32);
  236. clReleaseKernel(histogram_rgba_unorm8);
  237. //clReleaseKernel(histogram_rgba_fp);
  238. clReleaseKernel(histogram_sum_partial_results_unorm8);
  239. //clReleaseKernel(histogram_sum_partial_results_fp);
  240. clReleaseProgram(program);
  241. clReleaseMemObject(partial_histogram_buffer);
  242. clReleaseMemObject(histogram_buffer);
  243. clReleaseMemObject(input_image_unorm8);
  244. clReleaseMemObject(input_image_fp32);
  245. clReleaseCommandQueue(queue);
  246. clReleaseContext(context);
  247. return EXIT_SUCCESS;
  248. }
  249. static void * create_image_data_unorm8(int w, int h)
  250. {
  251. unsigned char *p = (unsigned char *)malloc(w * h * 4);
  252. int i;
  253. for (i=0; i<w*h*4; i++)
  254. p[i] = (unsigned char)(rand() & 0xFF);
  255. return (void *)p;
  256. }
  257. static void * generate_reference_histogram_results_unorm8(void *image_data, int w, int h)
  258. {
  259. unsigned int *ref_histogram_results = (unsigned int *)malloc(256 * 3 * sizeof(unsigned int));
  260. unsigned char *img = (unsigned char *)image_data;
  261. unsigned int *ptr = ref_histogram_results;
  262. int i;
  263. memset(ref_histogram_results, 0x0, 256 * 3 * sizeof(unsigned int));
  264. for (i=0; i<w*h*4; i+=4)
  265. {
  266. int indx = img[i];
  267. ptr[indx]++;
  268. }
  269. ptr += 256;
  270. for (i=1; i<w*h*4; i+=4)
  271. {
  272. int indx = img[i];
  273. ptr[indx]++;
  274. }
  275. ptr += 256;
  276. for (i=2; i<w*h*4; i+=4)
  277. {
  278. int indx = img[i];
  279. ptr[indx]++;
  280. }
  281. return ref_histogram_results;
  282. }
  283. static void * create_image_data_fp32(int w, int h)
  284. {
  285. float *p = (float *)malloc(w * h * 4 * sizeof(float));
  286. int i;
  287. for (i=0; i<w*h*4; i++)
  288. p[i] = (float)rand() / (float)RAND_MAX;
  289. return (void *)p;
  290. }
  291. static void * generate_reference_histogram_results_fp32(void *image_data, int w, int h)
  292. {
  293. unsigned int *ref_histogram_results = (unsigned int *)malloc(256 * 3 * sizeof(unsigned int));
  294. float *img = (float *)image_data;
  295. unsigned int *ptr = ref_histogram_results;
  296. int i;
  297. memset(ref_histogram_results, 0x0, 256 * 3 * sizeof(unsigned int));
  298. for (i=0; i<w*h*4; i+=4)
  299. {
  300. float f = img[i];
  301. unsigned int indx;
  302. if (f > 1.0f)
  303. f = 1.0f;
  304. f *= 256.0f;
  305. indx = (unsigned int)f;
  306. ptr[indx]++;
  307. }
  308. ptr += 256;
  309. for (i=1; i <w*h*4; i+=4)
  310. {
  311. float f = img[i];
  312. unsigned int indx;
  313. if ( f > 1.0f)
  314. f = 1.0f;
  315. f *= 256.0f;
  316. indx = (unsigned int)f;
  317. ptr[indx]++;
  318. }
  319. ptr += 256;
  320. for (i=2; i <w*h*4; i+=4)
  321. {
  322. float f = img[i];
  323. unsigned int indx;
  324. if ( f > 1.0f)
  325. f = 1.0f;
  326. f *= 256.0f;
  327. indx = (unsigned int)f;
  328. ptr[indx]++;
  329. }
  330. return ref_histogram_results;
  331. }
  332. static int verify_histogram_results(const char *str, unsigned int *histogram_results, unsigned int *ref_histogram_results, int num_entries)
  333. {
  334. int i;
  335. for (i=0; i <num_entries; i++)
  336. {
  337. if (histogram_results[i] != ref_histogram_results[i])
  338. {
  339. printf("%s: verify_histogram_results failed for indx = %d, gpu result = %d, expected result = %d\n",
  340. str, i, histogram_results[i], ref_histogram_results[i]);
  341. return -1;
  342. }
  343. }
  344. printf("%s: VERIFIED\n", str);
  345. return 0;
  346. }
  347. static int read_kernel_from_file(const char *filename, char **source, size_t *len)
  348. {
  349. struct stat statbuf;
  350. FILE *fh;
  351. size_t file_len;
  352. fh = fopen(filename, "r");
  353. if (fh == 0)
  354. return -1;
  355. stat(filename, &statbuf);
  356. file_len = (size_t)statbuf.st_size;
  357. *len = file_len;
  358. *source = (char *) malloc(file_len+1);
  359. fread(*source, file_len, 1, fh);
  360. (*source)[file_len] = '\0';
  361. fclose(fh);
  362. return 0;
  363. }
  364. cl_mem LoadImage(cl_context context, char *fileName, int &width, int &height)
  365. {
  366. FREE_IMAGE_FORMAT format = FreeImage_GetFileType(fileName, 0);
  367. FIBITMAP* image = FreeImage_Load(format, fileName);
  368. // Convert to 32-bit image
  369. FIBITMAP* temp = image;
  370. image = FreeImage_ConvertTo32Bits(image);
  371. FreeImage_Unload(temp);
  372. width = FreeImage_GetWidth(image);
  373. height = FreeImage_GetHeight(image);
  374. char *buffer = new char[width * height * 4];
  375. memcpy(buffer, FreeImage_GetBits(image), width * height * 4);
  376. FreeImage_Unload(image);
  377. // Create OpenCL image
  378. cl_image_format clImageFormat;
  379. clImageFormat.image_channel_order = CL_RGBA;
  380. clImageFormat.image_channel_data_type = CL_UNORM_INT8;
  381. cl_int errNum;
  382. cl_mem clImage;
  383. clImage = clCreateImage2D(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,&clImageFormat,width,height, 0,buffer,&errNum);
  384. if (errNum != CL_SUCCESS)
  385. {
  386. std::cerr << "Error creating CL image object" << std::endl;
  387. return 0;
  388. }
  389. return clImage;
  390. }
接下来是2个kernel:


 
 
  1. __kernel void histogram_local(__read_only image2d_t img, int num_pixels_per_workitem, global uint *histogram)
  2. {
  3.     int     local_size = (int)get_local_size(0) * (int)get_local_size(1);
  4.     int     image_width = get_image_width(img);
  5.     int     image_height = get_image_height(img);
  6.     //int     group_indx = mad24(get_group_id(1), get_num_groups(0), get_group_id(0)) * 256 * 3;
  7.     int group_indx=(get_group_id(1)*get_num_groups(0)+get_group_id(0))*256*3;
  8.     int     x = get_global_id(0);
  9.     int     y = get_global_id(1);
  10.     
  11.     local uint  tmp_histogram[256 * 3];
  12.         
  13.     //int     tid = mad24(get_local_id(1), get_local_size(0), get_local_id(0));
  14.     int tid=get_local_id(1)*get_local_size(0)+get_local_id(0);
  15.     int     j = 256 * 3;
  16.     int     indx = 0;
  17.     
  18.     // clear the local buffer that will generate the partial histogram
  19.     do
  20.     {
  21.         if (tid < j)
  22.             tmp_histogram[ indx+ tid] = 0;
  23.         j -= local_size;
  24.         indx += local_size;
  25.     } while ( j > 0);
  26.     
  27.     barrier(CLK_LOCAL_MEM_FENCE);
  28.     
  29.     const sampler_t sampler=CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;
  30.     if ((x < image_width) && (y < image_height))
  31.     {                
  32.         float4 clr = read_imagef(img, sampler, (float2)(x, y));
  33.         uchar   indx_x, indx_y, indx_z;
  34.         indx_x = convert_uchar_sat(clr.x * 255.0f);
  35.         indx_y = convert_uchar_sat(clr.y * 255.0f);
  36.         indx_z = convert_uchar_sat(clr.z * 255.0f);
  37.         
  38.         atom_inc(&tmp_histogram[indx_x]);
  39.         atom_inc(&tmp_histogram[256+(uint)indx_y]);
  40.         atom_inc(&tmp_histogram[512+(uint)indx_z]);
  41.     }
  42.     
  43.     
  44.     barrier(CLK_LOCAL_MEM_FENCE);
  45.     // copy the partial histogram to appropriate location in histogram given by group_indx
  46.     if (local_size >= (256 * 3))
  47.     {
  48.         if (tid < (256 * 3))
  49.             histogram[ group_indx + tid] = tmp_histogram[tid];
  50.     }
  51.     else
  52.     {
  53.         j = 256 * 3;
  54.         indx = 0;
  55.         do 
  56.         {
  57.             if ( tid < j)
  58.                 histogram[ group_indx + indx + tid] = tmp_histogram[indx + tid];
  59.                 
  60.             j -= local_size;
  61.             indx += local_size;
  62.         } while ( j > 0);
  63.     }
  64. }

 
 
  1. __kernel void histogram_global(global uint *partial_histogram, int num_groups, global uint *histogram)
  2. {
  3. int tid = (int)get_global_id(0);
  4. int group_indx;
  5. int n = num_groups;
  6. local uint tmp_histogram[256*3];
  7. tmp_histogram[tid] = partial_histogram[tid];
  8. group_indx = 256*3;
  9. while (--n > 0)
  10. {
  11. tmp_histogram[tid] += partial_histogram[group_indx + tid];
  12. group_indx += 256*3;
  13. }
  14. histogram[tid] = tmp_histogram[tid];
  15. }
但出来结果不对:将rgb的值打印出来又是无意义的值!???



好烦躁啊!!!!!!!!!!!!!!!!


书上的案例部分代码晦涩难懂,大神给我的建议是 “kernel最快的应当直接使用buffer读取的, 用image, 然后做一个空间方块型的读取,用来做直方图统计, 这无意义。 因为最终结果只会这些像素点本身有关, 而和你是否按照特定的顺序读取无关。 使用image额外增加了创建成image的数据格式, 和读取时候的代价。而且使用临近的方块区域读取, 因为图像本身的性质, 很可能像素值接近甚至相同, 这增加了在__local上进行原子+1统计时候的冲突风险。 从而会降低性能。 而直接简单平铺work-items, 例如按行读取, 不仅具有访存上的优势(例如,减少了刚才说的转换成image的后备存储格式(你的host上将图像转换为cl_mem的那个wrapper函数)的代价),而且还可以尽量降低像素值上的相关性。 避免对同一个__local的bank的访问,从而可能的提高性能。 第二个kernel建立了__local上的数组,然后每个线程只使用其中的独一无二的一个元素。这毫无意义。这种线程间完全无交流的, 却使用了共享的__local数组,除了用来迷惑, 毫无用途。建议修正。”   据说不应该学习。还是按照https://chenxiaowei.gitbooks.io/heterogeneous-computing-with-opencl2-0/content/content/chapter4/4.2-chinese.html   上的,亲测 https://chenxiaowei.gitbooks.io/heterogeneous-computing-with-opencl2-0/content/content/chapter4/4.2-chinese.html  通过。虽然这是计算的一幅灰度图的。
对于这个正确书写的kernel:


 
 
  1. #define HIST_BINS 256
  2. __kernel void histogram(__global int *data,int numData, __global int *histogram){
  3. __local int localHistorgram[HIST_BINS];
  4. int lid = get_local_id(0);
  5. /* Initialize local histogram to zero */
  6. for (int i = lid; i < HIST_BINS; i += get_local_size(0)){
  7. localHistorgram[i] = 0;
  8. }
  9. /* Wait nutil all work-items within
  10. * the work-group have completed their stores */
  11. barrier(CLK_LOCAL_MEM_FENCE);
  12. /* Compute local histogram */
  13. int gid = get_global_id(0);
  14. for (int i = gid; i < numData; i += get_global_size(0)){
  15. atomic_add(&(localHistorgram[data[i]]), 1);
  16. }
  17. /* Wait nutil all work-items within
  18. * the work-group have completed their stores */
  19. barrier(CLK_LOCAL_MEM_FENCE);
  20. /* Write the local histogram out to
  21. * the global histogram */
  22. for (int i = lid; i < HIST_BINS; i += get_local_size(0)){
  23. atomic_add(&(histogram[i]), localHistorgram[i]);
  24. }
  25. }
我之前是这样理解的:

所以我怎么也想不明白 ,对于globalsize=1024 在第一个for循环清零后,其实只有4个局部结果被清零 而这个程序的本意是每个工作组有一个局部直方图结果  可是现在只有4个啊  而公共16个工作组啊 ?!我之前一直停留在这里。

后来通过和一个CUDA大神讨论 @UFO&ET 恍然明白,原来是下面这样:

其实就是对于第一个工作组的256个结果 是由第一个工作组中的每1个人邀请自己后面对应位置的3个人 去给256数组的对应位置清零的。  对于第二个工作组的256个结果,是由第二个工作组中的每1个人去邀请后面对应位置的3个伙伴去给第二个工作组家的256数组对应位置清零。   其实对于第二个工作组中每个人都给自己和前一个工作组一共帮了两次忙。一个64大小的workgroup做完  其实结果就是清零了一个localHistogram。 那么16个工作组肯定清零16个256,而不是像我上面画的“就地” In-place的 关系  不是在那个位置上。其实localHistogram这个变量  可能包括后面的data变量和全局结果Histogram变量 都只是借助每个workitem的ID  才完成自己的计算。总算明白了,我是个对“抽象”看不见摸不着的东西反应比较慢理解不太容易的人!这个问题我真的想了挺久的。想明白以后才觉得自己竟然思考这么简单的问题思考了这么久,蠢得跟猪一样,难怪问问题会被大神们鄙视。说真的 当理解时就觉得简单,不理解时真的觉得难。

谁来做这个计算,就下标是谁。localHistogram 下标用每个工作项的ID  而不是直接像我以前一样用0---255  ,因为以前是串行!
那个大神画的这幅图更清晰:

向下到第16次!

至于后两个for循环 我也理解了:





另外对于事件机制同步点那里 非常感谢这个大神http://blog.csdn.net/bob_dong/article/details/70172165#reply 写了这篇文章,我懂了很多。如果用clWaitForEvents,那么host端的后续程序要等clWaitForEvents规定的那些事件完成后才能往下执行,如果用clEnqueueWaitForEvents那么queue中的后续命令要等待clEnqueueWaitForEvents之前的所有命令执行完,但host端不用等待,可以与clEnqueueWaitForEvents之前的命令同时运行。


尝试着自己仿照写了一个rgb彩图的直方图计算:


 
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <iostream>
  5. #include <CL/cl.h>
  6. #include "gFreeImage.h"
  7. static const int HIST_BINS = 256;
  8. void check(cl_int status);
  9. char* readFile(const char *filename);
  10. int main()
  11. {
  12. int imageCols, imageRows;
  13. gFreeImage img;
  14. int readflag=img.LoadImage("/home/jumper/OpenCL_projects/Book_ch14_Histogram/lenna.jpg");
  15. unsigned char *hInputImage = img.getImageData(imageCols,imageRows);
  16. const int imageElements = imageRows*imageCols;
  17. const size_t imageSize = imageElements*sizeof(unsigned char)*4;
  18. const int histogramSize = HIST_BINS*sizeof(int)*3;
  19. int *hOutputHistogram = (int*)malloc(histogramSize);
  20. if (!hOutputHistogram) { exit(-1); }
  21. cl_int status;
  22. cl_platform_id platform;
  23. status = clGetPlatformIDs(1, &platform, NULL);
  24. check(status);
  25. cl_device_id device;
  26. status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
  27. check(status);
  28. cl_context context;
  29. context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
  30. check(status);
  31. cl_command_queue cmdQueue=clCreateCommandQueue(context, device, 0, &status);
  32. check(status);
  33. cl_mem bufInputImage = clCreateBuffer(context, CL_MEM_READ_ONLY, imageSize, NULL,&status);
  34. check(status);
  35. cl_mem bufOutputHistogram = clCreateBuffer(context, CL_MEM_WRITE_ONLY,histogramSize, NULL, &status);
  36. check(status);
  37. status = clEnqueueWriteBuffer(cmdQueue, bufInputImage, CL_TRUE, 0, imageSize,(void*)hInputImage, 0, NULL, NULL);
  38. check(status);
  39. int zero = 0;
  40. status = clEnqueueFillBuffer(cmdQueue, bufOutputHistogram, &zero,sizeof(int), 0, histogramSize, 0, NULL, NULL);
  41. check(status);
  42. /* Create a program with source code */
  43. char *programSource = readFile("/home/jumper/OpenCL_projects/Book_ch14_Histogram/rgbHistogram.cl");
  44. size_t programSourceLen = strlen(programSource);
  45. cl_program program = clCreateProgramWithSource(context, 1,(const char**)&programSource, &programSourceLen, &status);
  46. check(status);
  47. status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
  48. //std::cout <<status<<std::endl;
  49. if (status != CL_SUCCESS) {
  50. printf("cannot build program successfully!\n");
  51. size_t logSize;
  52. status = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &logSize);
  53. char *log = (char*)malloc(logSize);
  54. status = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,logSize, log, NULL);
  55. printf("%s\n", log);
  56. exit(-1);
  57. }
  58. cl_kernel kernel;
  59. kernel = clCreateKernel(program, "histogramforRGB", &status);
  60. check(status);
  61. status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufInputImage);
  62. status |= clSetKernelArg(kernel, 1, sizeof(int), &imageElements);
  63. status |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufOutputHistogram);
  64. check(status);
  65. size_t globalWorkSize[1];
  66. globalWorkSize[0] = 1024;
  67. size_t localWorkSize[1];
  68. localWorkSize[0] = 64;
  69. status = clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL,globalWorkSize, localWorkSize, 0, NULL, NULL);
  70. check(status);
  71. status = clEnqueueReadBuffer(cmdQueue, bufOutputHistogram, CL_TRUE, 0,histogramSize, hOutputHistogram, 0, NULL, NULL);
  72. check(status);
  73. for (int i = 0; i < HIST_BINS; i+=3) {
  74. printf("histogram%d R:%d G:%d B:%d \n",i,hOutputHistogram[i],hOutputHistogram[1+i],hOutputHistogram[2+i]);
  75. }
  76. clReleaseKernel(kernel);
  77. clReleaseProgram(program);
  78. clReleaseCommandQueue(cmdQueue);
  79. clReleaseMemObject(bufInputImage);
  80. clReleaseMemObject(bufOutputHistogram);
  81. clReleaseContext(context);
  82. free(hOutputHistogram);
  83. free(programSource);
  84. return 0;
  85. }

kernel函数部分:


 
 
  1. #define HIST_BINS 256
  2. __kernel void histogramforRGB(__global unsigned char *data,int numData, __global int *histogram){
  3. __local int localHistorgram[HIST_BINS*3];
  4. int lid = get_local_id(0);
  5. //for (int i = lid; i < HIST_BINS; i += get_local_size(0)){
  6. // localHistorgram[i] = 0;
  7. // localHistorgram[256+i] = 0;
  8. // localHistorgram[512+i] = 0;
  9. //}
  10. //codes below faster!
  11. for (int i = lid; i < HIST_BINS*3; i += get_local_size(0)){
  12. localHistorgram[i] = 0;
  13. }
  14. barrier(CLK_LOCAL_MEM_FENCE);
  15. int gid = get_global_id(0);
  16. for (int i = gid; i < numData*3; i += get_global_size(0)){
  17. atomic_add(&(localHistorgram[data[i]]), 1);
  18. }
  19. barrier(CLK_LOCAL_MEM_FENCE);
  20. for (int i = lid; i < HIST_BINS*3; i += get_local_size(0)){
  21. atomic_add(&(histogram[i]), localHistorgram[i]);
  22. }
  23. }
结果:


怎么办 我不知道我写的这个正确与否。

经过大神提示:http://bbs.gpuworld.cn/forum.php?mod=viewthread&tid=10651&page=1#pid19338 意识到问题  首先图像数据data是RGBARGBARGBA...这样排列的,但我第二个for循环中 是将图像像素点的RGBARGBARGBA....分别统计 却遗留了剩下的1/4像素点没有统计   然后将这RGB、ARG、BAR、.....当成了我想要的.....是错的。

二、自己修改后:

kernel函数:


 
 
  1. #define HIST_BINS 256
  2. __kernel void histogramforRGB(__global unsigned char *data,int numData, __global int *histogram){
  3. __local int localHistorgram[HIST_BINS*4];
  4. int lid = get_local_id(0);
  5. for (int i = lid; i < HIST_BINS*4; i += get_local_size(0)){
  6. localHistorgram[i] = 0;
  7. }
  8. barrier(CLK_LOCAL_MEM_FENCE);
  9. int gid = get_global_id(0);
  10. for (int i = gid; i < numData*4; i += get_global_size(0)){
  11. atomic_add(&(localHistorgram[data[i]]), 1);
  12. }
  13. barrier(CLK_LOCAL_MEM_FENCE);
  14. for (int i = lid; i < HIST_BINS*4; i += get_local_size(0)){
  15. atomic_add(&(histogram[i]), localHistorgram[i]);
  16. }
  17. }
host端也要修改一点:

总共两处地方,第一个是kernel的直方图结果拷贝回host端的变量大小:

const int histogramSize = HIST_BINS*sizeof(int)*4;
 
 

还有就是打印那里:


 
 
  1. int j=0;
  2. for (int i = 0; i < HIST_BINS*4; i+=4) {
  3. printf("histogram%d R:%d G:%d B:%d \n",j,hOutputHistogram[i],hOutputHistogram[1+i],hOutputHistogram[2+i]);
  4. j++;
  5. }

但是结果看起来怪怪的!

这个是错的:因为:第二个for循环那里就开始加 混乱了:


正确的是下面的:


 
 
  1. #define HIST_BINS 256
  2. __kernel void histogramforRGB(__global unsigned char *data,int numData, __global int *histogramR, __global int *histogramG, __global int *histogramB){
  3. __local int localHistorgramR[HIST_BINS];
  4. __local int localHistorgramG[HIST_BINS];
  5. __local int localHistorgramB[HIST_BINS];
  6. int lid = get_local_id(0);
  7. for (int i = lid; i < HIST_BINS; i += get_local_size(0)){
  8. localHistorgramR[i] = 0;
  9. localHistorgramG[i] = 0;
  10. localHistorgramB[i] = 0;
  11. }
  12. barrier(CLK_LOCAL_MEM_FENCE);
  13. int gid = get_global_id(0);
  14. for (int i = gid; i < numData*4; i += get_global_size(0)){
  15. if(i%4==0)
  16. {
  17. atomic_add(&(localHistorgramR[data[i]]), 1);
  18. continue;
  19. }
  20. if(i%4==1)
  21. {
  22. atomic_add(&(localHistorgramG[data[i]]), 1);
  23. continue;
  24. }
  25. if(i%4==2)
  26. {
  27. atomic_add(&(localHistorgramB[data[i]]), 1);
  28. continue;
  29. }
  30. }
  31. barrier(CLK_LOCAL_MEM_FENCE);
  32. for (int i = lid; i < HIST_BINS; i += get_local_size(0)){
  33. atomic_add(&(histogramR[i]), localHistorgramR[i]);
  34. atomic_add(&(histogramG[i]), localHistorgramG[i]);
  35. atomic_add(&(histogramB[i]), localHistorgramB[i]);
  36. }
  37. }
host端的:


 
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <iostream>
  5. /* OpenCL includes */
  6. #include <CL/cl.h>
  7. #include "gFreeImage.h"
  8. static const int HIST_BINS = 256;
  9. void check(cl_int status);
  10. char* readFile(const char *filename);
  11. int main()
  12. {
  13. int imageCols, imageRows;
  14. gFreeImage img;
  15. int readflag=img.LoadImage("/home/jumper/OpenCL_projects/Book_ch14_Histogram/lenna.jpg");
  16. unsigned char *hInputImage = img.getImageData(imageCols,imageRows);
  17. const int imageElements = imageRows*imageCols;
  18. const size_t imageSize = imageElements*sizeof(unsigned char)*4;
  19. const int histogramSize = HIST_BINS*sizeof(int);
  20. int *hOutputHistogramR = (int*)malloc(histogramSize);
  21. int *hOutputHistogramG = (int*)malloc(histogramSize);
  22. int *hOutputHistogramB = (int*)malloc(histogramSize);
  23. cl_int status;
  24. cl_platform_id platform;
  25. status = clGetPlatformIDs(1, &platform, NULL);
  26. check(status);
  27. cl_device_id device;
  28. status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, NULL);
  29. check(status);
  30. cl_context context;
  31. context = clCreateContext(NULL, 1, &device, NULL, NULL, &status);
  32. check(status);
  33. cl_command_queue cmdQueue=clCreateCommandQueue(context, device, 0, &status);
  34. check(status);
  35. cl_mem bufInputImage = clCreateBuffer(context, CL_MEM_READ_ONLY, imageSize, NULL,&status);
  36. check(status);
  37. cl_mem bufOutputHistogramR = clCreateBuffer(context, CL_MEM_WRITE_ONLY,histogramSize, NULL, &status);
  38. cl_mem bufOutputHistogramG = clCreateBuffer(context, CL_MEM_WRITE_ONLY,histogramSize, NULL, &status);
  39. cl_mem bufOutputHistogramB = clCreateBuffer(context, CL_MEM_WRITE_ONLY,histogramSize, NULL, &status);
  40. check(status);
  41. status = clEnqueueWriteBuffer(cmdQueue, bufInputImage, CL_TRUE, 0, imageSize,(void*)hInputImage, 0, NULL, NULL);
  42. check(status);
  43. int zero = 0;
  44. status = clEnqueueFillBuffer(cmdQueue, bufOutputHistogramR, &zero,sizeof(int), 0, histogramSize, 0, NULL, NULL);
  45. status = clEnqueueFillBuffer(cmdQueue, bufOutputHistogramG, &zero,sizeof(int), 0, histogramSize, 0, NULL, NULL);
  46. status = clEnqueueFillBuffer(cmdQueue, bufOutputHistogramB, &zero,sizeof(int), 0, histogramSize, 0, NULL, NULL);
  47. check(status);
  48. /* Create a program with source code */
  49. char *programSource = readFile("/home/jumper/OpenCL_projects/Book_ch14_Histogram/rgbHistogram.cl");
  50. size_t programSourceLen = strlen(programSource);
  51. cl_program program = clCreateProgramWithSource(context, 1,(const char**)&programSource, &programSourceLen, &status);
  52. check(status);
  53. status = clBuildProgram(program, 1, &device, NULL, NULL, NULL);
  54. //std::cout <<status<<std::endl;
  55. if (status != CL_SUCCESS) {
  56. printf("cannot build program successfully!\n");
  57. size_t logSize;
  58. status = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &logSize);
  59. char *log = (char*)malloc(logSize);
  60. status = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,logSize, log, NULL);
  61. printf("%s\n", log);
  62. exit(-1);
  63. }
  64. cl_kernel kernel;
  65. kernel = clCreateKernel(program, "histogramforRGB", &status);
  66. check(status);
  67. status = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufInputImage);
  68. status |= clSetKernelArg(kernel, 1, sizeof(int), &imageElements);
  69. status |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufOutputHistogramR);
  70. status |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &bufOutputHistogramG);
  71. status |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &bufOutputHistogramB);
  72. check(status);
  73. size_t globalWorkSize[1];
  74. globalWorkSize[0] = 1024;
  75. size_t localWorkSize[1];
  76. localWorkSize[0] = 64;
  77. status = clEnqueueNDRangeKernel(cmdQueue, kernel, 1, NULL,globalWorkSize, localWorkSize, 0, NULL, NULL);
  78. check(status);
  79. status = clEnqueueReadBuffer(cmdQueue, bufOutputHistogramR, CL_TRUE, 0,histogramSize, hOutputHistogramR, 0, NULL, NULL);
  80. status = clEnqueueReadBuffer(cmdQueue, bufOutputHistogramG, CL_TRUE, 0,histogramSize, hOutputHistogramG, 0, NULL, NULL);
  81. status = clEnqueueReadBuffer(cmdQueue, bufOutputHistogramB, CL_TRUE, 0,histogramSize, hOutputHistogramB, 0, NULL, NULL);
  82. check(status);
  83. for (int i = 0; i < HIST_BINS; i++) {
  84. printf("histogram%d R:%d G:%d B:%d\n",i,hOutputHistogramR[i],hOutputHistogramG[i],hOutputHistogramB[i]);
  85. }
  86. clReleaseKernel(kernel);
  87. clReleaseProgram(program);
  88. clReleaseCommandQueue(cmdQueue);
  89. clReleaseMemObject(bufInputImage);
  90. clReleaseMemObject(bufOutputHistogramR);
  91. clReleaseMemObject(bufOutputHistogramG);
  92. clReleaseMemObject(bufOutputHistogramB);
  93. clReleaseContext(context);
  94. free(hOutputHistogramR);
  95. free(hOutputHistogramG);
  96. free(hOutputHistogramB);
  97. free(programSource);
  98. return 0;
  99. }
结果:


可以告一段落了。

或者像大神所说这样写也行: http://bbs.gpuworld.cn/foru

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值