Statistiques
| Révision :

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

Historique | Voir | Annoter | Télécharger (26,23 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
#define TCONG 0
72
#define TSHR3 1
73
#define TMWC 2
74
#define TKISS 3
75

76
#define TINT32 0
77
#define TINT64 1
78
#define TFP32 2
79
#define TFP64 3
80

81
// Marsaglia RNG very simple implementation
82

83
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
84
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
85
#define MWC   (znew+wnew)
86
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
87
#define CONG  (jcong=69069*jcong+1234567)
88
#define KISS  ((MWC^CONG)+SHR3)
89

90
#define MWCfp MWC * 2.328306435454494e-10f
91
#define KISSfp KISS * 2.328306435454494e-10f
92
#define SHR3fp SHR3 * 2.328306435454494e-10f
93
#define CONGfp CONG * 2.328306435454494e-10f
94

95
__global__ void MainLoopBlocks(ulong *s,ulong iterations,uint seed_w,uint seed_z)
96
{
97
   uint z=seed_z/(blockIdx.x+1);
98
   uint w=seed_w/(blockIdx.x+1);
99

100
   ulong total=0;
101

102
   for (ulong i=0;i<iterations;i++) {
103

104
      float x=MWCfp ;
105
      float y=MWCfp ;
106

107
      // Matching test
108
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
109
      total+=inside;
110

111
   }
112

113
   s[blockIdx.x]=total;
114
   __syncthreads();
115

116
}
117

118
__global__ void MainLoopThreads(ulong *s,ulong iterations,uint seed_w,uint seed_z)
119
{
120
   uint z=seed_z+threadIdx.x;
121
   uint w=seed_w+threadIdx.x;
122

123
   ulong total=0;
124

125
   for (ulong i=0;i<iterations;i++) {
126

127
      float x=MWCfp ;
128
      float y=MWCfp ;
129

130
      // Matching test
131
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
132
      total+=inside;
133

134
   }
135

136
   s[threadIdx.x]=total;
137
   __syncthreads();
138

139
}
140

141
__global__ void MainLoopHybrid(ulong *s,ulong iterations,uint seed_w,uint seed_z)
142
{
143
   uint z=seed_z+(blockDim.x*blockIdx.x+threadIdx.x+1);
144
   uint w=seed_w+(blockDim.x*blockIdx.x+threadIdx.x+1);
145

146
   ulong total=0;
147

148
   for (ulong i=0;i<iterations;i++) {
149

150
      float x=MWCfp ;
151
      float y=MWCfp ;
152

153
      // Matching test
154
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
155
      total+=inside;
156

157
   }
158

159
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
160
   __syncthreads();
161

162
}
163

164
__global__ void MainLoopBlocks64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
165
{
166
   uint z=seed_z+blockIdx.x;
167
   uint w=seed_w+blockIdx.x;
168

169
   ulong total=0;
170

171
   for (ulong i=0;i<iterations;i++) {
172

173
      double x=(double)MWCfp ;
174
      double y=(double)MWCfp ;
175

176
      // Matching test
177
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
178
      total+=inside;
179

180
   }
181

182
   s[blockIdx.x]=total;
183
   __syncthreads();
184

185
}
186

187
__global__ void MainLoopThreads64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
188
{
189
   uint z=seed_z+threadIdx.x;
190
   uint w=seed_w+threadIdx.x;
191

192
   ulong total=0;
193

194
   for (ulong i=0;i<iterations;i++) {
195

196
      double x=(double)MWCfp ;
197
      double y=(double)MWCfp ;
198

199
      // Matching test
200
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
201
      total+=inside;
202

203
   }
204

205
   s[threadIdx.x]=total;
206
   __syncthreads();
207

208
}
209

210
__global__ void MainLoopHybrid64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
211
{
212
   uint z=seed_z+blockDim.x*blockIdx.x+threadIdx.x;
213
   uint w=seed_w+blockDim.x*blockIdx.x+threadIdx.x;
214

215
   ulong total=0;
216

217
   for (ulong i=0;i<iterations;i++) {
218

219
      double x=(double)MWCfp ;
220
      double y=(double)MWCfp ;
221

222
      // Matching test
223
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
224
      total+=inside;
225

226
   }
227

228
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
229
   __syncthreads();
230

231
}
232
"""
233

    
234
KERNEL_CODE_OPENCL="""
235
#define TCONG 0
236
#define TSHR3 1
237
#define TMWC 2
238
#define TKISS 3
239

240
#define TINT32 0
241
#define TINT64 1
242
#define TFP32 2
243
#define TFP64 3
244

245
// Marsaglia RNG very simple implementation
246
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
247
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
248

249
#define MWC   (znew+wnew)
250
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
251
#define CONG  (jcong=69069*jcong+1234567)
252
#define KISS  ((MWC^CONG)+SHR3)
253

254
#define MWCfp MWC * 2.328306435454494e-10f
255
#define KISSfp KISS * 2.328306435454494e-10f
256
#define CONGfp CONG * 2.328306435454494e-10f
257
#define SHR3fp SHR3 * 2.328306435454494e-10f
258

259
ulong MainLoop(ulong iterations,uint seed_z,uint seed_w,size_t work)
260
{
261

262
#if TRNG == TCONG
263
   uint jcong=seed_z+work;
264
#elif TRNG == TSHR3
265
   uint jsr=seed_w+work;
266
#elif TRNG == TMWC
267
   uint z=seed_z+work;
268
   uint w=seed_w+work;
269
#elif TRNG == TKISS
270
   uint jcong=seed_z+work;
271
   uint jsr=seed_w+work;
272
   uint z=seed_z-work;
273
   uint w=seed_w-work;
274
#endif
275

276
   ulong total=0;
277

278
   for (ulong i=0;i<iterations;i++) {
279

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

343
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
344
      total+=inside;
345
   }
346
   
347
   return(total);
348
}
349

350
__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
351
{
352
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
353
   barrier(CLK_GLOBAL_MEM_FENCE);
354
   s[get_global_id(0)]=total;     
355
}
356

357

358
__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
359
{
360
   ulong total=MainLoop(iterations,seed_z,seed_w,get_local_id(0));
361
   barrier(CLK_LOCAL_MEM_FENCE);
362
   s[get_local_id(0)]=total;
363
}
364

365
__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
366
{
367
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
368
   barrier(CLK_GLOBAL_MEM_FENCE || CLK_LOCAL_MEM_FENCE);
369
   s[get_global_id(0)]=total;
370
}
371

372
"""
373

    
374
def MetropolisCuda(circle,iterations,steps,jobs,ParaStyle,DoublePrecision):
375

    
376
  # Avec PyCUDA autoinit, rien a faire !
377
  
378
  circleCU = cuda.InOut(circle)
379
  
380
  mod = SourceModule(KERNEL_CODE_CUDA)
381

    
382
  MetropolisBlocksCU=mod.get_function("MainLoopBlocks")
383
  MetropolisJobsCU=mod.get_function("MainLoopThreads")
384
  MetropolisHybridCU=mod.get_function("MainLoopHybrid")
385
  MetropolisBlocks64CU=mod.get_function("MainLoopBlocks64")
386
  MetropolisJobs64CU=mod.get_function("MainLoopThreads64")
387
  MetropolisHybrid64CU=mod.get_function("MainLoopHybrid64")
388
  
389
  start = pycuda.driver.Event()
390
  stop = pycuda.driver.Event()
391
  
392
  MyPi=numpy.zeros(steps)
393
  MyDuration=numpy.zeros(steps)
394

    
395
  if iterations%jobs==0:
396
    iterationsCL=numpy.uint64(iterations/jobs)
397
    iterationsNew=iterationsCL*jobs
398
  else:
399
    iterationsCL=numpy.uint64(iterations/jobs+1)
400
    iterationsNew=iterations
401

    
402
  for i in range(steps):
403
    start.record()
404
    start.synchronize()
405
    if ParaStyle=='Blocks':
406
      if DoublePrecision:
407
        MetropolisBlocksCU(circleCU,
408
                           numpy.uint64(iterationsCL),
409
                           numpy.uint32(nprnd(2**30/jobs)),
410
                           numpy.uint32(nprnd(2**30/jobs)),
411
                           grid=(jobs,1),
412
                           block=(1,1,1))
413
      else:
414
        MetropolisBlocks64CU(circleCU,
415
                             numpy.uint64(iterationsCL),
416
                             numpy.uint32(nprnd(2**30/jobs)),
417
                             numpy.uint32(nprnd(2**30/jobs)),
418
                             grid=(jobs,1),
419
                             block=(1,1,1))
420
        
421
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
422
            (Alu,jobs,1,ParaStyle)      
423
    elif ParaStyle=='Hybrid':
424
      threads=BestThreadsNumber(jobs)
425
      if DoublePrecision:
426
        MetropolisHybrid64CU(circleCU,
427
                             numpy.uint64(iterationsCL),
428
                             numpy.uint32(nprnd(2**30/jobs)),
429
                             numpy.uint32(nprnd(2**30/jobs)),
430
                             grid=(jobs,1),
431
                             block=(threads,1,1))
432
      else:
433
        MetropolisHybridCU(circleCU,
434
                           numpy.uint64(iterationsCL),
435
                           numpy.uint32(nprnd(2**30/jobs)),
436
                           numpy.uint32(nprnd(2**30/jobs)),
437
                           grid=(jobs,1),
438
                           block=(threads,1,1))
439
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
440
            (Alu,jobs/threads,threads,ParaStyle)
441
    else:
442
      if DoublePrecision:
443
        MetropolisJobs64CU(circleCU,
444
                           numpy.uint64(iterationsCL),
445
                           numpy.uint32(nprnd(2**30/jobs)),
446
                           numpy.uint32(nprnd(2**30/jobs)),
447
                           grid=(1,1),
448
                           block=(jobs,1,1))
449
      else:
450
        MetropolisJobsCU(circleCU,
451
                         numpy.uint64(iterationsCL),
452
                         numpy.uint32(nprnd(2**30/jobs)),
453
                         numpy.uint32(nprnd(2**30/jobs)),
454
                         grid=(1,1),
455
                         block=(jobs,1,1))
456
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
457
            (Alu,jobs,1,ParaStyle)
458
    stop.record()
459
    stop.synchronize()
460
                
461
    elapsed = start.time_till(stop)*1e-3
462

    
463
    MyDuration[i]=elapsed
464
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
465
    MyPi[i]=numpy.median(AllPi)
466
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
467

    
468

    
469
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
470

    
471
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
472

    
473

    
474
def MetropolisOpenCL(circle,iterations,steps,jobs,ParaStyle,Alu,Device,
475
                     RNG,ValueType):
476
        
477
  # Initialisation des variables en les CASTant correctement
478
    
479
  if Device==0:
480
    print "Enter XPU selector based on ALU type: first selected"
481
    HasXPU=False
482
    # Default Device selection based on ALU Type
483
    for platform in cl.get_platforms():
484
      for device in platform.get_devices():
485
        deviceType=cl.device_type.to_string(device.type)
486
        if deviceType=="GPU" and Alu=="GPU" and not HasXPU:
487
          XPU=device
488
          print "GPU selected: ",device.name
489
          HasXPU=True
490
        if deviceType=="CPU" and Alu=="CPU" and not HasXPU:        
491
          XPU=device
492
          print "CPU selected: ",device.name
493
          HasXPU=True
494
  else:
495
    print "Enter XPU selector based on device number & ALU type"
496
    Id=1
497
    HasXPU=False
498
    # Primary Device selection based on Device Id
499
    for platform in cl.get_platforms():
500
      for device in platform.get_devices():
501
        deviceType=cl.device_type.to_string(device.type)
502
        if Id==Device and Alu==deviceType and HasXPU==False:
503
          XPU=device
504
          print "CPU/GPU selected: ",device.name.lstrip()
505
          HasXPU=True
506
        Id=Id+1
507
    if HasXPU==False:
508
      print "No XPU #%i of type %s found in all of %i devices, sorry..." % \
509
          (Device,Alu,Id-1)
510
      return(0,0,0)
511
                                
512
  # Je cree le contexte et la queue pour son execution
513
  ctx = cl.Context([XPU])
514
  queue = cl.CommandQueue(ctx,
515
                          properties=cl.command_queue_properties.PROFILING_ENABLE)
516

    
517
  # Je recupere les flag possibles pour les buffers
518
  mf = cl.mem_flags
519
        
520
  circleCL = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=circle)
521

    
522
  
523
  MetropolisCL = cl.Program(ctx,KERNEL_CODE_OPENCL).build( \
524
    options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%s" % (Marsaglia[RNG],Computing[ValueType]))
525

    
526
  i=0
527

    
528
  MyPi=numpy.zeros(steps)
529
  MyDuration=numpy.zeros(steps)
530
  
531
  if iterations%jobs==0:
532
    iterationsCL=numpy.uint64(iterations/jobs)
533
    iterationsNew=numpy.uint64(iterationsCL*jobs)
534
  else:
535
    iterationsCL=numpy.uint64(iterations/jobs+1)
536
    iterationsNew=numpy.uint64(iterations)
537

    
538
  for i in range(steps):
539
                
540
    if ParaStyle=='Blocks':
541
      # Call OpenCL kernel
542
      # (1,) is Global work size (only 1 work size)
543
      # (1,) is local work size
544
      # circleCL is lattice translated in CL format
545
      # SeedZCL is lattice translated in CL format
546
      # SeedWCL is lattice translated in CL format
547
      # step is number of iterations
548
      CLLaunch=MetropolisCL.MainLoopGlobal(queue,(jobs,),None,
549
                                           circleCL,
550
                                           numpy.uint64(iterationsCL),
551
                                           numpy.uint32(nprnd(2**30/jobs)),
552
                                           numpy.uint32(nprnd(2**30/jobs)))
553
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
554
            (Alu,jobs,1,ParaStyle)
555
    elif ParaStyle=='Hybrid':
556
      threads=BestThreadsNumber(jobs)
557
      # en OpenCL, necessaire de mettre un Global_id identique au local_id
558
      CLLaunch=MetropolisCL.MainLoopHybrid(queue,(jobs,),(threads,),
559
                                          circleCL,
560
                                          numpy.uint64(iterationsCL),
561
                                          numpy.uint32(nprnd(2**30/jobs)),
562
                                          numpy.uint32(nprnd(2**30/jobs)))
563
        
564
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
565
            (Alu,jobs/threads,threads,ParaStyle)
566
    else:
567
      # en OpenCL, necessaire de mettre un Global_id identique au local_id
568
      CLLaunch=MetropolisCL.MainLoopLocal(queue,(jobs,),(jobs,),
569
                                          circleCL,
570
                                          numpy.uint64(iterationsCL),
571
                                          numpy.uint32(nprnd(2**30/jobs)),
572
                                          numpy.uint32(nprnd(2**30/jobs)))
573
      print "%s with %i %s done" % (Alu,jobs,ParaStyle)
574

    
575
    CLLaunch.wait()
576
    cl.enqueue_copy(queue, circle, circleCL).wait()
577

    
578
    elapsed = 1e-9*(CLLaunch.profile.end - CLLaunch.profile.start)
579

    
580
    print circle,numpy.mean(circle),numpy.median(circle),numpy.std(circle)
581
    MyDuration[i]=elapsed
582
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
583
    MyPi[i]=numpy.median(AllPi)
584
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
585

    
586
  circleCL.release()
587

    
588
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
589
        
590
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
591

    
592

    
593
def FitAndPrint(N,D,Curves):
594

    
595
  from scipy.optimize import curve_fit
596
  import matplotlib.pyplot as plt
597

    
598
  try:
599
    coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
600

    
601
    D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
602
    coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
603
    coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
604
    coeffs_Amdahl[0]=D[0]
605
    print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
606
        (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
607
  except:
608
    print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
609

    
610
  try:
611
    coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
612

    
613
    D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
614
    coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
615
    coeffs_AmdahlR[0]=D[0]
616
    print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
617
        (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
618

    
619
  except:
620
    print "Impossible to fit for Reduced Amdahl law : only %i elements" % len(D) 
621

    
622
  try:
623
    coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
624

    
625
    coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
626
    # coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
627
    coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
628
    coeffs_Mylq[0]=D[0]
629
    print "Mylq Normalized : T=%.2f(%.6f+%.6f/N)+%.6f*N" % (coeffs_Mylq[0],
630
                                                            coeffs_Mylq[1],
631
                                                            coeffs_Mylq[3],
632
                                                            coeffs_Mylq[2])
633
    D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
634
                coeffs_Mylq[3])
635
  except:
636
    print "Impossible to fit for Mylq law : only %i elements" % len(D) 
637

    
638
  try:
639
    coeffs_Mylq2, matcov_Mylq2 = curve_fit(Mylq2, N, D)
640

    
641
    coeffs_Mylq2[1]=coeffs_Mylq2[1]*coeffs_Mylq2[0]/D[0]
642
    # coeffs_Mylq2[2]=coeffs_Mylq2[2]*coeffs_Mylq2[0]/D[0]
643
    # coeffs_Mylq2[3]=coeffs_Mylq2[3]*coeffs_Mylq2[0]/D[0]
644
    coeffs_Mylq2[4]=coeffs_Mylq2[4]*coeffs_Mylq2[0]/D[0]
645
    coeffs_Mylq2[0]=D[0]
646
    print "Mylq 2nd order Normalized: T=%.2f(%.6f+%.6f/N)+%.6f*N+%.6f*N^2" % \
647
        (coeffs_Mylq2[0],coeffs_Mylq2[1],
648
         coeffs_Mylq2[4],coeffs_Mylq2[2],coeffs_Mylq2[3])
649

    
650
  except:
651
    print "Impossible to fit for 2nd order Mylq law : only %i elements" % len(D) 
652

    
653
  if Curves:
654
    plt.xlabel("Number of Threads/work Items")
655
    plt.ylabel("Total Elapsed Time")
656

    
657
    Experience,=plt.plot(N,D,'ro') 
658
    try:
659
      pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
660
      pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
661
    except:
662
      print "Fit curves seem not to be available"
663

    
664
    plt.legend()
665
    plt.show()
666

    
667
if __name__=='__main__':
668

    
669
  # Set defaults values
670
  
671
  # Alu can be CPU, GPU or ACCELERATOR
672
  Alu='CPU'
673
  # Id of GPU : 1 is for first find !
674
  Device=0
675
  # GPU style can be Cuda (Nvidia implementation) or OpenCL
676
  GpuStyle='OpenCL'
677
  # Parallel distribution can be on Threads or Blocks
678
  ParaStyle='Blocks'
679
  # Iterations is integer
680
  Iterations=100000000
681
  # JobStart in first number of Jobs to explore
682
  JobStart=1
683
  # JobEnd is last number of Jobs to explore
684
  JobEnd=16
685
  # JobStep is the step of Jobs to explore
686
  JobStep=1
687
  # Redo is the times to redo the test to improve metrology
688
  Redo=1
689
  # OutMetrology is method for duration estimation : False is GPU inside
690
  OutMetrology=False
691
  Metrology='InMetro'
692
  # Curves is True to print the curves
693
  Curves=False
694
  # Fit is True to print the curves
695
  Fit=False
696
  # Marsaglia RNG
697
  RNG='KISS'
698
  # Value type : INT32, INT64, FP32, FP64
699
  ValueType='INT32'
700
  
701
  try:
702
    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="])
703
  except getopt.GetoptError:
704
    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]
705
    sys.exit(2)
706
    
707
  for opt, arg in opts:
708
    if opt == '-h':
709
      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]
710

    
711
      print "\nInformations about devices detected under OpenCL:"
712
      # For PyOpenCL import
713
      try:
714
        import pyopencl as cl
715
        Id=1
716
        for platform in cl.get_platforms():
717
          for device in platform.get_devices():
718
            deviceType=cl.device_type.to_string(device.type)
719
            print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip())
720
            Id=Id+1
721

    
722
        print
723
        sys.exit()
724
      except ImportError:
725
        print "Your platform does not seem to support OpenCL"
726
        
727
    elif opt == '-o':
728
      OutMetrology=True
729
      Metrology='OutMetro'
730
    elif opt == '-c':
731
      Curves=True
732
    elif opt == '-f':
733
      Fit=True
734
    elif opt in ("-a", "--alu"):
735
      Alu = arg
736
    elif opt in ("-d", "--device"):
737
      Device = int(arg)
738
    elif opt in ("-g", "--gpustyle"):
739
      GpuStyle = arg
740
    elif opt in ("-p", "--parastyle"):
741
      ParaStyle = arg
742
    elif opt in ("-m", "--marsaglia"):
743
      RNG = arg
744
    elif opt in ("-v", "--valuetype"):
745
      ValueType = arg
746
    elif opt in ("-i", "--iterations"):
747
      Iterations = numpy.uint64(arg)
748
    elif opt in ("-s", "--jobstart"):
749
      JobStart = int(arg)
750
    elif opt in ("-e", "--jobend"):
751
      JobEnd = int(arg)
752
    elif opt in ("-t", "--jobstep"):
753
      JobStep = int(arg)
754
    elif opt in ("-r", "--redo"):
755
      Redo = int(arg)
756

    
757
  if Alu=='CPU' and GpuStyle=='CUDA':
758
    print "Alu can't be CPU for CUDA, set Alu to GPU"
759
    Alu='GPU'
760

    
761
  if ParaStyle not in ('Blocks','Threads','Hybrid'):
762
    print "%s not exists, ParaStyle set as Threads !" % ParaStyle
763
    ParaStyle='Threads'
764

    
765
  print "Compute unit : %s" % Alu
766
  print "Device Identification : %s" % Device
767
  print "GpuStyle used : %s" % GpuStyle
768
  print "Parallel Style used : %s" % ParaStyle
769
  print "Iterations : %s" % Iterations
770
  print "Number of threads on start : %s" % JobStart
771
  print "Number of threads on end : %s" % JobEnd
772
  print "Number of redo : %s" % Redo
773
  print "Metrology done out of CPU/GPU : %r" % OutMetrology
774
  print "Type of Marsaglia RNG used : %s" % RNG
775
  print "Type of variable : %s" % ValueType
776

    
777
  if GpuStyle=='CUDA':
778
    try:
779
      # For PyCUDA import
780
      import pycuda.driver as cuda
781
      import pycuda.gpuarray as gpuarray
782
      import pycuda.autoinit
783
      from pycuda.compiler import SourceModule
784
    except ImportError:
785
      print "Platform does not seem to support CUDA"
786

    
787
  if GpuStyle=='OpenCL':
788
    try:
789
      # For PyOpenCL import
790
      import pyopencl as cl
791
      Id=1
792
      for platform in cl.get_platforms():
793
        for device in platform.get_devices():
794
          deviceType=cl.device_type.to_string(device.type)
795
          print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip())
796

    
797
          if Id == Device:
798
            # Set the Alu as detected Device Type
799
            Alu=deviceType
800
          Id=Id+1
801
    except ImportError:
802
      print "Platform does not seem to support CUDA"
803
      
804
  average=numpy.array([]).astype(numpy.float32)
805
  median=numpy.array([]).astype(numpy.float32)
806
  stddev=numpy.array([]).astype(numpy.float32)
807

    
808
  ExploredJobs=numpy.array([]).astype(numpy.uint32)
809

    
810
  Jobs=JobStart
811

    
812
  while Jobs <= JobEnd:
813
    avg,med,std=0,0,0
814
    ExploredJobs=numpy.append(ExploredJobs,Jobs)
815
    circle=numpy.zeros(Jobs).astype(numpy.uint64)
816

    
817
    if OutMetrology:
818
      duration=numpy.array([]).astype(numpy.float32)
819
      for i in range(Redo):
820
        start=time.time()
821
        if GpuStyle=='CUDA':
822
          try:
823
            a,m,s=MetropolisCuda(circle,Iterations,1,Jobs,ParaStyle)
824
          except:
825
            print "Problem with %i // computations on Cuda" % Jobs
826
        elif GpuStyle=='OpenCL':
827
          try:
828
            a,m,s=MetropolisOpenCL(circle,Iterations,1,Jobs,ParaStyle,
829
                                   Alu,Device,RNG,ValueType)
830
          except:
831
            print "Problem with %i // computations on OpenCL" % Jobs            
832
        duration=numpy.append(duration,time.time()-start)
833
      if (a,m,s) != (0,0,0):
834
        avg=numpy.mean(duration)
835
        med=numpy.median(duration)
836
        std=numpy.std(duration)
837
      else:
838
        print "Values seem to be wrong..."
839
    else:
840
      if GpuStyle=='CUDA':
841
        try:
842
          avg,med,std=MetropolisCuda(circle,Iterations,Redo,Jobs,ParaStyle)
843
        except:
844
          print "Problem with %i // computations on Cuda" % Jobs
845
      elif GpuStyle=='OpenCL':
846
        try:
847
          avg,med,std=MetropolisOpenCL(circle,Iterations,Redo,Jobs,ParaStyle,
848
                                       Alu,Device,RNG,ValueType)
849
        except:
850
          print "Problem with %i // computations on OpenCL" % Jobs            
851

    
852
    if (avg,med,std) != (0,0,0):
853
      print "jobs,avg,med,std",Jobs,avg,med,std
854
      average=numpy.append(average,avg)
855
      median=numpy.append(median,med)
856
      stddev=numpy.append(stddev,std)
857
    else:
858
      print "Values seem to be wrong..."
859
    #THREADS*=2
860
    if len(average)!=0:
861
      numpy.savez("Pi%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (ValueType,Alu,GpuStyle,ParaStyle,JobStart,JobEnd,Iterations,Device,Metrology,gethostname()),(ExploredJobs,average,median,stddev))
862
      ToSave=[ ExploredJobs,average,median,stddev ]
863
      numpy.savetxt("Pi%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (ValueType,Alu,GpuStyle,ParaStyle,JobStart,JobEnd,Iterations,Device,Metrology,gethostname()),numpy.transpose(ToSave))
864
    Jobs+=JobStep
865

    
866
  if Fit:
867
    FitAndPrint(ExploredJobs,median,Curves)
868