Statistiques
| Révision :

root / Pi / GPU / Pi-GPU.py @ 72

Historique | Voir | Annoter | Télécharger (29,28 ko)

1
#!/usr/bin/env python
2

    
3
#
4
# Pi-by-MonteCarlo using PyCUDA/PyOpenCL
5
#
6
# CC BY-NC-SA 2011 : <emmanuel.quemener@ens-lyon.fr> 
7
#
8
# Thanks to Andreas Klockner for PyCUDA:
9
# http://mathema.tician.de/software/pycuda
10
# 
11

    
12
# 2013-01-01 : problems with launch timeout
13
# http://stackoverflow.com/questions/497685/how-do-you-get-around-the-maximum-cuda-run-time
14
# Option "Interactive" "0" in /etc/X11/xorg.conf
15

    
16
# Common tools
17
import numpy
18
from numpy.random import randint as nprnd
19
import sys
20
import getopt
21
import time
22
import math
23
from socket import gethostname
24

    
25
Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
26
Computing={'INT32':0,'INT64':1,'FP32':2,'FP64':3}
27

    
28
# find prime factors of a number
29
# Get for WWW :
30
# http://pythonism.wordpress.com/2008/05/17/looking-at-factorisation-in-python/
31
def PrimeFactors(x):
32
  factorlist=numpy.array([]).astype('uint32')
33
  loop=2
34
  while loop<=x:
35
    if x%loop==0:
36
      x/=loop
37
      factorlist=numpy.append(factorlist,[loop])
38
    else:
39
      loop+=1
40
  return factorlist
41

    
42
# Try to find the best thread number in Hybrid approach (Blocks&Threads)
43
# output is thread number
44
def BestThreadsNumber(jobs):
45
  factors=PrimeFactors(jobs)
46
  matrix=numpy.append([factors],[factors[::-1]],axis=0)
47
  threads=1
48
  for factor in matrix.transpose().ravel():
49
    threads=threads*factor
50
    if threads*threads>jobs or threads>512:
51
      break
52
  return(long(threads))
53

    
54
# Predicted Amdahl Law (Reduced with s=1-p)  
55
def AmdahlR(N, T1, p):
56
  return (T1*(1-p+p/N))
57

    
58
# Predicted Amdahl Law
59
def Amdahl(N, T1, s, p):
60
  return (T1*(s+p/N))
61

    
62
# Predicted Mylq Law with first order
63
def Mylq(N, T1,s,c,p):
64
  return (T1*(s+p/N)+c*N)
65

    
66
# Predicted Mylq Law with second order
67
def Mylq2(N, T1,s,c1,c2,p):
68
  return (T1*(s+p/N)+c1*N+c2*N*N)
69

    
70
KERNEL_CODE_CUDA="""
71

72
// Marsaglia RNG very simple implementation
73

74
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
75
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
76
#define MWC   (znew+wnew)
77
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
78
#define CONG  (jcong=69069*jcong+1234567)
79
#define KISS  ((MWC^CONG)+SHR3)
80

81
#define MWCfp MWC * 2.328306435454494e-10f
82
#define KISSfp KISS * 2.328306435454494e-10f
83
#define SHR3fp SHR3 * 2.328306435454494e-10f
84
#define CONGfp CONG * 2.328306435454494e-10f
85

86
__global__ void MainLoopBlocks(ulong *s,ulong iterations,uint seed_w,uint seed_z)
87
{
88
   uint z=seed_z/(blockIdx.x+1);
89
   uint w=seed_w/(blockIdx.x+1);
90

91
   ulong total=0;
92

93
   for (ulong i=0;i<iterations;i++) {
94

95
      float x=MWCfp ;
96
      float y=MWCfp ;
97

98
      // Matching test
99
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
100
      total+=inside;
101

102
   }
103

104
   s[blockIdx.x]=total;
105
   __syncthreads();
106

107
}
108

109
__global__ void MainLoopThreads(ulong *s,ulong iterations,uint seed_w,uint seed_z)
110
{
111
   uint z=seed_z+threadIdx.x;
112
   uint w=seed_w+threadIdx.x;
113

114
   ulong total=0;
115

116
   for (ulong i=0;i<iterations;i++) {
117

118
      float x=MWCfp ;
119
      float y=MWCfp ;
120

121
      // Matching test
122
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
123
      total+=inside;
124

125
   }
126

127
   s[threadIdx.x]=total;
128
   __syncthreads();
129

130
}
131

132
__global__ void MainLoopHybrid(ulong *s,ulong iterations,uint seed_w,uint seed_z)
133
{
134
   uint z=seed_z+(blockDim.x*blockIdx.x+threadIdx.x+1);
135
   uint w=seed_w+(blockDim.x*blockIdx.x+threadIdx.x+1);
136

137
   ulong total=0;
138

139
   for (ulong i=0;i<iterations;i++) {
140

141
      float x=MWCfp ;
142
      float y=MWCfp ;
143

144
      // Matching test
145
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
146
      total+=inside;
147

148
   }
149

150
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
151
   __syncthreads();
152

153
}
154

155
__global__ void MainLoopBlocks64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
156
{
157
   uint z=seed_z+blockIdx.x;
158
   uint w=seed_w+blockIdx.x;
159

160
   ulong total=0;
161

162
   for (ulong i=0;i<iterations;i++) {
163

164
      double x=(double)MWCfp ;
165
      double y=(double)MWCfp ;
166

167
      // Matching test
168
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
169
      total+=inside;
170

171
   }
172

173
   s[blockIdx.x]=total;
174
   __syncthreads();
175

176
}
177

178
__global__ void MainLoopThreads64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
179
{
180
   uint z=seed_z+threadIdx.x;
181
   uint w=seed_w+threadIdx.x;
182

183
   ulong total=0;
184

185
   for (ulong i=0;i<iterations;i++) {
186

187
      double x=(double)MWCfp ;
188
      double y=(double)MWCfp ;
189

190
      // Matching test
191
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
192
      total+=inside;
193

194
   }
195

196
   s[threadIdx.x]=total;
197
   __syncthreads();
198

199
}
200

201
__global__ void MainLoopHybrid64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
202
{
203
   uint z=seed_z+blockDim.x*blockIdx.x+threadIdx.x;
204
   uint w=seed_w+blockDim.x*blockIdx.x+threadIdx.x;
205

206
   ulong total=0;
207

208
   for (ulong i=0;i<iterations;i++) {
209

210
      double x=(double)MWCfp ;
211
      double y=(double)MWCfp ;
212

213
      // Matching test
214
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
215
      total+=inside;
216

217
   }
218

219
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
220
   __syncthreads();
221

222
}
223
"""
224

    
225
KERNEL_CODE_OPENCL="""
226
#define TCONG 0
227
#define TSHR3 1
228
#define TMWC 2
229
#define TKISS 3
230

231
#define TINT32 0
232
#define TINT64 1
233
#define TFP32 2
234
#define TFP64 3
235

236
#pragma OPENCL EXTENSION cl_khr_fp64: enable
237

238
// Marsaglia RNG very simple implementation
239
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
240
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
241

242
#define MWC   (znew+wnew)
243
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
244
#define CONG  (jcong=69069*jcong+1234567)
245
#define KISS  ((MWC^CONG)+SHR3)
246

247
#define MWCfp MWC * 2.328306435454494e-10f
248
#define KISSfp KISS * 2.328306435454494e-10f
249
#define CONGfp CONG * 2.328306435454494e-10f
250
#define SHR3fp SHR3 * 2.328306435454494e-10f
251

252
__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
253
{
254

255
// Initialization of RNG numbers
256
#if TRNG == TCONG
257
   uint jcong=seed_z+get_global_id(0);
258
#elif TRNG == TSHR3
259
   uint jsr=seed_w+get_global_id(0);
260
#elif TRNG == TMWC
261
   uint z=seed_z+get_global_id(0);
262
   uint w=seed_w+get_global_id(0);
263
#elif TRNG == TKISS
264
   uint jcong=seed_z+get_global_id(0);
265
   uint jsr=seed_w+get_global_id(0);
266
   uint z=seed_z-get_global_id(0);
267
   uint w=seed_w-get_global_id(0);
268
#endif
269

270
   ulong total=0;
271

272
   // Main Loop
273
   for (ulong i=0;i<iterations;i++) {
274

275
//
276

277
#if TYPE == TINT32
278
#define THEONE 1073741824
279
#if TRNG == TCONG
280
      uint x=CONG>>17 ;
281
      uint y=CONG>>17 ;
282
#elif TRNG == TSHR3
283
      uint x=SHR3>>17 ;
284
      uint y=SHR3>>17 ;
285
#elif TRNG == TMWC
286
      uint x=MWC>>17 ;
287
      uint y=MWC>>17 ;
288
#elif TRNG == TKISS
289
      uint x=KISS>>17 ;
290
      uint y=KISS>>17 ;
291
#endif
292
#elif TYPE == TINT64
293
#define THEONE 4611686018427387904
294
#if TRNG == TCONG
295
      ulong x=(ulong)(CONG>>1) ;
296
      ulong y=(ulong)(CONG>>1) ;
297
#elif TRNG == TSHR3
298
      ulong x=(ulong)(SHR3>>1) ;
299
      ulong y=(ulong)(SHR3>>1) ;
300
#elif TRNG == TMWC
301
      ulong x=(ulong)(MWC>>1) ;
302
      ulong y=(ulong)(MWC>>1) ;
303
#elif TRNG == TKISS
304
      ulong x=(ulong)(KISS>>1) ;
305
      ulong y=(ulong)(KISS>>1) ;
306
#endif
307
#elif TYPE == TFP32
308
#define THEONE 1.0f
309
#if TRNG == TCONG
310
      float x=CONGfp ;
311
      float y=CONGfp ;
312
#elif TRNG == TSHR3
313
      float x=SHR3fp ;
314
      float y=SHR3fp ;
315
#elif TRNG == TMWC
316
      float x=MWCfp ;
317
      float y=MWCfp ;
318
#elif TRNG == TKISS
319
      float x=KISSfp ;
320
      float y=KISSfp ;
321
#endif
322
#elif TYPE == TFP64
323
#define THEONE 1.0f
324
#if TRNG == TCONG
325
      double x=(double)CONGfp ;
326
      double y=(double)CONGfp ;
327
#elif TRNG == TSHR3
328
      double x=(double)SHR3fp ;
329
      double y=(double)SHR3fp ;
330
#elif TRNG == TMWC
331
      double x=(double)MWCfp ;
332
      double y=(double)MWCfp ;
333
#elif TRNG == TKISS
334
      double x=(double)KISSfp ;
335
      double y=(double)KISSfp ;
336
#endif
337
#endif
338

339
      // Matching test
340
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
341
      total+=inside;
342
   }
343

344
   barrier(CLK_GLOBAL_MEM_FENCE);
345
   s[get_global_id(0)]=total;
346
      
347
}
348

349
__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
350
{
351
   uint z=seed_z+get_local_id(0);
352
   uint w=seed_w+get_local_id(0);
353

354
   ulong total=0;
355

356
   for (ulong i=0;i<iterations;i++) {
357

358
      float x=MWCfp ;
359
      float y=MWCfp ;
360

361
      // Matching test
362
      ulong inside=((x*x+y*y) <= 1.0f) ? 1:0;
363
      total+=inside;
364
   }
365
   barrier(CLK_LOCAL_MEM_FENCE);
366
   s[get_local_id(0)]=total;
367
      
368
}
369

370
__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
371
{
372
   uint z=seed_z+get_global_id(0);
373
   uint w=seed_w+get_global_id(0);
374

375
   ulong total=0;
376

377
   for (uint i=0;i<iterations;i++) {
378

379
      float x=MWCfp ;
380
      float y=MWCfp ;
381

382
      // Matching test
383
      ulong inside=((x*x+y*y) <= 1.0f) ? 1:0;
384
      total+=inside;
385
   }
386
   barrier(CLK_GLOBAL_MEM_FENCE || CLK_GLOBAL_MEM_FENCE);
387
   // s[get_group_id(0)*get_num_groups(0)+get_local_id(0)]=total;
388
   s[get_global_id(0)]=total;
389
      
390
}
391

392
__kernel void MainLoopGlobal64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
393
{
394
   uint z=seed_z+get_global_id(0);
395
   uint w=seed_w+get_global_id(0);
396

397
   ulong total=0;
398

399
   for (ulong i=0;i<iterations;i++) {
400

401
      double x=(double)MWCfp ;
402
      double y=(double)MWCfp ;
403

404
      // Matching test
405
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
406
      total+=inside;
407
   }
408
   barrier(CLK_GLOBAL_MEM_FENCE);
409
   s[get_global_id(0)]=total;
410
      
411
}
412

413
__kernel void MainLoopLocal64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
414
{
415
   uint z=seed_z+get_local_id(0);
416
   uint w=seed_w+get_local_id(0);
417

418
   ulong total=0;
419

420
   for (ulong i=0;i<iterations;i++) {
421

422
      double x=(double)MWCfp ;
423
      double y=(double)MWCfp ;
424

425
      // Matching test
426
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
427
      total+=inside;
428
   }
429
   barrier(CLK_LOCAL_MEM_FENCE);
430
   s[get_local_id(0)]=total;
431
      
432
}
433

434
__kernel void MainLoopHybrid64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
435
{
436
   uint z=seed_z+get_global_id(0);
437
   uint w=seed_w+get_global_id(0);
438

439
   ulong total=0;
440

441
   for (uint i=0;i<iterations;i++) {
442

443
      double x=(double)MWCfp ;
444
      double y=(double)MWCfp ;
445

446
      // Matching test
447
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
448
      total+=inside;
449
   }
450
   barrier(CLK_LOCAL_MEM_FENCE);
451
   s[get_global_id(0)]=total;
452
      
453
}
454
"""
455

    
456
def MetropolisCuda(circle,iterations,steps,jobs,ParaStyle,DoublePrecision):
457

    
458
  # Avec PyCUDA autoinit, rien a faire !
459
  
460
  circleCU = cuda.InOut(circle)
461
  
462
  mod = SourceModule(KERNEL_CODE_CUDA)
463

    
464
  MetropolisBlocksCU=mod.get_function("MainLoopBlocks")
465
  MetropolisJobsCU=mod.get_function("MainLoopThreads")
466
  MetropolisHybridCU=mod.get_function("MainLoopHybrid")
467
  MetropolisBlocks64CU=mod.get_function("MainLoopBlocks64")
468
  MetropolisJobs64CU=mod.get_function("MainLoopThreads64")
469
  MetropolisHybrid64CU=mod.get_function("MainLoopHybrid64")
470
  
471
  start = pycuda.driver.Event()
472
  stop = pycuda.driver.Event()
473
  
474
  MyPi=numpy.zeros(steps)
475
  MyDuration=numpy.zeros(steps)
476

    
477
  if iterations%jobs==0:
478
    iterationsCL=numpy.uint64(iterations/jobs)
479
    iterationsNew=iterationsCL*jobs
480
  else:
481
    iterationsCL=numpy.uint64(iterations/jobs+1)
482
    iterationsNew=iterations
483

    
484
  for i in range(steps):
485
    start.record()
486
    start.synchronize()
487
    if ParaStyle=='Blocks':
488
      if DoublePrecision:
489
        MetropolisBlocksCU(circleCU,
490
                           numpy.uint64(iterationsCL),
491
                           numpy.uint32(nprnd(2**30/jobs)),
492
                           numpy.uint32(nprnd(2**30/jobs)),
493
                           grid=(jobs,1),
494
                           block=(1,1,1))
495
      else:
496
        MetropolisBlocks64CU(circleCU,
497
                             numpy.uint64(iterationsCL),
498
                             numpy.uint32(nprnd(2**30/jobs)),
499
                             numpy.uint32(nprnd(2**30/jobs)),
500
                             grid=(jobs,1),
501
                             block=(1,1,1))
502
        
503
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
504
            (Alu,jobs,1,ParaStyle)      
505
    elif ParaStyle=='Hybrid':
506
      threads=BestThreadsNumber(jobs)
507
      if DoublePrecision:
508
        MetropolisHybrid64CU(circleCU,
509
                             numpy.uint64(iterationsCL),
510
                             numpy.uint32(nprnd(2**30/jobs)),
511
                             numpy.uint32(nprnd(2**30/jobs)),
512
                             grid=(jobs,1),
513
                             block=(threads,1,1))
514
      else:
515
        MetropolisHybridCU(circleCU,
516
                           numpy.uint64(iterationsCL),
517
                           numpy.uint32(nprnd(2**30/jobs)),
518
                           numpy.uint32(nprnd(2**30/jobs)),
519
                           grid=(jobs,1),
520
                           block=(threads,1,1))
521
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
522
            (Alu,jobs/threads,threads,ParaStyle)
523
    else:
524
      if DoublePrecision:
525
        MetropolisJobs64CU(circleCU,
526
                           numpy.uint64(iterationsCL),
527
                           numpy.uint32(nprnd(2**30/jobs)),
528
                           numpy.uint32(nprnd(2**30/jobs)),
529
                           grid=(1,1),
530
                           block=(jobs,1,1))
531
      else:
532
        MetropolisJobsCU(circleCU,
533
                         numpy.uint64(iterationsCL),
534
                         numpy.uint32(nprnd(2**30/jobs)),
535
                         numpy.uint32(nprnd(2**30/jobs)),
536
                         grid=(1,1),
537
                         block=(jobs,1,1))
538
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
539
            (Alu,jobs,1,ParaStyle)
540
    stop.record()
541
    stop.synchronize()
542
                
543
    elapsed = start.time_till(stop)*1e-3
544

    
545
    MyDuration[i]=elapsed
546
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
547
    MyPi[i]=numpy.median(AllPi)
548
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
549

    
550

    
551
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
552

    
553
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
554

    
555

    
556
def MetropolisOpenCL(circle,iterations,steps,jobs,ParaStyle,Alu,Device,
557
                     DoublePrecision,RNG,ValueType):
558
        
559
  # Initialisation des variables en les CASTant correctement
560
    
561
  if Device==0:
562
    print "Enter XPU selector based on ALU type: first selected"
563
    HasXPU=False
564
    # Default Device selection based on ALU Type
565
    for platform in cl.get_platforms():
566
      for device in platform.get_devices():
567
        deviceType=cl.device_type.to_string(device.type)
568
        if deviceType=="GPU" and Alu=="GPU" and not HasXPU:
569
          XPU=device
570
          print "GPU selected: ",device.name
571
          HasXPU=True
572
        if deviceType=="CPU" and Alu=="CPU" and not HasXPU:        
573
          XPU=device
574
          print "CPU selected: ",device.name
575
          HasXPU=True
576
  else:
577
    print "Enter XPU selector based on device number & ALU type"
578
    Id=1
579
    HasXPU=False
580
    # Primary Device selection based on Device Id
581
    for platform in cl.get_platforms():
582
      for device in platform.get_devices():
583
        deviceType=cl.device_type.to_string(device.type)
584
        if Id==Device and Alu==deviceType and HasXPU==False:
585
          XPU=device
586
          print "CPU/GPU selected: ",device.name
587
          HasXPU=True
588
        Id=Id+1
589
    if HasXPU==False:
590
      print "No XPU #%i of type %s found in all of %i devices, sorry..." % \
591
          (Device,Alu,Id-1)
592
      return(0,0,0)
593
                                
594
  # Je cree le contexte et la queue pour son execution
595
  ctx = cl.Context([XPU])
596
  queue = cl.CommandQueue(ctx,
597
                          properties=cl.command_queue_properties.PROFILING_ENABLE)
598

    
599
  # Je recupere les flag possibles pour les buffers
600
  mf = cl.mem_flags
601
        
602
  circleCL = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=circle)
603

    
604
  
605
  MetropolisCL = cl.Program(ctx,KERNEL_CODE_OPENCL).build( \
606
    options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%s" % (Marsaglia[RNG],Computing[ValueType]))
607

    
608
  i=0
609

    
610
  MyPi=numpy.zeros(steps)
611
  MyDuration=numpy.zeros(steps)
612
  
613
  if iterations%jobs==0:
614
    iterationsCL=numpy.uint64(iterations/jobs)
615
    iterationsNew=numpy.uint64(iterationsCL*jobs)
616
  else:
617
    iterationsCL=numpy.uint64(iterations/jobs+1)
618
    iterationsNew=numpy.uint64(iterations)
619

    
620
  for i in range(steps):
621
                
622
    if ParaStyle=='Blocks':
623
      # Call OpenCL kernel
624
      # (1,) is Global work size (only 1 work size)
625
      # (1,) is local work size
626
      # circleCL is lattice translated in CL format
627
      # SeedZCL is lattice translated in CL format
628
      # SeedWCL is lattice translated in CL format
629
      # step is number of iterations
630
      if DoublePrecision:
631
        CLLaunch=MetropolisCL.MainLoopGlobal64(queue,(jobs,),None,
632
                                               circleCL,
633
                                               numpy.uint64(iterationsCL),
634
                                               numpy.uint32(nprnd(2**30/jobs)),
635
                                               numpy.uint32(nprnd(2**30/jobs)))
636
      else:
637
        CLLaunch=MetropolisCL.MainLoopGlobal(queue,(jobs,),None,
638
                                             circleCL,
639
                                             numpy.uint64(iterationsCL),
640
                                             numpy.uint32(nprnd(2**30/jobs)),
641
                                             numpy.uint32(nprnd(2**30/jobs)))
642
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
643
            (Alu,jobs,1,ParaStyle)
644
    elif ParaStyle=='Hybrid':
645
      threads=BestThreadsNumber(jobs)
646
      # en OpenCL, necessaire de mettre un Global_id identique au local_id
647
      if DoublePrecision:
648
        CLLaunch=MetropolisCL.MainLoopHybrid64(queue,(jobs,),(threads,),
649
                                               circleCL,
650
                                               numpy.uint64(iterationsCL),
651
                                               numpy.uint32(nprnd(2**30/jobs)),
652
                                               numpy.uint32(nprnd(2**30/jobs)))
653
      else:
654
        CLLaunch=MetropolisCL.MainLoopHybrid(queue,(jobs,),(threads,),
655
                                             circleCL,
656
                                             numpy.uint64(iterationsCL),
657
                                             numpy.uint32(nprnd(2**30/jobs)),
658
                                             numpy.uint32(nprnd(2**30/jobs)))
659
        
660
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
661
            (Alu,jobs/threads,threads,ParaStyle)
662
    else:
663
      # en OpenCL, necessaire de mettre un Global_id identique au local_id
664
      if DoublePrecision:
665
        CLLaunch=MetropolisCL.MainLoopLocal64(queue,(jobs,),(jobs,),
666
                                              circleCL,
667
                                              numpy.uint64(iterationsCL),
668
                                              numpy.uint32(nprnd(2**30/jobs)),
669
                                              numpy.uint32(nprnd(2**30/jobs)))
670
      else:
671
        CLLaunch=MetropolisCL.MainLoopLocal(queue,(jobs,),(jobs,),
672
                                            circleCL,
673
                                            numpy.uint64(iterationsCL),
674
                                            numpy.uint32(nprnd(2**30/jobs)),
675
                                            numpy.uint32(nprnd(2**30/jobs)))
676
      print "%s with %i %s done" % (Alu,jobs,ParaStyle)
677

    
678
    CLLaunch.wait()
679
    cl.enqueue_copy(queue, circle, circleCL).wait()
680

    
681
    elapsed = 1e-9*(CLLaunch.profile.end - CLLaunch.profile.start)
682

    
683
    print circle,numpy.mean(circle),numpy.median(circle),numpy.std(circle)
684
    MyDuration[i]=elapsed
685
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
686
    MyPi[i]=numpy.median(AllPi)
687
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
688

    
689
  circleCL.release()
690

    
691
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
692
        
693
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
694

    
695

    
696
def FitAndPrint(N,D,Curves):
697

    
698
  from scipy.optimize import curve_fit
699
  import matplotlib.pyplot as plt
700

    
701
  try:
702
    coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
703

    
704
    D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
705
    coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
706
    coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
707
    coeffs_Amdahl[0]=D[0]
708
    print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
709
        (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
710
  except:
711
    print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
712

    
713
  try:
714
    coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
715

    
716
    D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
717
    coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
718
    coeffs_AmdahlR[0]=D[0]
719
    print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
720
        (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
721

    
722
  except:
723
    print "Impossible to fit for Reduced Amdahl law : only %i elements" % len(D) 
724

    
725
  try:
726
    coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
727

    
728
    coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
729
    # coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
730
    coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
731
    coeffs_Mylq[0]=D[0]
732
    print "Mylq Normalized : T=%.2f(%.6f+%.6f/N)+%.6f*N" % (coeffs_Mylq[0],
733
                                                            coeffs_Mylq[1],
734
                                                            coeffs_Mylq[3],
735
                                                            coeffs_Mylq[2])
736
    D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
737
                coeffs_Mylq[3])
738
  except:
739
    print "Impossible to fit for Mylq law : only %i elements" % len(D) 
740

    
741
  try:
742
    coeffs_Mylq2, matcov_Mylq2 = curve_fit(Mylq2, N, D)
743

    
744
    coeffs_Mylq2[1]=coeffs_Mylq2[1]*coeffs_Mylq2[0]/D[0]
745
    # coeffs_Mylq2[2]=coeffs_Mylq2[2]*coeffs_Mylq2[0]/D[0]
746
    # coeffs_Mylq2[3]=coeffs_Mylq2[3]*coeffs_Mylq2[0]/D[0]
747
    coeffs_Mylq2[4]=coeffs_Mylq2[4]*coeffs_Mylq2[0]/D[0]
748
    coeffs_Mylq2[0]=D[0]
749
    print "Mylq 2nd order Normalized: T=%.2f(%.6f+%.6f/N)+%.6f*N+%.6f*N^2" % \
750
        (coeffs_Mylq2[0],coeffs_Mylq2[1],
751
         coeffs_Mylq2[4],coeffs_Mylq2[2],coeffs_Mylq2[3])
752

    
753
  except:
754
    print "Impossible to fit for 2nd order Mylq law : only %i elements" % len(D) 
755

    
756
  if Curves:
757
    plt.xlabel("Number of Threads/work Items")
758
    plt.ylabel("Total Elapsed Time")
759

    
760
    Experience,=plt.plot(N,D,'ro') 
761
    try:
762
      pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
763
      pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
764
    except:
765
      print "Fit curves seem not to be available"
766

    
767
    plt.legend()
768
    plt.show()
769

    
770
if __name__=='__main__':
771

    
772
  # Set defaults values
773
  
774
  # Alu can be CPU, GPU or ACCELERATOR
775
  Alu='CPU'
776
  # Id of GPU : 1 is for first find !
777
  Device=0
778
  # GPU style can be Cuda (Nvidia implementation) or OpenCL
779
  GpuStyle='OpenCL'
780
  # Parallel distribution can be on Threads or Blocks
781
  ParaStyle='Blocks'
782
  # Iterations is integer
783
  Iterations=100000000
784
  # JobStart in first number of Jobs to explore
785
  JobStart=1
786
  # JobEnd is last number of Jobs to explore
787
  JobEnd=16
788
  # JobStep is the step of Jobs to explore
789
  JobStep=1
790
  # Redo is the times to redo the test to improve metrology
791
  Redo=1
792
  # OutMetrology is method for duration estimation : False is GPU inside
793
  OutMetrology=False
794
  Metrology='InMetro'
795
  # Curves is True to print the curves
796
  Curves=False
797
  # Fit is True to print the curves
798
  Fit=False
799
  # DoublePrecision on FP calculus
800
  DoublePrecision=False
801
  # Marsaglia RNG
802
  RNG='KISS'
803
  # Value type : INT32, INT64, FP32, FP64
804
  ValueType='INT32'
805
  
806
  try:
807
    opts, args = getopt.getopt(sys.argv[1:],"hocfa:g:p:i:s:e:t:r:d:m:v:",["alu=","gpustyle=","parastyle=","iterations=","jobstart=","jobend=","jobstep=","redo=","device=","marsaglia=","valuetype="])
808
  except getopt.GetoptError:
809
    print '%s -o (Out of Core Metrology) -c (Print Curves) -f (Fit to Amdahl Law) -a <CPU/GPU/ACCELERATOR> -d <DeviceId> -g <CUDA/OpenCL> -p <Threads/Hybrid/Blocks> -i <Iterations> -s <JobStart> -e <JobEnd> -t <JobStep> -r <RedoToImproveStats> -m <SHR3/CONG/MWC/KISS> -v <INT32/INT64/FP32/FP64> ' % sys.argv[0]
810
    sys.exit(2)
811
    
812
  for opt, arg in opts:
813
    if opt == '-h':
814
      print '%s -o (Out of Core Metrology) -c (Print Curves) -f (Fit to Amdahl Law) -a <CPU/GPU/ACCELERATOR> -d <DeviceId> -g <CUDA/OpenCL> -p <Threads/Hybrid/Blocks> -i <Iterations> -s <JobStart> -e <JobEnd> -t <JobStep> -r <RedoToImproveStats> -m <SHR3/CONG/MWC/KISS> -v <INT32/INT64/FP32/FP64>' % sys.argv[0]
815

    
816
      print "\nInformations about devices detected under OpenCL:"
817
      # For PyOpenCL import
818
      try:
819
        import pyopencl as cl
820
        Id=1
821
        for platform in cl.get_platforms():
822
          for device in platform.get_devices():
823
            deviceType=cl.device_type.to_string(device.type)
824
            print "Device #%i from %s of type %s : %s" % (Id,platform.vendor,deviceType,device.name.lstrip())
825
            Id=Id+1
826

    
827
        print
828
        sys.exit()
829
      except ImportError:
830
        print "Your platform does not seem to support OpenCL"
831
        
832
    elif opt == '-o':
833
      OutMetrology=True
834
      Metrology='OutMetro'
835
    elif opt == '-l':
836
      DoublePrecision=True
837
    elif opt == '-c':
838
      Curves=True
839
    elif opt == '-f':
840
      Fit=True
841
    elif opt in ("-a", "--alu"):
842
      Alu = arg
843
    elif opt in ("-d", "--device"):
844
      Device = int(arg)
845
    elif opt in ("-g", "--gpustyle"):
846
      GpuStyle = arg
847
    elif opt in ("-p", "--parastyle"):
848
      ParaStyle = arg
849
    elif opt in ("-m", "--marsaglia"):
850
      RNG = arg
851
    elif opt in ("-v", "--valuetype"):
852
      ValueType = arg
853
    elif opt in ("-i", "--iterations"):
854
      Iterations = numpy.uint64(arg)
855
    elif opt in ("-s", "--jobstart"):
856
      JobStart = int(arg)
857
    elif opt in ("-e", "--jobend"):
858
      JobEnd = int(arg)
859
    elif opt in ("-t", "--jobstep"):
860
      JobStep = int(arg)
861
    elif opt in ("-r", "--redo"):
862
      Redo = int(arg)
863

    
864
  if Alu=='CPU' and GpuStyle=='CUDA':
865
    print "Alu can't be CPU for CUDA, set Alu to GPU"
866
    Alu='GPU'
867

    
868
  if ParaStyle not in ('Blocks','Threads','Hybrid'):
869
    print "%s not exists, ParaStyle set as Threads !" % ParaStyle
870
    ParaStyle='Threads'
871

    
872
  print "Compute unit : %s" % Alu
873
  print "Device Identification : %s" % Device
874
  print "GpuStyle used : %s" % GpuStyle
875
  print "Parallel Style used : %s" % ParaStyle
876
  print "Iterations : %s" % Iterations
877
  print "Number of threads on start : %s" % JobStart
878
  print "Number of threads on end : %s" % JobEnd
879
  print "Number of redo : %s" % Redo
880
  print "Metrology done out of CPU/GPU : %r" % OutMetrology
881
  print "Double Precision in Kernels : %r" % DoublePrecision
882
  print "Type of Marsaglia RNG used : %s" % RNG
883
  print "Type of variable : %s" % ValueType
884

    
885
  if GpuStyle=='CUDA':
886
    try:
887
      # For PyCUDA import
888
      import pycuda.driver as cuda
889
      import pycuda.gpuarray as gpuarray
890
      import pycuda.autoinit
891
      from pycuda.compiler import SourceModule
892
    except ImportError:
893
      print "Platform does not seem to support CUDA"
894

    
895
  if GpuStyle=='OpenCL':
896
    try:
897
      # For PyOpenCL import
898
      import pyopencl as cl
899
      Id=1
900
      for platform in cl.get_platforms():
901
        for device in platform.get_devices():
902
          deviceType=cl.device_type.to_string(device.type)
903
          print "Device #%i of type %s : %s" % (Id,deviceType,device.name)
904
          if Id == Device:
905
            # Set the Alu as detected Device Type
906
            Alu=deviceType
907
          Id=Id+1
908
    except ImportError:
909
      print "Platform does not seem to support CUDA"
910
      
911
  average=numpy.array([]).astype(numpy.float32)
912
  median=numpy.array([]).astype(numpy.float32)
913
  stddev=numpy.array([]).astype(numpy.float32)
914

    
915
  ExploredJobs=numpy.array([]).astype(numpy.uint32)
916

    
917
  Jobs=JobStart
918

    
919
  while Jobs <= JobEnd:
920
    avg,med,std=0,0,0
921
    ExploredJobs=numpy.append(ExploredJobs,Jobs)
922
    circle=numpy.zeros(Jobs).astype(numpy.uint64)
923

    
924
    if OutMetrology:
925
      duration=numpy.array([]).astype(numpy.float32)
926
      for i in range(Redo):
927
        start=time.time()
928
        if GpuStyle=='CUDA':
929
          try:
930
            a,m,s=MetropolisCuda(circle,Iterations,1,Jobs,ParaStyle,
931
                                 DoublePrecision)
932
          except:
933
            print "Problem with %i // computations on Cuda" % Jobs
934
        elif GpuStyle=='OpenCL':
935
          try:
936
            a,m,s=MetropolisOpenCL(circle,Iterations,1,Jobs,ParaStyle,
937
                                   Alu,Device,DoublePrecision,RNG,ValueType)
938
          except:
939
            print "Problem with %i // computations on OpenCL" % Jobs            
940
        duration=numpy.append(duration,time.time()-start)
941
      if (a,m,s) != (0,0,0):
942
        avg=numpy.mean(duration)
943
        med=numpy.median(duration)
944
        std=numpy.std(duration)
945
      else:
946
        print "Values seem to be wrong..."
947
    else:
948
      if GpuStyle=='CUDA':
949
        try:
950
          avg,med,std=MetropolisCuda(circle,Iterations,Redo,Jobs,ParaStyle,
951
                                     DoublePrecision)
952
        except:
953
          print "Problem with %i // computations on Cuda" % Jobs
954
      elif GpuStyle=='OpenCL':
955
        try:
956
          avg,med,std=MetropolisOpenCL(circle,Iterations,Redo,Jobs,ParaStyle,
957
                                       Alu,Device,DoublePrecision,RNG,ValueType)
958
        except:
959
          print "Problem with %i // computations on OpenCL" % Jobs            
960

    
961
    if (avg,med,std) != (0,0,0):
962
      print "jobs,avg,med,std",Jobs,avg,med,std
963
      average=numpy.append(average,avg)
964
      median=numpy.append(median,med)
965
      stddev=numpy.append(stddev,std)
966
    else:
967
      print "Values seem to be wrong..."
968
    #THREADS*=2
969
    if DoublePrecision:
970
      Precision='DP'
971
    else:
972
      Precision='SP'
973
    if len(average)!=0:
974
      numpy.savez("Pi%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (Precision,Alu,GpuStyle,ParaStyle,JobStart,JobEnd,Iterations,Device,Metrology,gethostname()),(ExploredJobs,average,median,stddev))
975
      ToSave=[ ExploredJobs,average,median,stddev ]
976
      numpy.savetxt("Pi%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (Precision,Alu,GpuStyle,ParaStyle,JobStart,JobEnd,Iterations,Device,Metrology,gethostname()),numpy.transpose(ToSave))
977
    Jobs+=JobStep
978

    
979
  if Fit:
980
    FitAndPrint(ExploredJobs,median,Curves)
981