Statistiques
| Révision :

root / Pi / XPU / PiXpuMPI.py @ 127

Historique | Voir | Annoter | Télécharger (14,53 ko)

1
#!/usr/bin/env python3
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
import mpi4py
30
from mpi4py import MPI
31

    
32
from PiXPU import *
33

    
34
if __name__=='__main__':
35

    
36
    # MPI Init
37
    comm = MPI.COMM_WORLD
38
    rank = comm.Get_rank()
39
        
40
    # Define number of Nodes on with computing is performed (exclude 0)
41
    RankSize=comm.Get_size()
42

    
43
    if rank == 0:
44
    
45
        # Set defaults values
46
  
47
        # Id of Device : 1 is for first find !
48
        Device=1
49
        # GPU style can be Cuda (Nvidia implementation) or OpenCL
50
        GpuStyle='OpenCL'
51
        # Iterations is integer
52
        Iterations=10000000
53
        # BlocksBlocks in first number of Blocks to explore
54
        BlocksBegin=1
55
        # BlocksEnd is last number of Blocks to explore
56
        BlocksEnd=16
57
        # BlocksStep is the step of Blocks to explore
58
        BlocksStep=1
59
        # ThreadsBlocks in first number of Blocks to explore
60
        ThreadsBegin=1
61
        # ThreadsEnd is last number of Blocks to explore
62
        ThreadsEnd=1
63
        # ThreadsStep is the step of Blocks to explore
64
        ThreadsStep=1
65
        # Redo is the times to redo the test to improve metrology
66
        Redo=1
67
        # OutMetrology is method for duration estimation : False is GPU inside
68
        OutMetrology=False
69
        Metrology='InMetro'
70
        # Curves is True to print the curves
71
        Curves=False
72
        # Fit is True to print the curves
73
        Fit=False
74
        # Marsaglia RNG
75
        RNG='MWC'
76
        # Value type : INT32, INT64, FP32, FP64
77
        ValueType='FP32'
78

    
79
        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>'
80
    
81
        try:
82
            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="])
83
        except getopt.GetoptError:
84
            print(HowToUse % sys.argv[0])
85
            sys.exit(2)
86

    
87
        # List of Devices
88
        Devices=[]
89
        Alu={}
90
        
91
        for opt, arg in opts:
92
            if opt == '-h':
93
                print(HowToUse % sys.argv[0])
94

    
95
                print("\nInformations about devices detected under OpenCL:")
96
                # For PyOpenCL import
97
                try:
98
                    import pyopencl as cl
99
                    Id=1
100
                    for platform in cl.get_platforms():
101
                        for device in platform.get_devices():
102
                            deviceType=cl.device_type.to_string(device.type)
103
                            print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
104
                            Id=Id+1
105

    
106
                    print
107
                except:
108
                    print("Your platform does not seem to support OpenCL")
109

    
110
                # For PyCUDA import
111
                try:
112
                    import pycuda.driver as cuda
113
                    cuda.init()
114
                    for Id in range(cuda.Device.count()):
115
                        device=cuda.Device(Id)
116
                        print("Device #%i of type GPU : %s" % (Id,device.name()))
117
                    print
118
                except:
119
                    print("Your platform does not seem to support CUDA")
120
        
121
                sys.exit()
122
                    
123
            elif opt == '-o':
124
                OutMetrology=True
125
                Metrology='OutMetro'
126
            elif opt == '-c':
127
                Curves=True
128
            elif opt in ("-d", "--device"):
129
                Devices.append(int(arg))
130
            elif opt in ("-g", "--gpustyle"):
131
                GpuStyle = arg
132
            elif opt in ("-m", "--marsaglia"):
133
                RNG = arg
134
            elif opt in ("-v", "--valuetype"):
135
                ValueType = arg
136
            elif opt in ("-i", "--iterations"):
137
                Iterations = numpy.uint64(arg)
138
            elif opt in ("-b", "--blocksbegin"):
139
                BlocksBegin = int(arg)
140
            elif opt in ("-e", "--blocksend"):
141
                BlocksEnd = int(arg)
142
            elif opt in ("-s", "--blocksstep"):
143
                BlocksStep = int(arg)
144
            elif opt in ("-f", "--threadsfirst"):
145
                ThreadsBegin = int(arg)
146
            elif opt in ("-l", "--threadslast"):
147
                ThreadsEnd = int(arg)
148
            elif opt in ("-t", "--threadsstep"):
149
                ThreadsStep = int(arg)
150
            elif opt in ("-r", "--redo"):
151
                Redo = int(arg)
152

    
153
        print("Devices Identification : %s" % Devices)
154
        print("GpuStyle used : %s" % GpuStyle)
155
        print("Iterations : %s" % Iterations)
156
        print("Number of Blocks on begin : %s" % BlocksBegin)
157
        print("Number of Blocks on end : %s" % BlocksEnd)
158
        print("Step on Blocks : %s" % BlocksStep)
159
        print("Number of Threads on begin : %s" % ThreadsBegin)
160
        print("Number of Threads on end : %s" % ThreadsEnd)
161
        print("Step on Threads : %s" % ThreadsStep)
162
        print("Number of redo : %s" % Redo)
163
        print("Metrology done out of XPU : %r" % OutMetrology)
164
        print("Type of Marsaglia RNG used : %s" % RNG)
165
        print("Type of variable : %s" % ValueType)
166

    
167
        if GpuStyle=='CUDA':
168
            try:
169
                # For PyCUDA import
170
                import pycuda.driver as cuda
171
                import pycuda.gpuarray as gpuarray
172
                import pycuda.autoinit
173
                from pycuda.compiler import SourceModule
174
            except ImportError:
175
                print("Platform does not seem to support CUDA")
176

    
177
        if GpuStyle=='OpenCL':
178
            try:
179
                # For PyOpenCL import
180
                import pyopencl as cl
181
                Id=1
182
                for platform in cl.get_platforms():
183
                    for device in platform.get_devices():
184
                        deviceType=cl.device_type.to_string(device.type)
185
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip()))
186

    
187
                        if Id in Devices:
188
                            # Set the Alu as detected Device Type
189
                            Alu[Id]=deviceType
190
                        Id=Id+1
191
            except ImportError:
192
                print("Platform does not seem to support OpenCL")
193

    
194
        print(Devices,Alu)
195
            
196
        BlocksList=range(BlocksBegin,BlocksEnd+BlocksStep,BlocksStep)
197
        ThreadsList=range(ThreadsBegin,ThreadsEnd+ThreadsStep,ThreadsStep)
198
    
199
        ExploredJobs=numpy.array([]).astype(numpy.uint32)
200
        ExploredBlocks=numpy.array([]).astype(numpy.uint32)
201
        ExploredThreads=numpy.array([]).astype(numpy.uint32)
202
        avgD=numpy.array([]).astype(numpy.float32)
203
        medD=numpy.array([]).astype(numpy.float32)
204
        stdD=numpy.array([]).astype(numpy.float32)
205
        minD=numpy.array([]).astype(numpy.float32)
206
        maxD=numpy.array([]).astype(numpy.float32)
207
        avgR=numpy.array([]).astype(numpy.float32)
208
        medR=numpy.array([]).astype(numpy.float32)
209
        stdR=numpy.array([]).astype(numpy.float32)
210
        minR=numpy.array([]).astype(numpy.float32)
211
        maxR=numpy.array([]).astype(numpy.float32)
212

    
213
        for Blocks,Threads in itertools.product(BlocksList,ThreadsList):
214
        
215
            # print Blocks,Threads
216
            circle=numpy.zeros(Blocks*Threads).astype(numpy.uint64)
217
            ExploredJobs=numpy.append(ExploredJobs,Blocks*Threads)
218
            ExploredBlocks=numpy.append(ExploredBlocks,Blocks)
219
            ExploredThreads=numpy.append(ExploredThreads,Threads)
220
        
221
            if OutMetrology: 
222
                DurationItem=numpy.array([]).astype(numpy.float32)
223
                Duration=numpy.array([]).astype(numpy.float32)
224
                Rate=numpy.array([]).astype(numpy.float32)
225
                for i in range(Redo):
226
                    start=time.time()
227
                    if GpuStyle=='CUDA':
228
                        try:
229
                            Inside,NewIterations,DurationItem=MetropolisCuda(circle,Iterations,1,Blocks,Threads,RNG,ValueType)
230
                        except:
231
                            print("Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads))
232
                    elif GpuStyle=='OpenCL':
233
                        try:
234
                            MetroParamCL={}
235
                            MetroParamCL['Iterations']=Iterations
236
                            MetroParamCL['Steps']=1
237
                            MetroParamCL['Blocks']=Blocks
238
                            MetroParamCL['Threads']=Threads
239
                            MetroParamCL['Device']=Devices[0]
240
                            MetroParamCL['RNG']=RNG
241
                            MetroParamCL['ValueType']=ValueType
242
                            
243
                            OutputCL=MetropolisOpenCL(MetroParamCL)
244
                        except:
245
                            print("Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads))
246
                    Duration=numpy.append(Duration,time.time()-start)
247
                    Rate=numpy.append(Rate,NewIterations/Duration[-1])
248
            else:
249
                if GpuStyle=='CUDA':
250
                    try:
251
                        Inside,NewIterations,Duration=MetropolisCuda(circle,Iterations,Redo,Blocks,Threads,RNG,ValueType)
252
                    except:
253
                        print("Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads))
254
                elif GpuStyle=='OpenCL':
255
                    try:
256
                        IterationsMPI=numpy.uint64(Iterations/len(Devices))
257
                        if Iterations%len(Devices)!=0:
258
                            IterationsMPI+=1
259

    
260
                        r=1
261
                        time_start=time.time()
262
                        # Distribution of Devices over nodes
263
                        InputCL={}
264
                        InputCL['Iterations']=IterationsMPI
265
                        InputCL['Steps']=Redo
266
                        InputCL['Blocks']=Blocks
267
                        InputCL['Threads']=Threads
268
                        InputCL['RNG']=RNG
269
                        InputCL['ValueType']=ValueType
270
                        for Device in Devices[1:]:
271
                            print("Send to device %i on rank %i" % (Device,r))
272
                            InputCL['Device']=Device
273
                            comm.send('CONTINUE',dest=r,tag=11)
274
                            comm.send(InputCL,dest=r,tag=11)
275
                            r+=1
276

    
277
                        # Compute on rank 0
278
                        print("Compute on rank 0")
279
                        InputCL['Device']=Devices[0]
280
                        OutputCL=MetropolisOpenCL(InputCL)
281
                        Inside=OutputCL['Inside']
282
                        NewIterations=OutputCL['NewIterations']
283
                            
284
                        for slave in range(1,len(Devices)):
285
                            print("Get OutputCL from %i" % slave)
286
                            OutputCL=comm.recv(source=slave,tag=11)
287
                            print(OutputCL)
288
                            NewIterations+=OutputCL['NewIterations']
289
                            Inside+=OutputCL['Inside']
290

    
291
                        Duration=time.time()-time_start
292
                        print("Pi estimation %.8f" % (4./NewIterations*Inside))
293
                    except:
294
                        print("Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads))
295
            #Duration=OutputCL['Duration']
296
            #NewIterations=OutputCL['NewIterations']
297
            Rate=NewIterations/Duration
298
            
299
            avgD=numpy.append(avgD,numpy.average(Duration))
300
            medD=numpy.append(medD,numpy.median(Duration))
301
            stdD=numpy.append(stdD,numpy.std(Duration))
302
            minD=numpy.append(minD,numpy.min(Duration))
303
            maxD=numpy.append(maxD,numpy.max(Duration))
304
            avgR=numpy.append(avgR,numpy.average(Rate))
305
            medR=numpy.append(medR,numpy.median(Rate))
306
            stdR=numpy.append(stdR,numpy.std(Rate))
307
            minR=numpy.append(minR,numpy.min(Rate))
308
            maxR=numpy.append(maxR,numpy.max(Rate))
309

    
310
            print("%.2f %.2f %.2f %.2f %.2f %i %i %i %i %i" % (avgD[-1],medD[-1],stdD[-1],minD[-1],maxD[-1],avgR[-1],medR[-1],stdR[-1],minR[-1],maxR[-1]))
311
        
312
            numpy.savez("Pi_%s_%s_%s_%s_%s_%s_%s_%s_%.8i_Device%i_%s_%s" % (ValueType,RNG,Alu[Devices[0]],GpuStyle,BlocksBegin,BlocksEnd,ThreadsBegin,ThreadsEnd,Iterations,Devices[0],Metrology,gethostname()),(ExploredBlocks,ExploredThreads,avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR))
313
            ToSave=[ ExploredBlocks,ExploredThreads,avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR ]
314
            numpy.savetxt("Pi_%s_%s_%s_%s_%s_%s_%s_%i_%.8i_Device%i_%s_%s" % (ValueType,RNG,Alu[Devices[0]],GpuStyle,BlocksBegin,BlocksEnd,ThreadsBegin,ThreadsEnd,Iterations,Devices[0],Metrology,gethostname()),numpy.transpose(ToSave),fmt='%i %i %e %e %e %e %e %i %i %i %i %i')
315

    
316
            if Fit:
317
                FitAndPrint(ExploredJobs,median,Curves)
318
        # Send MPI exit tag
319
        for slave in range(1,RankSize):
320
            comm.send('BREAK',dest=slave,tag=11)
321
            
322
    else:
323
        while True:
324
            Signal=comm.recv(source=0,tag=11)
325
            if Signal=='CONTINUE':
326
                # Receive information from Master
327
                InputCL=comm.recv(source=0,tag=11)
328
                print("Parameters retreive for rank %s of %s on %s from master:" % (rank,RankSize,gethostname()))
329
                print("Input CL:" % InputCL)
330
                # Execute on slave
331
                OutputCL=MetropolisOpenCL(InputCL)
332
                print("Output CL:" % OutputCL)
333
                # Send information to Master
334
                comm.send(OutputCL,dest=0,tag=11)
335
                print("Data sent to master")
336
            else:
337
                print('Exit signal from Master')
338
                break