Statistiques
| Révision :

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

Historique | Voir | Annoter | Télécharger (26,69 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
# find prime factors of a number
26
# Get for WWW :
27
# http://pythonism.wordpress.com/2008/05/17/looking-at-factorisation-in-python/
28
def PrimeFactors(x):
29
  factorlist=numpy.array([]).astype('uint32')
30
  loop=2
31
  while loop<=x:
32
    if x%loop==0:
33
      x/=loop
34
      factorlist=numpy.append(factorlist,[loop])
35
    else:
36
      loop+=1
37
  return factorlist
38

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

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

    
55
# Predicted Amdahl Law
56
def Amdahl(N, T1, s, p):
57
  return (T1*(s+p/N))
58

    
59
# Predicted Mylq Law with first order
60
def Mylq(N, T1,s,c,p):
61
  return (T1*(s+p/N)+c*N)
62

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

    
67
KERNEL_CODE_CUDA="""
68

69
// Marsaglia RNG very simple implementation
70

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

78
#define MWCfp MWC * 2.328306435454494e-10f
79
#define KISSfp KISS * 2.328306435454494e-10f
80

81
__global__ void MainLoopBlocks(ulong *s,ulong iterations,uint seed_w,uint seed_z)
82
{
83
   uint z=seed_z/(blockIdx.x+1);
84
   uint w=seed_w/(blockIdx.x+1);
85

86
   ulong total=0;
87

88
   for (ulong i=0;i<iterations;i++) {
89

90
      float x=MWCfp ;
91
      float y=MWCfp ;
92

93
      // Matching test
94
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
95
      total+=inside;
96

97
   }
98

99
   s[blockIdx.x]=total;
100
   __syncthreads();
101

102
}
103

104
__global__ void MainLoopThreads(ulong *s,ulong iterations,uint seed_w,uint seed_z)
105
{
106
   uint z=seed_z/(threadIdx.x+1);
107
   uint w=seed_w/(threadIdx.x+1);
108

109
   ulong total=0;
110

111
   for (ulong i=0;i<iterations;i++) {
112

113
      float x=MWCfp ;
114
      float y=MWCfp ;
115

116
      // Matching test
117
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
118
      total+=inside;
119

120
   }
121

122
   s[threadIdx.x]=total;
123
   __syncthreads();
124

125
}
126

127
__global__ void MainLoopHybrid(ulong *s,ulong iterations,uint seed_w,uint seed_z)
128
{
129
   uint z=seed_z/(blockDim.x*blockIdx.x+threadIdx.x+1);
130
   uint w=seed_w/(blockDim.x*blockIdx.x+threadIdx.x+1);
131

132
   ulong total=0;
133

134
   for (ulong i=0;i<iterations;i++) {
135

136
      float x=MWCfp ;
137
      float y=MWCfp ;
138

139
      // Matching test
140
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
141
      total+=inside;
142

143
   }
144

145
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
146
   __syncthreads();
147

148
}
149

150
__global__ void MainLoopBlocks64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
151
{
152
   uint z=seed_z/(blockIdx.x+1);
153
   uint w=seed_w/(blockIdx.x+1);
154

155
   ulong total=0;
156

157
   for (ulong i=0;i<iterations;i++) {
158

159
      double x=(double)MWCfp ;
160
      double y=(double)MWCfp ;
161

162
      // Matching test
163
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
164
      total+=inside;
165

166
   }
167

168
   s[blockIdx.x]=total;
169
   __syncthreads();
170

171
}
172

173
__global__ void MainLoopThreads64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
174
{
175
   uint z=seed_z/(threadIdx.x+1);
176
   uint w=seed_w/(threadIdx.x+1);
177

178
   ulong total=0;
179

180
   for (ulong i=0;i<iterations;i++) {
181

182
      double x=(double)MWCfp ;
183
      double y=(double)MWCfp ;
184

185
      // Matching test
186
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
187
      total+=inside;
188

189
   }
190

191
   s[threadIdx.x]=total;
192
   __syncthreads();
193

194
}
195

196
__global__ void MainLoopHybrid64(ulong *s,ulong iterations,uint seed_w,uint seed_z)
197
{
198
   uint z=seed_z/(blockDim.x*blockIdx.x+threadIdx.x+1);
199
   uint w=seed_w/(blockDim.x*blockIdx.x+threadIdx.x+1);
200

201
   ulong total=0;
202

203
   for (ulong i=0;i<iterations;i++) {
204

205
      double x=(double)MWCfp ;
206
      double y=(double)MWCfp ;
207

208
      // Matching test
209
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
210
      total+=inside;
211

212
   }
213

214
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
215
   __syncthreads();
216

217
}
218
"""
219

    
220
KERNEL_CODE_OPENCL="""
221
#pragma OPENCL EXTENSION cl_khr_fp64: enable
222

223
// Marsaglia RNG very simple implementation
224
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
225
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
226
#define MWC   (znew+wnew)
227
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
228
#define CONG  (jcong=69069*jcong+1234567)
229
#define KISS  ((MWC^CONG)+SHR3)
230

231
#define MWCfp MWC * 2.328306435454494e-10f
232
#define KISSfp KISS * 2.328306435454494e-10f
233

234
__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
235
{
236
   uint z=seed_z+get_global_id(0);
237
   uint w=seed_w+get_global_id(0);
238

239
   ulong total=0;
240

241
   for (ulong i=0;i<iterations;i++) {
242

243
      float x=MWCfp ;
244
      float y=MWCfp ;
245

246
      // Matching test
247
      ulong inside=((x*x+y*y) <= 1.0f) ? 1:0;
248
      total+=inside;
249
   }
250
   barrier(CLK_GLOBAL_MEM_FENCE);
251
   s[get_global_id(0)]=total;
252
      
253
}
254

255
__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
256
{
257
   uint z=seed_z+get_local_id(0);
258
   uint w=seed_w+get_local_id(0);
259

260
   ulong total=0;
261

262
   for (ulong i=0;i<iterations;i++) {
263

264
      float x=MWCfp ;
265
      float y=MWCfp ;
266

267
      // Matching test
268
      ulong inside=((x*x+y*y) <= 1.0f) ? 1:0;
269
      total+=inside;
270
   }
271
   barrier(CLK_LOCAL_MEM_FENCE);
272
   s[get_local_id(0)]=total;
273
      
274
}
275

276
__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
277
{
278
   uint z=seed_z+get_global_id(0);
279
   uint w=seed_w+get_global_id(0);
280

281
   ulong total=0;
282

283
   for (uint i=0;i<iterations;i++) {
284

285
      float x=MWCfp ;
286
      float y=MWCfp ;
287

288
      // Matching test
289
      ulong inside=((x*x+y*y) <= 1.0f) ? 1:0;
290
      total+=inside;
291
   }
292
   barrier(CLK_GLOBAL_MEM_FENCE || CLK_GLOBAL_MEM_FENCE);
293
   // s[get_group_id(0)*get_num_groups(0)+get_local_id(0)]=total;
294
   s[get_global_id(0)]=total;
295
      
296
}
297

298
__kernel void MainLoopGlobal64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
299
{
300
   uint z=seed_z+get_global_id(0);
301
   uint w=seed_w+get_global_id(0);
302

303
   ulong total=0;
304

305
   for (ulong i=0;i<iterations;i++) {
306

307
      double x=(double)MWCfp ;
308
      double y=(double)MWCfp ;
309

310
      // Matching test
311
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
312
      total+=inside;
313
   }
314
   barrier(CLK_GLOBAL_MEM_FENCE);
315
   s[get_global_id(0)]=total;
316
      
317
}
318

319
__kernel void MainLoopLocal64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
320
{
321
   uint z=seed_z+get_local_id(0);
322
   uint w=seed_w+get_local_id(0);
323

324
   ulong total=0;
325

326
   for (ulong i=0;i<iterations;i++) {
327

328
      double x=(double)MWCfp ;
329
      double y=(double)MWCfp ;
330

331
      // Matching test
332
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
333
      total+=inside;
334
   }
335
   barrier(CLK_LOCAL_MEM_FENCE);
336
   s[get_local_id(0)]=total;
337
      
338
}
339

340
__kernel void MainLoopHybrid64(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
341
{
342
   uint z=seed_z+get_global_id(0);
343
   uint w=seed_w+get_global_id(0);
344

345
   ulong total=0;
346

347
   for (uint i=0;i<iterations;i++) {
348

349
      double x=(double)MWCfp ;
350
      double y=(double)MWCfp ;
351

352
      // Matching test
353
      ulong inside=((x*x+y*y) < 1.0f) ? 1:0;
354
      total+=inside;
355
   }
356
   barrier(CLK_LOCAL_MEM_FENCE);
357
   s[get_global_id(0)]=total;
358
      
359
}
360
"""
361

    
362
def MetropolisCuda(circle,iterations,steps,jobs,ParaStyle,DoublePrecision):
363

    
364
  # Avec PyCUDA autoinit, rien a faire !
365
  
366
  circleCU = cuda.InOut(circle)
367
  
368
  mod = SourceModule(KERNEL_CODE_CUDA)
369

    
370
  MetropolisBlocksCU=mod.get_function("MainLoopBlocks")
371
  MetropolisJobsCU=mod.get_function("MainLoopThreads")
372
  MetropolisHybridCU=mod.get_function("MainLoopHybrid")
373
  MetropolisBlocks64CU=mod.get_function("MainLoopBlocks64")
374
  MetropolisJobs64CU=mod.get_function("MainLoopThreads64")
375
  MetropolisHybrid64CU=mod.get_function("MainLoopHybrid64")
376
  
377
  start = pycuda.driver.Event()
378
  stop = pycuda.driver.Event()
379
  
380
  MyPi=numpy.zeros(steps)
381
  MyDuration=numpy.zeros(steps)
382

    
383
  if iterations%jobs==0:
384
    iterationsCL=numpy.uint64(iterations/jobs)
385
    iterationsNew=iterationsCL*jobs
386
  else:
387
    iterationsCL=numpy.uint64(iterations/jobs+1)
388
    iterationsNew=iterations
389

    
390
  for i in range(steps):
391
    start.record()
392
    start.synchronize()
393
    if ParaStyle=='Blocks':
394
      if DoublePrecision:
395
        MetropolisBlocksCU(circleCU,
396
                           numpy.uint64(iterationsCL),
397
                           numpy.uint32(nprnd(2**30/jobs)),
398
                           numpy.uint32(nprnd(2**30/jobs)),
399
                           grid=(jobs,1),
400
                           block=(1,1,1))
401
      else:
402
        MetropolisBlocks64CU(circleCU,
403
                             numpy.uint64(iterationsCL),
404
                             numpy.uint32(nprnd(2**30/jobs)),
405
                             numpy.uint32(nprnd(2**30/jobs)),
406
                             grid=(jobs,1),
407
                             block=(1,1,1))
408
        
409
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
410
            (Alu,jobs,1,ParaStyle)      
411
    elif ParaStyle=='Hybrid':
412
      threads=BestThreadsNumber(jobs)
413
      if DoublePrecision:
414
        MetropolisHybrid64CU(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=(threads,1,1))
420
      else:
421
        MetropolisHybridCU(circleCU,
422
                           numpy.uint64(iterationsCL),
423
                           numpy.uint32(nprnd(2**30/jobs)),
424
                           numpy.uint32(nprnd(2**30/jobs)),
425
                           grid=(jobs,1),
426
                           block=(threads,1,1))
427
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
428
            (Alu,jobs/threads,threads,ParaStyle)
429
    else:
430
      if DoublePrecision:
431
        MetropolisJobs64CU(circleCU,
432
                           numpy.uint64(iterationsCL),
433
                           numpy.uint32(nprnd(2**30/jobs)),
434
                           numpy.uint32(nprnd(2**30/jobs)),
435
                           grid=(1,1),
436
                           block=(jobs,1,1))
437
      else:
438
        MetropolisJobsCU(circleCU,
439
                         numpy.uint64(iterationsCL),
440
                         numpy.uint32(nprnd(2**30/jobs)),
441
                         numpy.uint32(nprnd(2**30/jobs)),
442
                         grid=(1,1),
443
                         block=(jobs,1,1))
444
      print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
445
            (Alu,jobs,1,ParaStyle)
446
    stop.record()
447
    stop.synchronize()
448
                
449
    elapsed = start.time_till(stop)*1e-3
450

    
451
    MyDuration[i]=elapsed
452
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
453
    MyPi[i]=numpy.median(AllPi)
454
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
455

    
456

    
457
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
458

    
459
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
460

    
461

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

    
505
  # Je recupere les flag possibles pour les buffers
506
  mf = cl.mem_flags
507
        
508
  circleCL = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=circle)
509

    
510
  MetropolisCL = cl.Program(ctx,KERNEL_CODE_OPENCL).build( \
511
    options = "-cl-mad-enable -cl-fast-relaxed-math")
512

    
513
  i=0
514

    
515
  MyPi=numpy.zeros(steps)
516
  MyDuration=numpy.zeros(steps)
517
  
518
  if iterations%jobs==0:
519
    iterationsCL=numpy.uint64(iterations/jobs)
520
    iterationsNew=numpy.uint64(iterationsCL*jobs)
521
  else:
522
    iterationsCL=numpy.uint64(iterations/jobs+1)
523
    iterationsNew=numpy.uint64(iterations)
524

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

    
583
    CLLaunch.wait()
584
    cl.enqueue_copy(queue, circle, circleCL).wait()
585

    
586
    elapsed = 1e-9*(CLLaunch.profile.end - CLLaunch.profile.start)
587

    
588
    print circle,numpy.mean(circle),numpy.median(circle),numpy.std(circle)
589
    MyDuration[i]=elapsed
590
    AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
591
    MyPi[i]=numpy.median(AllPi)
592
    print MyPi[i],numpy.std(AllPi),MyDuration[i]
593

    
594
  circleCL.release()
595

    
596
  print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration)
597
        
598
  return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration))
599

    
600

    
601
def FitAndPrint(N,D,Curves):
602

    
603
  from scipy.optimize import curve_fit
604
  import matplotlib.pyplot as plt
605

    
606
  try:
607
    coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
608

    
609
    D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
610
    coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
611
    coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
612
    coeffs_Amdahl[0]=D[0]
613
    print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
614
        (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
615
  except:
616
    print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
617

    
618
  try:
619
    coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
620

    
621
    D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
622
    coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
623
    coeffs_AmdahlR[0]=D[0]
624
    print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
625
        (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
626

    
627
  except:
628
    print "Impossible to fit for Reduced Amdahl law : only %i elements" % len(D) 
629

    
630
  try:
631
    coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
632

    
633
    coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
634
    # coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
635
    coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
636
    coeffs_Mylq[0]=D[0]
637
    print "Mylq Normalized : T=%.2f(%.6f+%.6f/N)+%.6f*N" % (coeffs_Mylq[0],
638
                                                            coeffs_Mylq[1],
639
                                                            coeffs_Mylq[3],
640
                                                            coeffs_Mylq[2])
641
    D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
642
                coeffs_Mylq[3])
643
  except:
644
    print "Impossible to fit for Mylq law : only %i elements" % len(D) 
645

    
646
  try:
647
    coeffs_Mylq2, matcov_Mylq2 = curve_fit(Mylq2, N, D)
648

    
649
    coeffs_Mylq2[1]=coeffs_Mylq2[1]*coeffs_Mylq2[0]/D[0]
650
    # coeffs_Mylq2[2]=coeffs_Mylq2[2]*coeffs_Mylq2[0]/D[0]
651
    # coeffs_Mylq2[3]=coeffs_Mylq2[3]*coeffs_Mylq2[0]/D[0]
652
    coeffs_Mylq2[4]=coeffs_Mylq2[4]*coeffs_Mylq2[0]/D[0]
653
    coeffs_Mylq2[0]=D[0]
654
    print "Mylq 2nd order Normalized: T=%.2f(%.6f+%.6f/N)+%.6f*N+%.6f*N^2" % \
655
        (coeffs_Mylq2[0],coeffs_Mylq2[1],
656
         coeffs_Mylq2[4],coeffs_Mylq2[2],coeffs_Mylq2[3])
657

    
658
  except:
659
    print "Impossible to fit for 2nd order Mylq law : only %i elements" % len(D) 
660

    
661
  if Curves:
662
    plt.xlabel("Number of Threads/work Items")
663
    plt.ylabel("Total Elapsed Time")
664

    
665
    Experience,=plt.plot(N,D,'ro') 
666
    try:
667
      pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
668
      pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
669
    except:
670
      print "Fit curves seem not to be available"
671

    
672
    plt.legend()
673
    plt.show()
674

    
675
if __name__=='__main__':
676

    
677
  # Set defaults values
678
  
679
  # Alu can be CPU, GPU or ACCELERATOR
680
  Alu='CPU'
681
  # Id of GPU : 1 is for first find !
682
  Device=0
683
  # GPU style can be Cuda (Nvidia implementation) or OpenCL
684
  GpuStyle='OpenCL'
685
  # Parallel distribution can be on Threads or Blocks
686
  ParaStyle='Blocks'
687
  # Iterations is integer
688
  Iterations=100000000
689
  # JobStart in first number of Jobs to explore
690
  JobStart=1
691
  # JobEnd is last number of Jobs to explore
692
  JobEnd=16
693
  # JobStep is the step of Jobs to explore
694
  JobStep=1
695
  # Redo is the times to redo the test to improve metrology
696
  Redo=1
697
  # OutMetrology is method for duration estimation : False is GPU inside
698
  OutMetrology=False
699
  Metrology='InMetro'
700
  # Curves is True to print the curves
701
  Curves=False
702
  # Fit is True to print the curves
703
  Fit=False
704
  # DoublePrecision on FP calculus
705
  DoublePrecision=False
706

    
707
  try:
708
    opts, args = getopt.getopt(sys.argv[1:],"hoclfa:g:p:i:s:e:t:r:d:",["alu=","gpustyle=","parastyle=","iterations=","jobstart=","jobend=","jobstep=","redo=","device="])
709
  except getopt.GetoptError:
710
    print '%s -o (Out of Core Metrology) -c (Print Curves) -l (Double Precision) -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> ' % sys.argv[0]
711
    sys.exit(2)
712
    
713
  for opt, arg in opts:
714
    if opt == '-h':
715
      print '%s -o (Out of Core Metrology) -c (Print Curves) -l (Double Precision) -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>' % sys.argv[0]
716

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

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

    
761
  if Alu=='CPU' and GpuStyle=='CUDA':
762
    print "Alu can't be CPU for CUDA, set Alu to GPU"
763
    Alu='GPU'
764

    
765
  if ParaStyle not in ('Blocks','Threads','Hybrid'):
766
    print "%s not exists, ParaStyle set as Threads !" % ParaStyle
767
    ParaStyle='Threads'
768

    
769
  print "Compute unit : %s" % Alu
770
  print "Device Identification : %s" % Device
771
  print "GpuStyle used : %s" % GpuStyle
772
  print "Parallel Style used : %s" % ParaStyle
773
  print "Iterations : %s" % Iterations
774
  print "Number of threads on start : %s" % JobStart
775
  print "Number of threads on end : %s" % JobEnd
776
  print "Number of redo : %s" % Redo
777
  print "Metrology done out of CPU/GPU : %r" % OutMetrology
778
  print "Double Precision in Kernels : %r" % DoublePrecision
779

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

    
790
  if GpuStyle=='OpenCL':
791
    try:
792
      # For PyOpenCL import
793
      import pyopencl as cl
794
      Id=1
795
      for platform in cl.get_platforms():
796
        for device in platform.get_devices():
797
          deviceType=cl.device_type.to_string(device.type)
798
          print "Device #%i of type %s : %s" % (Id,deviceType,device.name)
799
          if Id == Device:
800
            # Set the Alu as detected Device Type
801
            Alu=deviceType
802
          Id=Id+1
803
    except ImportError:
804
      print "Platform does not seem to support CUDA"
805
      
806
  average=numpy.array([]).astype(numpy.float32)
807
  median=numpy.array([]).astype(numpy.float32)
808
  stddev=numpy.array([]).astype(numpy.float32)
809

    
810
  ExploredJobs=numpy.array([]).astype(numpy.uint32)
811

    
812
  Jobs=JobStart
813

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

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

    
855
    if (avg,med,std) != (0,0,0):
856
      print "jobs,avg,med,std",Jobs,avg,med,std
857
      average=numpy.append(average,avg)
858
      median=numpy.append(median,med)
859
      stddev=numpy.append(stddev,std)
860
    else:
861
      print "Values seem to be wrong..."
862
    #THREADS*=2
863
    if DoublePrecision:
864
      Precision='DP'
865
    else:
866
      Precision='SP'
867
    if len(average)!=0:
868
      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))
869
      ToSave=[ ExploredJobs,average,median,stddev ]
870
      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))
871
    Jobs+=JobStep
872

    
873
  if Fit:
874
    FitAndPrint(ExploredJobs,median,Curves)
875