Statistiques
| Révision :

root / Pi / C / OpenCL / PiOpenCL_MWC.c @ 308

Historique | Voir | Annoter | Télécharger (15,06 ko)

1
// Pi Dart Dash in OpenCL in C, illustrative example
2
//
3
// Emmanuel Quemener <emmanuel.quemener@gmail.com>
4
//
5
// CC BY-NC-SA 2011 : Emmanuel QUEMENER <emmanuel.quemener@gmail.com> 
6
// Copyleft Cecill v2
7
//
8
// -h : print the documentation and detect devices as (platform,device)
9
//
10
// classical use:
11
// #1 OpenCL Plateform ID: get this information with -h option
12
// #2 OpenCL Device ID: get this information with -h option
13
// #3 Minimal number of iterations: 
14
// #4 Parallel Rate: scattering global work in parts executed //ly
15
// #5 Loops (to improve statistics)
16
// #6 Type of variables INT32, INT64, FP32, FP64
17
// 
18
// To compile : gcc -o PiOpenCL PiOpenCL.c -lOpenCL -lm
19

    
20
#define CL_TARGET_OPENCL_VERSION 220
21
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
#include <CL/cl.h>
26
#include <stdint.h>
27
#include <math.h>
28
#include <sys/time.h>
29

    
30
#define TINT32 0
31
#define TINT64 1
32
#define TFP32 2
33
#define TFP64 3
34

    
35
int DetectOpenCLDevices(void) 
36
{
37
  int i, j;
38
  char* value;
39
  size_t valueSize;
40
  cl_uint platformCount;
41
  cl_platform_id* platforms;
42
  cl_uint deviceCount;
43
  cl_device_id* devices;
44
  cl_uint maxComputeUnits;
45
  cl_int maxWorkGroupSize;
46
  cl_int maxWorkItemSizes;
47
  cl_device_type dev_type;
48

    
49
  // get all platforms
50
  clGetPlatformIDs(0, NULL, &platformCount);
51
  platforms = (cl_platform_id*) malloc(sizeof(cl_platform_id) * platformCount);
52
  clGetPlatformIDs(platformCount, platforms, NULL);
53

    
54
  printf("OpenCL statistics: %d platform(s) detected\n\n",platformCount);
55

    
56
  for (i = 0; i < platformCount; i++) {
57

    
58
    // get all devices
59
    clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, 0, NULL, &deviceCount);
60
    devices = (cl_device_id*) malloc(sizeof(cl_device_id) * deviceCount);
61
    clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_ALL, deviceCount, devices, NULL);
62

    
63
    // for each device print critical attributes
64
    for (j = 0; j < deviceCount; j++) {
65
      
66
      // print device name
67
      clGetDeviceInfo(devices[j], CL_DEVICE_NAME, 0, NULL, &valueSize);
68
      value = (char*) malloc(valueSize);
69
      clGetDeviceInfo(devices[j], CL_DEVICE_NAME, valueSize, value, NULL);
70
      printf("Device (%d,%d): %s\n",i, j, value);
71
      free(value);
72

    
73
      // print type device CPU/GPU/ACCELERATOR
74
      clGetDeviceInfo(devices[j], CL_DEVICE_TYPE, sizeof(dev_type), &dev_type, NULL);
75
      printf("\tDevice Type: ");
76
      if(dev_type & CL_DEVICE_TYPE_GPU)
77
        printf("CL_DEVICE_TYPE_GPU ");
78
      if(dev_type & CL_DEVICE_TYPE_CPU)
79
        printf("CL_DEVICE_TYPE_CPU ");
80
      if(dev_type & CL_DEVICE_TYPE_ACCELERATOR)
81
        printf("CL_DEVICE_TYPE_ACCELERATOR ");
82
      if(dev_type & CL_DEVICE_TYPE_DEFAULT)
83
        printf("CL_DEVICE_TYPE_DEFAULT ");
84
      printf("\n");
85

    
86
      // print device vendor
87
      clGetDeviceInfo(devices[j], CL_DEVICE_VENDOR, 0, NULL, &valueSize);
88
      value = (char*) malloc(valueSize);
89
      clGetDeviceInfo(devices[j], CL_DEVICE_VENDOR, valueSize, value, NULL);
90
      printf("\tDevice vendor: %s\n", value);
91
      free(value);
92

    
93
      // print hardware device version
94
      clGetDeviceInfo(devices[j], CL_DEVICE_VERSION, 0, NULL, &valueSize);
95
      value = (char*) malloc(valueSize);
96
      clGetDeviceInfo(devices[j], CL_DEVICE_VERSION, valueSize, value, NULL);
97
      printf("\tHardware version: %s\n", value);
98
      free(value);
99

    
100
      // print software driver version
101
      clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, 0, NULL, &valueSize);
102
      value = (char*) malloc(valueSize);
103
      clGetDeviceInfo(devices[j], CL_DRIVER_VERSION, valueSize, value, NULL);
104
      printf("\tSoftware version: %s\n", value);
105
      free(value);
106
      
107
      // print c version supported by compiler for device
108
      clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, 0, NULL, &valueSize);
109
      value = (char*) malloc(valueSize);
110
      clGetDeviceInfo(devices[j], CL_DEVICE_OPENCL_C_VERSION, valueSize, value, NULL);
111
      printf("\tOpenCL C version: %s\n", value);
112
      free(value);
113

    
114
      // print parallel compute units
115
      clGetDeviceInfo(devices[j], CL_DEVICE_MAX_COMPUTE_UNITS,
116
                      sizeof(maxComputeUnits), &maxComputeUnits, NULL);
117
      printf("\tParallel compute units: %d\n", maxComputeUnits);
118
      
119
      // print max work group size
120
      clGetDeviceInfo(devices[j], CL_DEVICE_MAX_WORK_GROUP_SIZE,
121
                      sizeof(maxWorkGroupSize), &maxWorkGroupSize, NULL);
122
      printf("\tMaximum Work Group Size: %d\n", maxWorkGroupSize);
123
      
124
      // print max work items size
125
      clGetDeviceInfo(devices[j], CL_DEVICE_MAX_WORK_ITEM_SIZES,
126
                      sizeof(maxWorkItemSizes), &maxWorkItemSizes, NULL);
127
      printf("\tMaximum Work Item Sizes: %d\n", maxWorkItemSizes);
128
      
129
    }
130
    printf("\n");
131
    free(devices);
132
  }
133

    
134
  free(platforms);
135
  return 0;
136

    
137
}
138

    
139
const char* OpenCLSource[] = {
140
  "#pragma OPENCL EXTENSION cl_khr_fp64: enable \n",
141
  "// Marsaglia RNG very simple implementation \n",
142
  "#define znew  ((z=36969*(z&65535)+(z>>16))<<16) \n",
143
  "#define wnew  ((w=18000*(w&65535)+(w>>16))&65535) \n",
144
  "#define MWC   (znew+wnew) \n",
145
  "#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5)) \n",
146
  "#define CONG  (jcong=69069*jcong+1234567) \n",
147
  "#define KISS  ((MWC^CONG)+SHR3) \n",
148
  "#define MWCfp MWC * 2.328306435454494e-10f \n",
149
  "#define KISSfp KISS * 2.328306435454494e-10f \n",
150
  "#define CONGfp CONG * 2.328306435454494e-10f \n",
151
  "#define SHR3fp SHR3 * 2.328306435454494e-10f \n",
152
  "#define TINT32 0 \n",
153
  "#define TINT64 1 \n",
154
  "#define TFP32 2 \n",
155
  "#define TFP64 3 \n",
156
  "#define THEONE32I 1073741824 \n",
157
  "#define THEONE32F 1.e0f \n",
158
  "#define THEONE64I 4611686018427387904 \n",
159
  "#define THEONE64F (double)1.e0f \n",
160
  "ulong MainLoop32I(ulong iterations,uint seed_z,uint seed_w,size_t work)",
161
  "{",
162
  "   uint z=seed_z+work;",
163
  "   uint w=seed_w+work;",
164
  "   ulong total=0;",
165
  "   for (ulong i=0;i<iterations;i++)",
166
  "   {",
167
  "      uint x= MWC>>17;",
168
  "      uint y= MWC>>17;",
169
  "      ulong inside=((x*x+y*y) <= THEONE32I) ? 1:0;",
170
  "      total+=inside;",
171
  "   }",
172
  "   return(total);",
173
  "}",
174
  "ulong MainLoop32F(ulong iterations,uint seed_z,uint seed_w,size_t work)",
175
  "{",
176
  "   uint z=seed_z+work;",
177
  "   uint w=seed_w+work;",
178
  "   ulong total=0;",
179
  "   for (ulong i=0;i<iterations;i++)",
180
  "   {",
181
  "      float x=(float)MWCfp ;",
182
  "      float y=(float)MWCfp ;",
183
  "      ulong inside=((x*x+y*y) <= THEONE32F) ? 1:0;",
184
  "      total+=inside;",
185
  "   }",
186
  "   return(total);",
187
  "}",
188
  "ulong MainLoop64I(ulong iterations,uint seed_z,uint seed_w,size_t work)",
189
  "{",
190
  "   uint z=seed_z+work;",
191
  "   uint w=seed_w+work;",
192
  "   ulong total=0;",
193
  "   for (ulong i=0;i<iterations;i++)",
194
  "   {",
195
  "      ulong x=(ulong)(MWC>>1);",
196
  "      ulong y=(ulong)(MWC>>1);",
197
  "      ulong inside=((x*x+y*y) <= THEONE64I) ? 1:0;",
198
  "      total+=inside;",
199
  "   }",
200
  "   return(total);",
201
  "}",
202
  "ulong MainLoop64F(ulong iterations,uint seed_z,uint seed_w,size_t work)",
203
  "{",
204
  "   uint z=seed_z+work;",
205
  "   uint w=seed_w+work;",
206
  "   ulong total=0;",
207
  "   for (ulong i=0;i<iterations;i++)",
208
  "{",
209
  "        double x=(double)MWCfp ;",
210
  "        double y=(double)MWCfp ;",
211
  "      ulong inside=((x*x+y*y) <= THEONE64F) ? 1:0;",
212
  "      total+=inside;",
213
  "}",
214
  "   return(total);",
215
  "}",
216
  "__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z,uint MyType)",
217
  "{",
218
  "   ulong total;",
219
  "   if (MyType==TFP32) {",
220
  "      total=(ulong)MainLoop32F(iterations,seed_z,seed_w,get_global_id(0));",
221
  "   }",
222
  "   else if (MyType==TFP64) {",
223
  "      total=(ulong)MainLoop64F(iterations,seed_z,seed_w,get_global_id(0));",
224
  "   }",  
225
  "   else if (MyType==TINT32) {",
226
  "      total=(ulong)MainLoop32I(iterations,seed_z,seed_w,get_global_id(0));",
227
  "   }",  
228
  "   else if (MyType==TINT64) {",
229
  "      total=(ulong)MainLoop64I(iterations,seed_z,seed_w,get_global_id(0));",
230
  "   }",  
231
  "   barrier(CLK_GLOBAL_MEM_FENCE);",
232
  "   s[get_global_id(0)]=(ulong)total;",
233
  "}",
234
  "__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z,uint MyType)",
235
  "{",
236
  "   ulong total;",
237
  "   if (MyType==TFP32) {",
238
  "      total=(ulong)MainLoop32F(iterations,seed_z,seed_w,get_local_id(0));",
239
  "   }",
240
  "   else if (MyType==TFP64) {",
241
  "      total=(ulong)MainLoop64F(iterations,seed_z,seed_w,get_local_id(0));",
242
  "   }",  
243
  "   else if (MyType==TINT32) {",
244
  "      total=(ulong)MainLoop32I(iterations,seed_z,seed_w,get_local_id(0));",
245
  "   }",  
246
  "   else if (MyType==TINT64) {",
247
  "      total=(ulong)MainLoop64I(iterations,seed_z,seed_w,get_local_id(0));",
248
  "   }",  
249
  "   barrier(CLK_LOCAL_MEM_FENCE);",
250
  "   s[get_local_id(0)]=(ulong)total;",
251
  "}",
252
  "__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z,uint MyType)",
253
  "{",
254
  "   ulong total;",
255
  "   if (MyType==TFP32) {",
256
  "      total=(ulong)MainLoop32F(iterations,seed_z,seed_w,get_global_id(0));",
257
  "   }",
258
  "   else if (MyType==TFP64) {",
259
  "      total=(ulong)MainLoop64F(iterations,seed_z,seed_w,get_global_id(0));",
260
  "   }",  
261
  "   else if (MyType==TINT32) {",
262
  "      total=(ulong)MainLoop32I(iterations,seed_z,seed_w,get_global_id(0));",
263
  "   }",  
264
  "   else if (MyType==TINT64) {",
265
  "      total=(ulong)MainLoop64I(iterations,seed_z,seed_w,get_global_id(0));",
266
  "   }",  
267
  "   barrier(CLK_GLOBAL_MEM_FENCE || CLK_LOCAL_MEM_FENCE);",
268
  "   s[get_global_id(0)]=total;",
269
  "}"
270
};
271

    
272
int main(int argc, char **argv)
273
{
274
  if ((argc==1)||
275
      (strcmp(argv[1],"-h")==0)||
276
      (strcmp(argv[1],"--help")==0))
277
    {
278
      printf("\nPerforms a Pi estimation by Dart Dash:\n\n"
279
             "\t#1 OpenCL Plateform ID (default 0)\n"
280
             "\t#2 OpenCL Device ID (default 0)\n"
281
             "\t#3 Minimal number of iterations (default 1000000)\n"
282
             "\t#4 Parallel Rate (default 1024)\n"
283
             "\t#5 Loops (default 1)\n"
284
             "\t#6 Type of variable: INT32, INT64, FP32, FP64 (default FP32)\n\n");
285
      DetectOpenCLDevices();
286
    }
287
  else
288
    {
289
      
290
      int MyPlatform=atoi(argv[1]);
291
      int MyDevice=atoi(argv[2]);
292

    
293
      struct timeval tv1,tv2;
294
      
295
      uint64_t Iterations=1000000;
296
      if (argc>3) {
297
        Iterations=(uint64_t)atoll(argv[3]);
298
      }
299
      
300
      uint32_t ParallelRate=1024;
301
      if (argc>4) {
302
        ParallelRate=(uint32_t)atoi(argv[4]);
303
      }
304
      
305
      uint32_t Loops=1;
306
      if (argc>5) {
307
        Loops=(uint32_t)atoi(argv[5]);
308
      }
309
      
310
      uint32_t MyType=TFP32;
311
      if (argc>6) {
312
        if (strcmp(argv[6],"INT32")==0) {
313
          MyType=(uint32_t)TINT32;
314
        }
315
        else if (strcmp(argv[6],"INT64")==0) {
316
          MyType=(uint32_t)TINT64;
317
        }
318
        else if (strcmp(argv[6],"FP32")==0) {
319
          MyType=(uint32_t)TFP32;
320
        }
321
        else if (strcmp(argv[6],"FP64")==0) {
322
          MyType=(uint32_t)TFP64;
323
        }
324
      }
325

    
326
      printf("MyType %d\n",MyType);
327
      
328
      cl_int err;
329
      cl_context_properties props[3] = { CL_CONTEXT_PLATFORM, 0, 0 };
330
      
331
      // Detect, scan, get & initialize platform and device
332
      cl_uint platformCount;
333
      cl_platform_id* platforms;
334
      cl_uint deviceCount;
335
      cl_device_id* devices;      
336
      size_t valueSize;
337
      
338
      /* Setup OpenCL environment. */
339
     
340
      // Get all platforms
341
      err = clGetPlatformIDs(0, NULL, &platformCount);
342
      platforms = (cl_platform_id*) malloc(sizeof(cl_platform_id) * platformCount);
343
      err = clGetPlatformIDs(platformCount, platforms, NULL);
344

    
345
      // Get Device defined
346
      err = clGetDeviceIDs(platforms[MyPlatform], CL_DEVICE_TYPE_ALL, 0, NULL, &deviceCount);
347
      devices = (cl_device_id*) malloc(sizeof(cl_device_id) * deviceCount);
348
      err = clGetDeviceIDs(platforms[MyPlatform], CL_DEVICE_TYPE_ALL, deviceCount, devices, NULL);  
349

    
350
      // print device name
351
      err = clGetDeviceInfo(devices[MyDevice], CL_DEVICE_NAME, 0, NULL, &valueSize);
352
      char* deviceName=(char*)malloc(valueSize);
353
      err = clGetDeviceInfo(devices[MyDevice], CL_DEVICE_NAME, valueSize, deviceName, NULL);
354
      err = clGetDeviceInfo(devices[MyDevice], CL_DEVICE_VENDOR, 0, NULL, &valueSize);
355
      char* vendorName=(char*)malloc(valueSize);      
356
      err = clGetDeviceInfo(devices[MyDevice], CL_DEVICE_VENDOR, valueSize, vendorName, NULL);
357
      printf("\nDevice (%d,%d):\n\t- vendor: %s\n\t- device: %s\n\n",MyPlatform,MyDevice, vendorName,deviceName);
358
      free(deviceName);
359
      free(vendorName);
360
      
361
      props[1] = (cl_context_properties)platforms[MyPlatform];
362
      
363
      cl_context GPUContext = clCreateContext(props, 1, &devices[MyDevice], NULL, NULL, &err);
364
      cl_command_queue cqCommandQueue = clCreateCommandQueue(GPUContext,devices[MyDevice], 0, &err);
365

    
366
      cl_mem GPUInside = clCreateBuffer(GPUContext, CL_MEM_WRITE_ONLY,
367
                                              sizeof(uint64_t) * ParallelRate, NULL, NULL);
368
      
369
      // 130 is the number of line for OpenCL code
370
      cl_program OpenCLProgram = clCreateProgramWithSource(GPUContext, 130 ,OpenCLSource,NULL,NULL);
371
      clBuildProgram(OpenCLProgram, 0, NULL, NULL, NULL, NULL);
372
      cl_kernel OpenCLMainLoopGlobal = clCreateKernel(OpenCLProgram, "MainLoopGlobal", NULL);
373
      cl_kernel OpenCLMainLoopLocal = clCreateKernel(OpenCLProgram, "MainLoopLocal", NULL);
374
      cl_kernel OpenCLMainLoopHybrid = clCreateKernel(OpenCLProgram, "MainLoopHybrid", NULL);
375

    
376
      // Divide the total number of iterations by the parallel rate
377
      // Add +1 to the number of per work iterations if division not integer
378
      uint64_t IterationsEach=((Iterations%ParallelRate)==0)?Iterations/ParallelRate:Iterations/ParallelRate+1;
379
      // Initialize seeds for MWC RNG generator from Marsaglia
380
      uint32_t seed_w=110271;
381
      uint32_t seed_z=101008;
382

    
383
      // Set the values of arguments for OpenCL function call
384
      clSetKernelArg(OpenCLMainLoopGlobal, 0, sizeof(cl_mem),&GPUInside);
385
      clSetKernelArg(OpenCLMainLoopGlobal, 1, sizeof(uint64_t),&IterationsEach);
386
      clSetKernelArg(OpenCLMainLoopGlobal, 2, sizeof(uint32_t),&seed_w);
387
      clSetKernelArg(OpenCLMainLoopGlobal, 3, sizeof(uint32_t),&seed_z);
388
      clSetKernelArg(OpenCLMainLoopGlobal, 4, sizeof(uint32_t),&MyType);
389
      
390
      size_t WorkSize[1] = {ParallelRate}; // one dimensional Range
391

    
392
      uint64_t HostInside[ParallelRate];
393

    
394
      for (uint32_t loop=0;loop<Loops;loop++) {
395
        // Set start timer
396
        gettimeofday(&tv1, NULL);
397
        
398
            // Execute the OpenCL kernel with datas
399
        clEnqueueNDRangeKernel(cqCommandQueue, OpenCLMainLoopGlobal, 1, NULL,
400
                               WorkSize, NULL, 0, NULL, NULL);
401
        // Copy each result for each PR from Device to Host
402
        clEnqueueReadBuffer(cqCommandQueue, GPUInside, CL_TRUE, 0,
403
                            ParallelRate * sizeof(uint64_t), HostInside, 0, NULL, NULL);
404
        uint64_t inside=0;
405

    
406
        for (int i= 0; i < ParallelRate; i++) {
407
          inside+=HostInside[i];
408
        }
409
          
410
        // Set stop timer
411
        gettimeofday(&tv2, NULL);
412

    
413
        double elapsed=(double)((tv2.tv_sec-tv1.tv_sec) * 1000000L +
414
                                (tv2.tv_usec-tv1.tv_usec))/1000000;  
415

    
416
        double itops=(double)(ParallelRate*IterationsEach)/elapsed;
417
      
418
        printf("Inside/Total %ld %ld\nParallelRate %i\nElapsed Time %.2f\nItops %.0f\nLogItops %.2f\nPi estimation %f\n\n",inside,ParallelRate*IterationsEach,ParallelRate,elapsed,itops,log10(itops),(4.*(float)inside/((float)(ParallelRate)*(float)(IterationsEach))));
419
      }
420
      printf("\n\n");
421
      
422
      clReleaseKernel(OpenCLMainLoopGlobal);
423
      clReleaseProgram(OpenCLProgram);
424
      clReleaseCommandQueue(cqCommandQueue);
425
      clReleaseContext(GPUContext);
426
      clReleaseMemObject(GPUInside);
427

    
428
      
429
      return 0;
430
    }
431
}
432