Révision 102

Pi/XPU/Pi-XPU.py (revision 102)
1
#!/usr/bin/env python
2

  
3
#
4
# Pi-by-MonteCarlo using PyCUDA/PyOpenCL
5
#
6
# CC BY-NC-SA 2011 : Emmanuel QUEMENER <emmanuel.quemener@gmail.com> 
7
# Cecill v2 : Emmanuel QUEMENER <emmanuel.quemener@gmail.com>
8
#
9
# Thanks to Andreas Klockner for PyCUDA:
10
# http://mathema.tician.de/software/pycuda
11
# Thanks to Andreas Klockner for PyOpenCL:
12
# http://mathema.tician.de/software/pyopencl
13
# 
14

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

  
19
# Common tools
20
import numpy
21
from numpy.random import randint as nprnd
22
import sys
23
import getopt
24
import time
25
import math
26
import itertools
27
from socket import gethostname
28

  
29
Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
30
Computing={'INT32':0,'INT64':1,'FP32':2,'FP64':3}
31

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

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

  
58
# Predicted Amdahl Law (Reduced with s=1-p)  
59
def AmdahlR(N, T1, p):
60
    return (T1*(1-p+p/N))
61

  
62
# Predicted Amdahl Law
63
def Amdahl(N, T1, s, p):
64
    return (T1*(s+p/N))
65

  
66
# Predicted Mylq Law with first order
67
def Mylq(N, T1,s,c,p):
68
    return (T1*(s+p/N)+c*N)
69

  
70
# Predicted Mylq Law with second order
71
def Mylq2(N, T1,s,c1,c2,p):
72
    return (T1*(s+p/N)+c1*N+c2*N*N)
73

  
74
KERNEL_CODE_CUDA="""
75
#define TCONG 0
76
#define TSHR3 1
77
#define TMWC 2
78
#define TKISS 3
79

  
80
#define TINT32 0
81
#define TINT64 1
82
#define TFP32 2
83
#define TFP64 3
84

  
85
// Marsaglia RNG very simple implementation
86

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

  
94
#define MWCfp MWC * 2.328306435454494e-10f
95
#define KISSfp KISS * 2.328306435454494e-10f
96
#define SHR3fp SHR3 * 2.328306435454494e-10f
97
#define CONGfp CONG * 2.328306435454494e-10f
98

  
99
__device__ ulong MainLoop(ulong iterations,uint seed_w,uint seed_z,size_t work)
100
{
101

  
102
#if TRNG == TCONG
103
   uint jcong=seed_z+work;
104
#elif TRNG == TSHR3
105
   uint jsr=seed_w+work;
106
#elif TRNG == TMWC
107
   uint z=seed_z+work;
108
   uint w=seed_w+work;
109
#elif TRNG == TKISS
110
   uint jcong=seed_z+work;
111
   uint jsr=seed_w+work;
112
   uint z=seed_z-work;
113
   uint w=seed_w-work;
114
#endif
115

  
116
   ulong total=0;
117

  
118
   for (ulong i=0;i<iterations;i++) {
119

  
120
#if TYPE == TINT32
121
    #define THEONE 1073741824
122
    #if TRNG == TCONG
123
        uint x=CONG>>17 ;
124
        uint y=CONG>>17 ;
125
    #elif TRNG == TSHR3
126
        uint x=SHR3>>17 ;
127
        uint y=SHR3>>17 ;
128
    #elif TRNG == TMWC
129
        uint x=MWC>>17 ;
130
        uint y=MWC>>17 ;
131
    #elif TRNG == TKISS
132
        uint x=KISS>>17 ;
133
        uint y=KISS>>17 ;
134
    #endif
135
#elif TYPE == TINT64
136
    #define THEONE 4611686018427387904
137
    #if TRNG == TCONG
138
        ulong x=(ulong)(CONG>>1) ;
139
        ulong y=(ulong)(CONG>>1) ;
140
    #elif TRNG == TSHR3
141
        ulong x=(ulong)(SHR3>>1) ;
142
        ulong y=(ulong)(SHR3>>1) ;
143
    #elif TRNG == TMWC
144
        ulong x=(ulong)(MWC>>1) ;
145
        ulong y=(ulong)(MWC>>1) ;
146
    #elif TRNG == TKISS
147
        ulong x=(ulong)(KISS>>1) ;
148
        ulong y=(ulong)(KISS>>1) ;
149
    #endif
150
#elif TYPE == TFP32
151
    #define THEONE 1.0f
152
    #if TRNG == TCONG
153
        float x=CONGfp ;
154
        float y=CONGfp ;
155
    #elif TRNG == TSHR3
156
        float x=SHR3fp ;
157
        float y=SHR3fp ;
158
    #elif TRNG == TMWC
159
        float x=MWCfp ;
160
        float y=MWCfp ;
161
    #elif TRNG == TKISS
162
      float x=KISSfp ;
163
      float y=KISSfp ;
164
    #endif
165
#elif TYPE == TFP64
166
    #define THEONE 1.0f
167
    #if TRNG == TCONG
168
        double x=(double)CONGfp ;
169
        double y=(double)CONGfp ;
170
    #elif TRNG == TSHR3
171
        double x=(double)SHR3fp ;
172
        double y=(double)SHR3fp ;
173
    #elif TRNG == TMWC
174
        double x=(double)MWCfp ;
175
        double y=(double)MWCfp ;
176
    #elif TRNG == TKISS
177
        double x=(double)KISSfp ;
178
        double y=(double)KISSfp ;
179
    #endif
180
#endif
181

  
182
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
183
      total+=inside;
184
   }
185

  
186
   return(total);
187
}
188

  
189
__global__ void MainLoopBlocks(ulong *s,ulong iterations,uint seed_w,uint seed_z)
190
{
191
   ulong total=MainLoop(iterations,seed_z,seed_w,blockIdx.x);
192
   s[blockIdx.x]=total;
193
   __syncthreads();
194

  
195
}
196

  
197
__global__ void MainLoopThreads(ulong *s,ulong iterations,uint seed_w,uint seed_z)
198
{
199
   ulong total=MainLoop(iterations,seed_z,seed_w,threadIdx.x);
200
   s[threadIdx.x]=total;
201
   __syncthreads();
202

  
203
}
204

  
205
__global__ void MainLoopHybrid(ulong *s,ulong iterations,uint seed_w,uint seed_z)
206
{
207
   ulong total=MainLoop(iterations,seed_z,seed_w,blockDim.x*blockIdx.x+threadIdx.x);
208
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
209
   __syncthreads();
210
}
211

  
212
"""
213

  
214
KERNEL_CODE_OPENCL="""
215
#define TCONG 0
216
#define TSHR3 1
217
#define TMWC 2
218
#define TKISS 3
219

  
220
#define TINT32 0
221
#define TINT64 1
222
#define TFP32 2
223
#define TFP64 3
224

  
225
// Marsaglia RNG very simple implementation
226
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
227
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
228

  
229
#define MWC   (znew+wnew)
230
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
231
#define CONG  (jcong=69069*jcong+1234567)
232
#define KISS  ((MWC^CONG)+SHR3)
233

  
234
#define MWCfp MWC * 2.328306435454494e-10f
235
#define KISSfp KISS * 2.328306435454494e-10f
236
#define CONGfp CONG * 2.328306435454494e-10f
237
#define SHR3fp SHR3 * 2.328306435454494e-10f
238

  
239
ulong MainLoop(ulong iterations,uint seed_z,uint seed_w,size_t work)
240
{
241

  
242
#if TRNG == TCONG
243
   uint jcong=seed_z+work;
244
#elif TRNG == TSHR3
245
   uint jsr=seed_w+work;
246
#elif TRNG == TMWC
247
   uint z=seed_z+work;
248
   uint w=seed_w+work;
249
#elif TRNG == TKISS
250
   uint jcong=seed_z+work;
251
   uint jsr=seed_w+work;
252
   uint z=seed_z-work;
253
   uint w=seed_w-work;
254
#endif
255

  
256
   ulong total=0;
257

  
258
   for (ulong i=0;i<iterations;i++) {
259

  
260
#if TYPE == TINT32
261
    #define THEONE 1073741824
262
    #if TRNG == TCONG
263
        uint x=CONG>>17 ;
264
        uint y=CONG>>17 ;
265
    #elif TRNG == TSHR3
266
        uint x=SHR3>>17 ;
267
        uint y=SHR3>>17 ;
268
    #elif TRNG == TMWC
269
        uint x=MWC>>17 ;
270
        uint y=MWC>>17 ;
271
    #elif TRNG == TKISS
272
        uint x=KISS>>17 ;
273
        uint y=KISS>>17 ;
274
    #endif
275
#elif TYPE == TINT64
276
    #define THEONE 4611686018427387904
277
    #if TRNG == TCONG
278
        ulong x=(ulong)(CONG>>1) ;
279
        ulong y=(ulong)(CONG>>1) ;
280
    #elif TRNG == TSHR3
281
        ulong x=(ulong)(SHR3>>1) ;
282
        ulong y=(ulong)(SHR3>>1) ;
283
    #elif TRNG == TMWC
284
        ulong x=(ulong)(MWC>>1) ;
285
        ulong y=(ulong)(MWC>>1) ;
286
    #elif TRNG == TKISS
287
        ulong x=(ulong)(KISS>>1) ;
288
        ulong y=(ulong)(KISS>>1) ;
289
    #endif
290
#elif TYPE == TFP32
291
    #define THEONE 1.0f
292
    #if TRNG == TCONG
293
        float x=CONGfp ;
294
        float y=CONGfp ;
295
    #elif TRNG == TSHR3
296
        float x=SHR3fp ;
297
        float y=SHR3fp ;
298
    #elif TRNG == TMWC
299
        float x=MWCfp ;
300
        float y=MWCfp ;
301
    #elif TRNG == TKISS
302
      float x=KISSfp ;
303
      float y=KISSfp ;
304
    #endif
305
#elif TYPE == TFP64
306
#pragma OPENCL EXTENSION cl_khr_fp64: enable
307
    #define THEONE 1.0f
308
    #if TRNG == TCONG
309
        double x=(double)CONGfp ;
310
        double y=(double)CONGfp ;
311
    #elif TRNG == TSHR3
312
        double x=(double)SHR3fp ;
313
        double y=(double)SHR3fp ;
314
    #elif TRNG == TMWC
315
        double x=(double)MWCfp ;
316
        double y=(double)MWCfp ;
317
    #elif TRNG == TKISS
318
        double x=(double)KISSfp ;
319
        double y=(double)KISSfp ;
320
    #endif
321
#endif
322

  
323
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
324
      total+=inside;
325
   }
326
   
327
   return(total);
328
}
329

  
330
__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
331
{
332
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
333
   barrier(CLK_GLOBAL_MEM_FENCE);
334
   s[get_global_id(0)]=total;     
335
}
336

  
337

  
338
__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
339
{
340
   ulong total=MainLoop(iterations,seed_z,seed_w,get_local_id(0));
341
   barrier(CLK_LOCAL_MEM_FENCE);
342
   s[get_local_id(0)]=total;
343
}
344

  
345
__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
346
{
347
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
348
   barrier(CLK_GLOBAL_MEM_FENCE || CLK_LOCAL_MEM_FENCE);
349
   s[get_global_id(0)]=total;
350
}
351

  
352
"""
353

  
354
def MetropolisCuda(circle,iterations,steps,blocks,threads,RNG,ValueType):
355

  
356
  # Avec PyCUDA autoinit, rien a faire !
357
  
358
    circleCU = cuda.InOut(circle)
359

  
360
    try:
361
        mod = SourceModule(KERNEL_CODE_CUDA,options=['--compiler-options','-Wall -DTRNG=%i -DTYPE=%s' % (Marsaglia[RNG],Computing[ValueType])])
362
    except:
363
        print "Compilation seems to brake"
364
  
365
    MetropolisBlocksCU=mod.get_function("MainLoopBlocks")
366
    MetropolisJobsCU=mod.get_function("MainLoopThreads")
367
    MetropolisHybridCU=mod.get_function("MainLoopHybrid")
368
  
369
    start = pycuda.driver.Event()
370
    stop = pycuda.driver.Event()
371
  
372
    MyPi=numpy.zeros(steps)
373
    MyDuration=numpy.zeros(steps)
374

  
375
    if iterations%jobs==0:
376
        iterationsCL=numpy.uint64(iterations/jobs)
377
        iterationsNew=iterationsCL*jobs
378
    else:
379
        iterationsCL=numpy.uint64(iterations/jobs+1)
380
        iterationsNew=iterations
381

  
382
    for i in range(steps):
383
        start.record()
384
        start.synchronize()
385
        MetropolisBlocksCU(circleCU,
386
                           numpy.uint64(iterationsCL),
387
                           numpy.uint32(nprnd(2**32)),
388
                           numpy.uint32(nprnd(2**32)),
389
                           grid=(jobs,1),
390
                           block=(threads,1,1))
391
        print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
392
            (Alu,jobs,1,ParaStyle)      
393
        stop.record()
394
        stop.synchronize()
395
                
396
        elapsed = start.time_till(stop)*1e-3
397

  
398
        MyDuration[i]=elapsed
399
        AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
400
        MyPi[i]=numpy.median(AllPi)
401
        print MyPi[i],numpy.std(AllPi),MyDuration[i]
402

  
403

  
404
    print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration)
405

  
406
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.min(MyDuration),numpy.max(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration),numpy.max(Iterations/MyDuration),numpy.max(Iterations/MyDuration))
407

  
408
def MetropolisOpenCL(circle,iterations,steps,blocks,threads,Device,
409
                     RNG,ValueType):
410
	
411
    # Initialisation des variables en les CASTant correctement
412

  
413
    Id=1
414
    HasXPU=False
415
    for platform in cl.get_platforms():
416
        for device in platform.get_devices():
417
            if Id==Device:
418
                XPU=device
419
                print "CPU/GPU selected: ",device.name.lstrip()
420
                HasXPU=True
421
            Id+=1
422

  
423
    if HasXPU==False:
424
        print "No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1)
425
        sys.exit()              
426

  
427
    # Je cree le contexte et la queue pour son execution
428
    ctx = cl.Context([XPU])
429
    queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
430

  
431
    # Je recupere les flag possibles pour les buffers
432
    mf = cl.mem_flags
433
	
434
    circleCL = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=circle)
435
  
436
    MetropolisCL = cl.Program(ctx,KERNEL_CODE_OPENCL).build( options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%s" % (Marsaglia[RNG],Computing[ValueType]))
437

  
438
    MyPi=numpy.zeros(steps)
439
    MyDuration=numpy.zeros(steps)
440
  
441
    jobs=blocks*threads;
442

  
443
    if iterations%jobs==0:
444
        iterationsCL=numpy.uint64(iterations/jobs)
445
        iterationsNew=numpy.uint64(iterationsCL*jobs)
446
    else:
447
        iterationsCL=numpy.uint64(iterations/jobs+1)
448
        iterationsNew=numpy.uint64(iterations)
449

  
450
    for i in range(steps):
451
        start_time=time.time()
452
        if threads == 1:
453
            CLLaunch=MetropolisCL.MainLoopGlobal(queue,(blocks,),None,
454
                                                 circleCL,
455
                                                 numpy.uint64(iterationsCL),
456
                                                 numpy.uint32(nprnd(2**32)),
457
                                                 numpy.uint32(nprnd(2**32)))
458
        else:
459
            CLLaunch=MetropolisCL.MainLoopHybrid(queue,(jobs,),(threads,),
460
                                                 circleCL,
461
                                                 numpy.uint64(iterationsCL),
462
                                                 numpy.uint32(nprnd(2**32)),
463
                                                 numpy.uint32(nprnd(2**32)))
464

  
465
        CLLaunch.wait()
466
        cl.enqueue_copy(queue, circle, circleCL).wait()
467

  
468
        elapsed = time.time()-start_time
469
        print "(Blocks/Threads)=(%i,%i) method done in %.2f s..." % (blocks,threads,elapsed)
470
            
471
        # Elapsed method based on CLLaunch doesn't work...
472
        # elapsed = 1e-9*(CLLaunch.profile.end - CLLaunch.profile.start)
473

  
474
        # print circle,numpy.mean(circle),numpy.median(circle),numpy.std(circle)
475
        MyDuration[i]=elapsed
476
        AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
477
        MyPi[i]=numpy.median(AllPi)
478
        # print MyPi[i],numpy.std(AllPi),MyDuration[i]
479

  
480
    circleCL.release()
481

  
482
    # print "(%i,%i) %f %f %f %i %i %i" % (blocks,threads,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration))
483
	
484
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.min(MyDuration),numpy.max(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration),numpy.min(Iterations/MyDuration),numpy.max(Iterations/MyDuration))
485

  
486

  
487
def FitAndPrint(N,D,Curves):
488

  
489
    from scipy.optimize import curve_fit
490
    import matplotlib.pyplot as plt
491

  
492
    try:
493
        coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
494

  
495
        D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
496
        coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
497
        coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
498
        coeffs_Amdahl[0]=D[0]
499
        print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
500
            (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
501
    except:
502
        print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
503

  
504
    try:
505
        coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
506

  
507
        D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
508
        coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
509
        coeffs_AmdahlR[0]=D[0]
510
        print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
511
            (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
512

  
513
    except:
514
        print "Impossible to fit for Reduced Amdahl law : only %i elements" \
515
            % len(D) 
516

  
517
    try:
518
        coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
519

  
520
        coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
521
        # coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
522
        coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
523
        coeffs_Mylq[0]=D[0]
524
        print "Mylq Normalized : T=%.2f(%.6f+%.6f/N)+%.6f*N" % (coeffs_Mylq[0],
525
                                                                coeffs_Mylq[1],
526
                                                                coeffs_Mylq[3],
527
                                                                coeffs_Mylq[2])
528
        D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
529
                    coeffs_Mylq[3])
530
    except:
531
        print "Impossible to fit for Mylq law : only %i elements" % len(D) 
532

  
533
    try:
534
        coeffs_Mylq2, matcov_Mylq2 = curve_fit(Mylq2, N, D)
535

  
536
        coeffs_Mylq2[1]=coeffs_Mylq2[1]*coeffs_Mylq2[0]/D[0]
537
        # coeffs_Mylq2[2]=coeffs_Mylq2[2]*coeffs_Mylq2[0]/D[0]
538
        # coeffs_Mylq2[3]=coeffs_Mylq2[3]*coeffs_Mylq2[0]/D[0]
539
        coeffs_Mylq2[4]=coeffs_Mylq2[4]*coeffs_Mylq2[0]/D[0]
540
        coeffs_Mylq2[0]=D[0]
541
        print "Mylq 2nd order Normalized: T=%.2f(%.6f+%.6f/N)+%.6f*N+%.6f*N^2" % \
542
            (coeffs_Mylq2[0],coeffs_Mylq2[1],
543
             coeffs_Mylq2[4],coeffs_Mylq2[2],coeffs_Mylq2[3])
544

  
545
    except:
546
        print "Impossible to fit for 2nd order Mylq law : only %i elements" % len(D) 
547

  
548
    if Curves:
549
        plt.xlabel("Number of Threads/work Items")
550
        plt.ylabel("Total Elapsed Time")
551

  
552
        Experience,=plt.plot(N,D,'ro') 
553
    try:
554
        pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
555
        pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
556
    except:
557
        print "Fit curves seem not to be available"
558

  
559
    plt.legend()
560
    plt.show()
561

  
562
if __name__=='__main__':
563

  
564
    # Set defaults values
565
  
566
    # Id of Device : 1 is for first find !
567
    Device=1
568
    # GPU style can be Cuda (Nvidia implementation) or OpenCL
569
    GpuStyle='OpenCL'
570
    # Iterations is integer
571
    Iterations=100000000
572
    # BlocksBlocks in first number of Blocks to explore
573
    BlocksBegin=1
574
    # BlocksEnd is last number of Blocks to explore
575
    BlocksEnd=16
576
    # BlocksStep is the step of Blocks to explore
577
    BlocksStep=1
578
    # ThreadsBlocks in first number of Blocks to explore
579
    ThreadsBegin=1
580
    # ThreadsEnd is last number of Blocks to explore
581
    ThreadsEnd=1
582
    # ThreadsStep is the step of Blocks to explore
583
    ThreadsStep=1
584
    # Redo is the times to redo the test to improve metrology
585
    Redo=1
586
    # OutMetrology is method for duration estimation : False is GPU inside
587
    OutMetrology=False
588
    Metrology='InMetro'
589
    # Curves is True to print the curves
590
    Curves=False
591
    # Fit is True to print the curves
592
    Fit=False
593
    # Marsaglia RNG
594
    RNG='MWC'
595
    # Value type : INT32, INT64, FP32, FP64
596
    ValueType='FP32'
597
  
598
    try:
599
        opts, args = getopt.getopt(sys.argv[1:],"hocg:i:b:e:s:f:l:t:r:d:m:v:",["gpustyle=","iterations=","blocksBegin=","blocksEnd=","blocksStep=","threadsFirst=","threadsLast=","threadssTep=","redo=","device=","marsaglia=","valuetype="])
600
    except getopt.GetoptError:
601
        print '%s -o (Out of Core Metrology) -c (Print Curves) -d <DeviceId> -g <CUDA/OpenCL> -i <Iterations> -b <blocksBegin> -e <JobEnd> -s <JobStep> -f <threadsFirst> -l <threadsLast> -t <threadssTep> -r <RedoToImproveStats> -m <SHR3/CONG/MWC/KISS> -v <INT32/INT64/FP32/FP64>' % sys.argv[0]
602
        sys.exit(2)
603
    
604
    for opt, arg in opts:
605
        if opt == '-h':
606
            print '%s -o (Out of Core Metrology) -c (Print Curves) -d <DeviceId> -g <CUDA/OpenCL> -i <Iterations> -b <blocksBegin> -e <JobEnd> -s <JobStep> -f <threadsFirst> -l <threadsLast> -t <threadssTep> -r <RedoToImproveStats> -m <SHR3/CONG/MWC/KISS> -v <INT32/INT64/FP32/FP64>' % sys.argv[0]
607

  
608
            print "\nInformations about devices detected under OpenCL:"
609
            # For PyOpenCL import
610
            try:
611
                import pyopencl as cl
612
                Id=1
613
                for platform in cl.get_platforms():
614
                    for device in platform.get_devices():
615
                        deviceType=cl.device_type.to_string(device.type)
616
                        print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip())
617
                        Id=Id+1
618

  
619
                print
620
                sys.exit()
621
            except ImportError:
622
                print "Your platform does not seem to support OpenCL"
623
        
624
        elif opt == '-o':
625
            OutMetrology=True
626
            Metrology='OutMetro'
627
        elif opt == '-c':
628
            Curves=True
629
        elif opt in ("-d", "--device"):
630
            Device = int(arg)
631
        elif opt in ("-g", "--gpustyle"):
632
            GpuStyle = arg
633
        elif opt in ("-m", "--marsaglia"):
634
            RNG = arg
635
        elif opt in ("-v", "--valuetype"):
636
            ValueType = arg
637
        elif opt in ("-i", "--iterations"):
638
            Iterations = numpy.uint64(arg)
639
        elif opt in ("-b", "--blocksbegin"):
640
            BlocksBegin = int(arg)
641
        elif opt in ("-e", "--blocksend"):
642
            BlocksEnd = int(arg)
643
        elif opt in ("-s", "--blocksstep"):
644
            BlocksStep = int(arg)
645
        elif opt in ("-f", "--threadsfirst"):
646
            ThreadsBegin = int(arg)
647
        elif opt in ("-l", "--threadslast"):
648
            ThreadsEnd = int(arg)
649
        elif opt in ("-t", "--threadsstep"):
650
            ThreadsStep = int(arg)
651
        elif opt in ("-r", "--redo"):
652
            Redo = int(arg)
653

  
654
    print "Device Identification : %s" % Device
655
    print "GpuStyle used : %s" % GpuStyle
656
    print "Iterations : %s" % Iterations
657
    print "Number of Blocks on begin : %s" % BlocksBegin
658
    print "Number of Blocks on end : %s" % BlocksEnd
659
    print "Step on Blocks : %s" % BlocksStep
660
    print "Number of Threads on begin : %s" % ThreadsBegin
661
    print "Number of Threads on end : %s" % ThreadsEnd
662
    print "Step on Threads : %s" % ThreadsStep
663
    print "Number of redo : %s" % Redo
664
    print "Metrology done out of XPU : %r" % OutMetrology
665
    print "Type of Marsaglia RNG used : %s" % RNG
666
    print "Type of variable : %s" % ValueType
667

  
668
    if GpuStyle=='CUDA':
669
        try:
670
            # For PyCUDA import
671
            import pycuda.driver as cuda
672
            import pycuda.gpuarray as gpuarray
673
            import pycuda.autoinit
674
            from pycuda.compiler import SourceModule
675
        except ImportError:
676
            print "Platform does not seem to support CUDA"
677

  
678
    if GpuStyle=='OpenCL':
679
        try:
680
            # For PyOpenCL import
681
            import pyopencl as cl
682
            Id=1
683
            for platform in cl.get_platforms():
684
                for device in platform.get_devices():
685
                    deviceType=cl.device_type.to_string(device.type)
686
                    print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip())
687

  
688
                    if Id == Device:
689
                    # Set the Alu as detected Device Type
690
                        Alu=deviceType
691
                    Id=Id+1
692
        except ImportError:
693
            print "Platform does not seem to support OpenCL"
694
      
695
    BlocksList=xrange(BlocksBegin,BlocksEnd+BlocksStep,BlocksStep)
696
    ThreadsList=xrange(ThreadsBegin,ThreadsEnd+ThreadsStep,ThreadsStep)
697
    
698
    ExploredJobs=numpy.array([]).astype(numpy.uint32)
699
    ExploredBlocks=numpy.array([]).astype(numpy.uint32)
700
    ExploredThreads=numpy.array([]).astype(numpy.uint32)
701
    averageD=numpy.array([]).astype(numpy.float32)
702
    medianD=numpy.array([]).astype(numpy.float32)
703
    stddevD=numpy.array([]).astype(numpy.float32)
704
    minimumD=numpy.array([]).astype(numpy.float32)
705
    maximumD=numpy.array([]).astype(numpy.float32)
706
    averageRate=numpy.array([]).astype(numpy.float32)
707
    medianRate=numpy.array([]).astype(numpy.float32)
708
    stddevRate=numpy.array([]).astype(numpy.float32)
709
    minimumRate=numpy.array([]).astype(numpy.float32)
710
    maximumRate=numpy.array([]).astype(numpy.float32)
711

  
712
    for Blocks,Threads in itertools.product(BlocksList,ThreadsList):
713
        
714
        # print Blocks,Threads
715
        avgD,medD,stdD,minD,maxD=0,0,0,0,0
716
        circle=numpy.zeros(Blocks*Threads).astype(numpy.uint64)
717
        ExploredJobs=numpy.append(ExploredJobs,Blocks*Threads)
718
        ExploredBlocks=numpy.append(ExploredBlocks,Blocks)
719
        ExploredThreads=numpy.append(ExploredThreads,Threads)
720
        
721
        if OutMetrology: 
722
            duration=numpy.array([]).astype(numpy.float32)
723
            rate=numpy.array([]).astype(numpy.float32)
724
            for i in range(Redo):
725
                start=time.time()
726
                if GpuStyle=='CUDA':
727
                    try:
728
                        aD,mD,sD,nD,xD,aR,mR,sR,nR,xR=MetropolisCuda(circle,Iterations,1,Blocks,Threads,RNG,ValueType)
729
                    except:
730
                        print "Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads)
731
                elif GpuStyle=='OpenCL':
732
                    try:
733
                        aD,mD,sD,nD,xD,aR,mR,sR,nR,xR=MetropolisOpenCL(circle,Iterations,1,Blocks,Threads,Device,RNG,ValueType)
734
                    except:
735
                        print "Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads)            
736
                duration=numpy.append(duration,time.time()-start)
737
                rate=numpy.append(rate,Iterations/(time.time()-start))
738
                if (aD,mD,sD,nD,xD) != (0,0,0,0,0):
739
                    avgD=numpy.mean(duration)
740
                    medD=numpy.median(duration)
741
                    stdD=numpy.std(duration)
742
                    minD=numpy.min(duration)
743
                    maxD=numpy.max(duration)
744
                    avgR=numpy.mean(Iterations/duration)
745
                    medR=numpy.median(Iterations/duration)
746
                    stdR=numpy.std(Iterations/duration)
747
                    minR=numpy.min(Iterations/duration)
748
                    maxR=numpy.max(Iterations/duration)
749
                else:
750
                    print "Values seem to be wrong..."
751
        else:
752
            if GpuStyle=='CUDA':
753
                try:
754
                    avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR=MetropolisCuda(circle,Iterations,Redo,Blocks,Threads,RNG,ValueType)
755
                except:
756
                    print "Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads)
757
            elif GpuStyle=='OpenCL':
758
                try:
759
                    avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR=MetropolisOpenCL(circle,Iterations,Redo,Blocks,Threads,Device,RNG,ValueType)
760
                except:
761
                    print "Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads)            
762

  
763
            if (avgD,medD,stdD,minD,maxD) != (0,0,0,0,0):
764
                print "(%i,%i) (%.2f %.2f %.2f %.2f %.2f) (%i %i %i %i %i)" % (Blocks,Threads,avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR)
765
                averageD=numpy.append(averageD,avgD)
766
                medianD=numpy.append(medianD,medD)
767
                stddevD=numpy.append(stddevD,stdD)
768
                minimumD=numpy.append(minimumD,minD)
769
                maximumD=numpy.append(maximumD,maxD)
770
                averageRate=numpy.append(averageRate,avgR)
771
                medianRate=numpy.append(medianRate,medR)
772
                stddevRate=numpy.append(stddevRate,stdR)
773
                minimumRate=numpy.append(minimumRate,minR)
774
                maximumRate=numpy.append(maximumRate,maxR)
775
            else:
776
                print "Values seem to be wrong..."
777
            if len(averageD)!=0:
778
                averageRate=averageRate.astype(int)
779
                medianRate=medianRate.astype(int)
780
                stddevRate=stddevRate.astype(int)
781

  
782
        numpy.savez("Pi_%s_%s_%s_%s_%s_%s_%s_%s_%.8i_Device%i_%s_%s" % (ValueType,RNG,Alu,GpuStyle,BlocksBegin,BlocksEnd,ThreadsBegin,ThreadsEnd,Iterations,Device,Metrology,gethostname()),(ExploredBlocks,ExploredThreads,averageD,medianD,stddevD,minimumD,maximumD,averageRate,medianRate,stddevRate,minimumRate,maximumRate))
783
        ToSave=[ ExploredBlocks,ExploredThreads,averageD,medianD,stddevD,minimumD,maximumD,averageRate,medianRate,stddevRate,minimumRate,maximumRate ]
784
        numpy.savetxt("Pi_%s_%s_%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (ValueType,RNG,Alu,GpuStyle,BlocksBegin,BlocksEnd,ThreadsBegin,ThreadsEnd,Iterations,Device,Metrology,gethostname()),numpy.transpose(ToSave),fmt='%i %i %e %e %e %e %e %i %i %i %i %i')
785

  
786
    if Fit:
787
        FitAndPrint(ExploredJobs,median,Curves)
Pi/XPU/PiXPU.py (revision 102)
1
#!/usr/bin/env python
2

  
3
#
4
# Pi-by-MonteCarlo using PyCUDA/PyOpenCL
5
#
6
# CC BY-NC-SA 2011 : Emmanuel QUEMENER <emmanuel.quemener@gmail.com> 
7
# Cecill v2 : Emmanuel QUEMENER <emmanuel.quemener@gmail.com>
8
#
9
# Thanks to Andreas Klockner for PyCUDA:
10
# http://mathema.tician.de/software/pycuda
11
# Thanks to Andreas Klockner for PyOpenCL:
12
# http://mathema.tician.de/software/pyopencl
13
# 
14

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

  
19
# Common tools
20
import numpy
21
from numpy.random import randint as nprnd
22
import sys
23
import getopt
24
import time
25
import math
26
import itertools
27
from socket import gethostname
28

  
29
Marsaglia={'CONG':0,'SHR3':1,'MWC':2,'KISS':3}
30
Computing={'INT32':0,'INT64':1,'FP32':2,'FP64':3}
31

  
32
# find prime factors of a number
33
# Get for WWW :
34
# http://pythonism.wordpress.com/2008/05/17/looking-at-factorisation-in-python/
35
def PrimeFactors(x):
36

  
37
    factorlist=numpy.array([]).astype('uint32')
38
    loop=2
39
    while loop<=x:
40
        if x%loop==0:
41
            x/=loop
42
            factorlist=numpy.append(factorlist,[loop])
43
        else:
44
            loop+=1
45
    return factorlist
46

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

  
59
# Predicted Amdahl Law (Reduced with s=1-p)  
60
def AmdahlR(N, T1, p):
61
    return (T1*(1-p+p/N))
62

  
63
# Predicted Amdahl Law
64
def Amdahl(N, T1, s, p):
65
    return (T1*(s+p/N))
66

  
67
# Predicted Mylq Law with first order
68
def Mylq(N, T1,s,c,p):
69
    return (T1*(s+p/N)+c*N)
70

  
71
# Predicted Mylq Law with second order
72
def Mylq2(N, T1,s,c1,c2,p):
73
    return (T1*(s+p/N)+c1*N+c2*N*N)
74

  
75
KERNEL_CODE_CUDA="""
76
#define TCONG 0
77
#define TSHR3 1
78
#define TMWC 2
79
#define TKISS 3
80

  
81
#define TINT32 0
82
#define TINT64 1
83
#define TFP32 2
84
#define TFP64 3
85

  
86
// Marsaglia RNG very simple implementation
87

  
88
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
89
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
90
#define MWC   (znew+wnew)
91
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
92
#define CONG  (jcong=69069*jcong+1234567)
93
#define KISS  ((MWC^CONG)+SHR3)
94

  
95
#define MWCfp MWC * 2.328306435454494e-10f
96
#define KISSfp KISS * 2.328306435454494e-10f
97
#define SHR3fp SHR3 * 2.328306435454494e-10f
98
#define CONGfp CONG * 2.328306435454494e-10f
99

  
100
__device__ ulong MainLoop(ulong iterations,uint seed_w,uint seed_z,size_t work)
101
{
102

  
103
#if TRNG == TCONG
104
   uint jcong=seed_z+work;
105
#elif TRNG == TSHR3
106
   uint jsr=seed_w+work;
107
#elif TRNG == TMWC
108
   uint z=seed_z+work;
109
   uint w=seed_w+work;
110
#elif TRNG == TKISS
111
   uint jcong=seed_z+work;
112
   uint jsr=seed_w+work;
113
   uint z=seed_z-work;
114
   uint w=seed_w-work;
115
#endif
116

  
117
   ulong total=0;
118

  
119
   for (ulong i=0;i<iterations;i++) {
120

  
121
#if TYPE == TINT32
122
    #define THEONE 1073741824
123
    #if TRNG == TCONG
124
        uint x=CONG>>17 ;
125
        uint y=CONG>>17 ;
126
    #elif TRNG == TSHR3
127
        uint x=SHR3>>17 ;
128
        uint y=SHR3>>17 ;
129
    #elif TRNG == TMWC
130
        uint x=MWC>>17 ;
131
        uint y=MWC>>17 ;
132
    #elif TRNG == TKISS
133
        uint x=KISS>>17 ;
134
        uint y=KISS>>17 ;
135
    #endif
136
#elif TYPE == TINT64
137
    #define THEONE 4611686018427387904
138
    #if TRNG == TCONG
139
        ulong x=(ulong)(CONG>>1) ;
140
        ulong y=(ulong)(CONG>>1) ;
141
    #elif TRNG == TSHR3
142
        ulong x=(ulong)(SHR3>>1) ;
143
        ulong y=(ulong)(SHR3>>1) ;
144
    #elif TRNG == TMWC
145
        ulong x=(ulong)(MWC>>1) ;
146
        ulong y=(ulong)(MWC>>1) ;
147
    #elif TRNG == TKISS
148
        ulong x=(ulong)(KISS>>1) ;
149
        ulong y=(ulong)(KISS>>1) ;
150
    #endif
151
#elif TYPE == TFP32
152
    #define THEONE 1.0f
153
    #if TRNG == TCONG
154
        float x=CONGfp ;
155
        float y=CONGfp ;
156
    #elif TRNG == TSHR3
157
        float x=SHR3fp ;
158
        float y=SHR3fp ;
159
    #elif TRNG == TMWC
160
        float x=MWCfp ;
161
        float y=MWCfp ;
162
    #elif TRNG == TKISS
163
      float x=KISSfp ;
164
      float y=KISSfp ;
165
    #endif
166
#elif TYPE == TFP64
167
    #define THEONE 1.0f
168
    #if TRNG == TCONG
169
        double x=(double)CONGfp ;
170
        double y=(double)CONGfp ;
171
    #elif TRNG == TSHR3
172
        double x=(double)SHR3fp ;
173
        double y=(double)SHR3fp ;
174
    #elif TRNG == TMWC
175
        double x=(double)MWCfp ;
176
        double y=(double)MWCfp ;
177
    #elif TRNG == TKISS
178
        double x=(double)KISSfp ;
179
        double y=(double)KISSfp ;
180
    #endif
181
#endif
182

  
183
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
184
      total+=inside;
185
   }
186

  
187
   return(total);
188
}
189

  
190
__global__ void MainLoopBlocks(ulong *s,ulong iterations,uint seed_w,uint seed_z)
191
{
192
   ulong total=MainLoop(iterations,seed_z,seed_w,blockIdx.x);
193
   s[blockIdx.x]=total;
194
   __syncthreads();
195

  
196
}
197

  
198
__global__ void MainLoopThreads(ulong *s,ulong iterations,uint seed_w,uint seed_z)
199
{
200
   ulong total=MainLoop(iterations,seed_z,seed_w,threadIdx.x);
201
   s[threadIdx.x]=total;
202
   __syncthreads();
203

  
204
}
205

  
206
__global__ void MainLoopHybrid(ulong *s,ulong iterations,uint seed_w,uint seed_z)
207
{
208
   ulong total=MainLoop(iterations,seed_z,seed_w,blockDim.x*blockIdx.x+threadIdx.x);
209
   s[blockDim.x*blockIdx.x+threadIdx.x]=total;
210
   __syncthreads();
211
}
212

  
213
"""
214

  
215
KERNEL_CODE_OPENCL="""
216
#define TCONG 0
217
#define TSHR3 1
218
#define TMWC 2
219
#define TKISS 3
220

  
221
#define TINT32 0
222
#define TINT64 1
223
#define TFP32 2
224
#define TFP64 3
225

  
226
// Marsaglia RNG very simple implementation
227
#define znew  ((z=36969*(z&65535)+(z>>16))<<16)
228
#define wnew  ((w=18000*(w&65535)+(w>>16))&65535)
229

  
230
#define MWC   (znew+wnew)
231
#define SHR3  (jsr=(jsr=(jsr=jsr^(jsr<<17))^(jsr>>13))^(jsr<<5))
232
#define CONG  (jcong=69069*jcong+1234567)
233
#define KISS  ((MWC^CONG)+SHR3)
234

  
235
#define MWCfp MWC * 2.328306435454494e-10f
236
#define KISSfp KISS * 2.328306435454494e-10f
237
#define CONGfp CONG * 2.328306435454494e-10f
238
#define SHR3fp SHR3 * 2.328306435454494e-10f
239

  
240
ulong MainLoop(ulong iterations,uint seed_z,uint seed_w,size_t work)
241
{
242

  
243
#if TRNG == TCONG
244
   uint jcong=seed_z+work;
245
#elif TRNG == TSHR3
246
   uint jsr=seed_w+work;
247
#elif TRNG == TMWC
248
   uint z=seed_z+work;
249
   uint w=seed_w+work;
250
#elif TRNG == TKISS
251
   uint jcong=seed_z+work;
252
   uint jsr=seed_w+work;
253
   uint z=seed_z-work;
254
   uint w=seed_w-work;
255
#endif
256

  
257
   ulong total=0;
258

  
259
   for (ulong i=0;i<iterations;i++) {
260

  
261
#if TYPE == TINT32
262
    #define THEONE 1073741824
263
    #if TRNG == TCONG
264
        uint x=CONG>>17 ;
265
        uint y=CONG>>17 ;
266
    #elif TRNG == TSHR3
267
        uint x=SHR3>>17 ;
268
        uint y=SHR3>>17 ;
269
    #elif TRNG == TMWC
270
        uint x=MWC>>17 ;
271
        uint y=MWC>>17 ;
272
    #elif TRNG == TKISS
273
        uint x=KISS>>17 ;
274
        uint y=KISS>>17 ;
275
    #endif
276
#elif TYPE == TINT64
277
    #define THEONE 4611686018427387904
278
    #if TRNG == TCONG
279
        ulong x=(ulong)(CONG>>1) ;
280
        ulong y=(ulong)(CONG>>1) ;
281
    #elif TRNG == TSHR3
282
        ulong x=(ulong)(SHR3>>1) ;
283
        ulong y=(ulong)(SHR3>>1) ;
284
    #elif TRNG == TMWC
285
        ulong x=(ulong)(MWC>>1) ;
286
        ulong y=(ulong)(MWC>>1) ;
287
    #elif TRNG == TKISS
288
        ulong x=(ulong)(KISS>>1) ;
289
        ulong y=(ulong)(KISS>>1) ;
290
    #endif
291
#elif TYPE == TFP32
292
    #define THEONE 1.0f
293
    #if TRNG == TCONG
294
        float x=CONGfp ;
295
        float y=CONGfp ;
296
    #elif TRNG == TSHR3
297
        float x=SHR3fp ;
298
        float y=SHR3fp ;
299
    #elif TRNG == TMWC
300
        float x=MWCfp ;
301
        float y=MWCfp ;
302
    #elif TRNG == TKISS
303
      float x=KISSfp ;
304
      float y=KISSfp ;
305
    #endif
306
#elif TYPE == TFP64
307
#pragma OPENCL EXTENSION cl_khr_fp64: enable
308
    #define THEONE 1.0f
309
    #if TRNG == TCONG
310
        double x=(double)CONGfp ;
311
        double y=(double)CONGfp ;
312
    #elif TRNG == TSHR3
313
        double x=(double)SHR3fp ;
314
        double y=(double)SHR3fp ;
315
    #elif TRNG == TMWC
316
        double x=(double)MWCfp ;
317
        double y=(double)MWCfp ;
318
    #elif TRNG == TKISS
319
        double x=(double)KISSfp ;
320
        double y=(double)KISSfp ;
321
    #endif
322
#endif
323

  
324
      ulong inside=((x*x+y*y) <= THEONE) ? 1:0;
325
      total+=inside;
326
   }
327
   
328
   return(total);
329
}
330

  
331
__kernel void MainLoopGlobal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
332
{
333
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
334
   barrier(CLK_GLOBAL_MEM_FENCE);
335
   s[get_global_id(0)]=total;     
336
}
337

  
338

  
339
__kernel void MainLoopLocal(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
340
{
341
   ulong total=MainLoop(iterations,seed_z,seed_w,get_local_id(0));
342
   barrier(CLK_LOCAL_MEM_FENCE);
343
   s[get_local_id(0)]=total;
344
}
345

  
346
__kernel void MainLoopHybrid(__global ulong *s,ulong iterations,uint seed_w,uint seed_z)
347
{
348
   ulong total=MainLoop(iterations,seed_z,seed_w,get_global_id(0));
349
   barrier(CLK_GLOBAL_MEM_FENCE || CLK_LOCAL_MEM_FENCE);
350
   s[get_global_id(0)]=total;
351
}
352

  
353
"""
354

  
355
def MetropolisCuda(circle,iterations,steps,blocks,threads,RNG,ValueType):
356

  
357
  # Avec PyCUDA autoinit, rien a faire !
358
  
359
    circleCU = cuda.InOut(circle)
360

  
361
    try:
362
        mod = SourceModule(KERNEL_CODE_CUDA,options=['--compiler-options','-Wall -DTRNG=%i -DTYPE=%s' % (Marsaglia[RNG],Computing[ValueType])])
363
    except:
364
        print "Compilation seems to brake"
365
  
366
    MetropolisBlocksCU=mod.get_function("MainLoopBlocks")
367
    MetropolisJobsCU=mod.get_function("MainLoopThreads")
368
    MetropolisHybridCU=mod.get_function("MainLoopHybrid")
369
  
370
    start = pycuda.driver.Event()
371
    stop = pycuda.driver.Event()
372
  
373
    MyPi=numpy.zeros(steps)
374
    MyDuration=numpy.zeros(steps)
375

  
376
    if iterations%jobs==0:
377
        iterationsCL=numpy.uint64(iterations/jobs)
378
        iterationsNew=iterationsCL*jobs
379
    else:
380
        iterationsCL=numpy.uint64(iterations/jobs+1)
381
        iterationsNew=iterations
382

  
383
    for i in range(steps):
384
        start.record()
385
        start.synchronize()
386
        MetropolisBlocksCU(circleCU,
387
                           numpy.uint64(iterationsCL),
388
                           numpy.uint32(nprnd(2**32)),
389
                           numpy.uint32(nprnd(2**32)),
390
                           grid=(jobs,1),
391
                           block=(threads,1,1))
392
        print "%s with (WorkItems/Threads)=(%i,%i) %s method done" % \
393
            (Alu,jobs,1,ParaStyle)      
394
        stop.record()
395
        stop.synchronize()
396
                
397
        elapsed = start.time_till(stop)*1e-3
398

  
399
        MyDuration[i]=elapsed
400
        AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
401
        MyPi[i]=numpy.median(AllPi)
402
        print MyPi[i],numpy.std(AllPi),MyDuration[i]
403

  
404

  
405
    print jobs,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration)
406

  
407
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.min(MyDuration),numpy.max(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration),numpy.max(Iterations/MyDuration),numpy.max(Iterations/MyDuration))
408

  
409
def MetropolisOpenCL(circle,iterations,steps,blocks,threads,Device,
410
                     RNG,ValueType):
411
	
412
    # Initialisation des variables en les CASTant correctement
413

  
414
    Id=1
415
    HasXPU=False
416
    for platform in cl.get_platforms():
417
        for device in platform.get_devices():
418
            if Id==Device:
419
                XPU=device
420
                print "CPU/GPU selected: ",device.name.lstrip()
421
                HasXPU=True
422
            Id+=1
423

  
424
    if HasXPU==False:
425
        print "No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1)
426
        sys.exit()              
427

  
428
    # Je cree le contexte et la queue pour son execution
429
    ctx = cl.Context([XPU])
430
    queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
431

  
432
    # Je recupere les flag possibles pour les buffers
433
    mf = cl.mem_flags
434
	
435
    circleCL = cl.Buffer(ctx, mf.WRITE_ONLY|mf.COPY_HOST_PTR,hostbuf=circle)
436
  
437
    MetropolisCL = cl.Program(ctx,KERNEL_CODE_OPENCL).build( options = "-cl-mad-enable -cl-fast-relaxed-math -DTRNG=%i -DTYPE=%s" % (Marsaglia[RNG],Computing[ValueType]))
438

  
439
    MyPi=numpy.zeros(steps)
440
    MyDuration=numpy.zeros(steps)
441
  
442
    jobs=blocks*threads;
443

  
444
    if iterations%jobs==0:
445
        iterationsCL=numpy.uint64(iterations/jobs)
446
        iterationsNew=numpy.uint64(iterationsCL*jobs)
447
    else:
448
        iterationsCL=numpy.uint64(iterations/jobs+1)
449
        iterationsNew=numpy.uint64(iterations)
450

  
451
    for i in range(steps):
452
        start_time=time.time()
453
        if threads == 1:
454
            CLLaunch=MetropolisCL.MainLoopGlobal(queue,(blocks,),None,
455
                                                 circleCL,
456
                                                 numpy.uint64(iterationsCL),
457
                                                 numpy.uint32(nprnd(2**32)),
458
                                                 numpy.uint32(nprnd(2**32)))
459
        else:
460
            CLLaunch=MetropolisCL.MainLoopHybrid(queue,(jobs,),(threads,),
461
                                                 circleCL,
462
                                                 numpy.uint64(iterationsCL),
463
                                                 numpy.uint32(nprnd(2**32)),
464
                                                 numpy.uint32(nprnd(2**32)))
465

  
466
        CLLaunch.wait()
467
        cl.enqueue_copy(queue, circle, circleCL).wait()
468

  
469
        elapsed = time.time()-start_time
470
        print "(Blocks/Threads)=(%i,%i) method done in %.2f s..." % (blocks,threads,elapsed)
471
            
472
        # Elapsed method based on CLLaunch doesn't work...
473
        # elapsed = 1e-9*(CLLaunch.profile.end - CLLaunch.profile.start)
474

  
475
        # print circle,numpy.mean(circle),numpy.median(circle),numpy.std(circle)
476
        MyDuration[i]=elapsed
477
        AllPi=4./numpy.float32(iterationsCL)*circle.astype(numpy.float32)
478
        MyPi[i]=numpy.median(AllPi)
479
        # print MyPi[i],numpy.std(AllPi),MyDuration[i]
480

  
481
    circleCL.release()
482

  
483
    # print "(%i,%i) %f %f %f %i %i %i" % (blocks,threads,numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration))
484
	
485
    return(numpy.mean(MyDuration),numpy.median(MyDuration),numpy.std(MyDuration),numpy.min(MyDuration),numpy.max(MyDuration),numpy.mean(Iterations/MyDuration),numpy.median(Iterations/MyDuration),numpy.std(Iterations/MyDuration),numpy.min(Iterations/MyDuration),numpy.max(Iterations/MyDuration))
486

  
487

  
488
def FitAndPrint(N,D,Curves):
489

  
490
    from scipy.optimize import curve_fit
491
    import matplotlib.pyplot as plt
492

  
493
    try:
494
        coeffs_Amdahl, matcov_Amdahl = curve_fit(Amdahl, N, D)
495

  
496
        D_Amdahl=Amdahl(N,coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
497
        coeffs_Amdahl[1]=coeffs_Amdahl[1]*coeffs_Amdahl[0]/D[0]
498
        coeffs_Amdahl[2]=coeffs_Amdahl[2]*coeffs_Amdahl[0]/D[0]
499
        coeffs_Amdahl[0]=D[0]
500
        print "Amdahl Normalized: T=%.2f(%.6f+%.6f/N)" % \
501
            (coeffs_Amdahl[0],coeffs_Amdahl[1],coeffs_Amdahl[2])
502
    except:
503
        print "Impossible to fit for Amdahl law : only %i elements" % len(D) 
504

  
505
    try:
506
        coeffs_AmdahlR, matcov_AmdahlR = curve_fit(AmdahlR, N, D)
507

  
508
        D_AmdahlR=AmdahlR(N,coeffs_AmdahlR[0],coeffs_AmdahlR[1])
509
        coeffs_AmdahlR[1]=coeffs_AmdahlR[1]*coeffs_AmdahlR[0]/D[0]
510
        coeffs_AmdahlR[0]=D[0]
511
        print "Amdahl Reduced Normalized: T=%.2f(%.6f+%.6f/N)" % \
512
            (coeffs_AmdahlR[0],1-coeffs_AmdahlR[1],coeffs_AmdahlR[1])
513

  
514
    except:
515
        print "Impossible to fit for Reduced Amdahl law : only %i elements" \
516
            % len(D) 
517

  
518
    try:
519
        coeffs_Mylq, matcov_Mylq = curve_fit(Mylq, N, D)
520

  
521
        coeffs_Mylq[1]=coeffs_Mylq[1]*coeffs_Mylq[0]/D[0]
522
        # coeffs_Mylq[2]=coeffs_Mylq[2]*coeffs_Mylq[0]/D[0]
523
        coeffs_Mylq[3]=coeffs_Mylq[3]*coeffs_Mylq[0]/D[0]
524
        coeffs_Mylq[0]=D[0]
525
        print "Mylq Normalized : T=%.2f(%.6f+%.6f/N)+%.6f*N" % (coeffs_Mylq[0],
526
                                                                coeffs_Mylq[1],
527
                                                                coeffs_Mylq[3],
528
                                                                coeffs_Mylq[2])
529
        D_Mylq=Mylq(N,coeffs_Mylq[0],coeffs_Mylq[1],coeffs_Mylq[2],
530
                    coeffs_Mylq[3])
531
    except:
532
        print "Impossible to fit for Mylq law : only %i elements" % len(D) 
533

  
534
    try:
535
        coeffs_Mylq2, matcov_Mylq2 = curve_fit(Mylq2, N, D)
536

  
537
        coeffs_Mylq2[1]=coeffs_Mylq2[1]*coeffs_Mylq2[0]/D[0]
538
        # coeffs_Mylq2[2]=coeffs_Mylq2[2]*coeffs_Mylq2[0]/D[0]
539
        # coeffs_Mylq2[3]=coeffs_Mylq2[3]*coeffs_Mylq2[0]/D[0]
540
        coeffs_Mylq2[4]=coeffs_Mylq2[4]*coeffs_Mylq2[0]/D[0]
541
        coeffs_Mylq2[0]=D[0]
542
        print "Mylq 2nd order Normalized: T=%.2f(%.6f+%.6f/N)+%.6f*N+%.6f*N^2" % \
543
            (coeffs_Mylq2[0],coeffs_Mylq2[1],
544
             coeffs_Mylq2[4],coeffs_Mylq2[2],coeffs_Mylq2[3])
545

  
546
    except:
547
        print "Impossible to fit for 2nd order Mylq law : only %i elements" % len(D) 
548

  
549
    if Curves:
550
        plt.xlabel("Number of Threads/work Items")
551
        plt.ylabel("Total Elapsed Time")
552

  
553
        Experience,=plt.plot(N,D,'ro') 
554
    try:
555
        pAmdahl,=plt.plot(N,D_Amdahl,label="Loi de Amdahl")    
556
        pMylq,=plt.plot(N,D_Mylq,label="Loi de Mylq")
557
    except:
558
        print "Fit curves seem not to be available"
559

  
560
    plt.legend()
561
    plt.show()
562

  
563
if __name__=='__main__':
564

  
565
    # Set defaults values
566
  
567
    # Id of Device : 1 is for first find !
568
    Device=1
569
    # GPU style can be Cuda (Nvidia implementation) or OpenCL
570
    GpuStyle='OpenCL'
571
    # Iterations is integer
572
    Iterations=100000000
573
    # BlocksBlocks in first number of Blocks to explore
574
    BlocksBegin=1
575
    # BlocksEnd is last number of Blocks to explore
576
    BlocksEnd=16
577
    # BlocksStep is the step of Blocks to explore
578
    BlocksStep=1
579
    # ThreadsBlocks in first number of Blocks to explore
580
    ThreadsBegin=1
581
    # ThreadsEnd is last number of Blocks to explore
582
    ThreadsEnd=1
583
    # ThreadsStep is the step of Blocks to explore
584
    ThreadsStep=1
585
    # Redo is the times to redo the test to improve metrology
586
    Redo=1
587
    # OutMetrology is method for duration estimation : False is GPU inside
588
    OutMetrology=False
589
    Metrology='InMetro'
590
    # Curves is True to print the curves
591
    Curves=False
592
    # Fit is True to print the curves
593
    Fit=False
594
    # Marsaglia RNG
595
    RNG='MWC'
596
    # Value type : INT32, INT64, FP32, FP64
597
    ValueType='FP32'
598

  
599
    HowToUse='%s -o (Out of Core Metrology) -c (Print Curves) -d <DeviceId> -g <CUDA/OpenCL> -i <Iterations> -b <BlocksBegin> -e <BlocksEnd> -s <BlocksStep> -f <ThreadsFirst> -l <ThreadsLast> -t <ThreadssTep> -r <RedoToImproveStats> -m <SHR3/CONG/MWC/KISS> -v <INT32/INT64/FP32/FP64>'
600
    
601
    try:
602
        opts, args = getopt.getopt(sys.argv[1:],"hocg:i:b:e:s:f:l:t:r:d:m:v:",["gpustyle=","iterations=","blocksBegin=","blocksEnd=","blocksStep=","threadsFirst=","threadsLast=","threadssTep=","redo=","device=","marsaglia=","valuetype="])
603
    except getopt.GetoptError:
604
        print HowToUse % sys.argv[0]
605
        sys.exit(2)
606
    
607
    for opt, arg in opts:
608
        if opt == '-h':
609
            print HowToUse % sys.argv[0]
610

  
611
            print "\nInformations about devices detected under OpenCL:"
612
            # For PyOpenCL import
613
            try:
614
                import pyopencl as cl
615
                Id=1
616
                for platform in cl.get_platforms():
617
                    for device in platform.get_devices():
618
                        deviceType=cl.device_type.to_string(device.type)
619
                        print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip())
620
                        Id=Id+1
621

  
622
                print
623
                sys.exit()
624
            except ImportError:
625
                print "Your platform does not seem to support OpenCL"
626
        
627
        elif opt == '-o':
628
            OutMetrology=True
629
            Metrology='OutMetro'
630
        elif opt == '-c':
631
            Curves=True
632
        elif opt in ("-d", "--device"):
633
            Device = int(arg)
634
        elif opt in ("-g", "--gpustyle"):
635
            GpuStyle = arg
636
        elif opt in ("-m", "--marsaglia"):
637
            RNG = arg
638
        elif opt in ("-v", "--valuetype"):
639
            ValueType = arg
640
        elif opt in ("-i", "--iterations"):
641
            Iterations = numpy.uint64(arg)
642
        elif opt in ("-b", "--blocksbegin"):
643
            BlocksBegin = int(arg)
644
        elif opt in ("-e", "--blocksend"):
645
            BlocksEnd = int(arg)
646
        elif opt in ("-s", "--blocksstep"):
647
            BlocksStep = int(arg)
648
        elif opt in ("-f", "--threadsfirst"):
649
            ThreadsBegin = int(arg)
650
        elif opt in ("-l", "--threadslast"):
651
            ThreadsEnd = int(arg)
652
        elif opt in ("-t", "--threadsstep"):
653
            ThreadsStep = int(arg)
654
        elif opt in ("-r", "--redo"):
655
            Redo = int(arg)
656

  
657
    print "Device Identification : %s" % Device
658
    print "GpuStyle used : %s" % GpuStyle
659
    print "Iterations : %s" % Iterations
660
    print "Number of Blocks on begin : %s" % BlocksBegin
661
    print "Number of Blocks on end : %s" % BlocksEnd
662
    print "Step on Blocks : %s" % BlocksStep
663
    print "Number of Threads on begin : %s" % ThreadsBegin
664
    print "Number of Threads on end : %s" % ThreadsEnd
665
    print "Step on Threads : %s" % ThreadsStep
666
    print "Number of redo : %s" % Redo
667
    print "Metrology done out of XPU : %r" % OutMetrology
668
    print "Type of Marsaglia RNG used : %s" % RNG
669
    print "Type of variable : %s" % ValueType
670

  
671
    if GpuStyle=='CUDA':
672
        try:
673
            # For PyCUDA import
674
            import pycuda.driver as cuda
675
            import pycuda.gpuarray as gpuarray
676
            import pycuda.autoinit
677
            from pycuda.compiler import SourceModule
678
        except ImportError:
679
            print "Platform does not seem to support CUDA"
680

  
681
    if GpuStyle=='OpenCL':
682
        try:
683
            # For PyOpenCL import
684
            import pyopencl as cl
685
            Id=1
686
            for platform in cl.get_platforms():
687
                for device in platform.get_devices():
688
                    deviceType=cl.device_type.to_string(device.type)
689
                    print "Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip())
690

  
691
                    if Id == Device:
692
                    # Set the Alu as detected Device Type
693
                        Alu=deviceType
694
                    Id=Id+1
695
        except ImportError:
696
            print "Platform does not seem to support OpenCL"
697
      
698
    BlocksList=xrange(BlocksBegin,BlocksEnd+BlocksStep,BlocksStep)
699
    ThreadsList=xrange(ThreadsBegin,ThreadsEnd+ThreadsStep,ThreadsStep)
700
    
701
    ExploredJobs=numpy.array([]).astype(numpy.uint32)
702
    ExploredBlocks=numpy.array([]).astype(numpy.uint32)
703
    ExploredThreads=numpy.array([]).astype(numpy.uint32)
704
    averageD=numpy.array([]).astype(numpy.float32)
... Ce différentiel a été tronqué car il excède la taille maximale pouvant être affichée.

Formats disponibles : Unified diff