Statistiques
| Révision :

root / Pi / XPU / PiXpuThreads.py @ 127

Historique | Voir | Annoter | Télécharger (12,24 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
from threading import Thread
30

    
31
from PiXPU import *
32

    
33
class threadWithReturn(Thread):
34
    def __init__(self, *args, **kwargs):
35
        super(threadWithReturn, self).__init__(*args, **kwargs)
36
        self._return = None
37

    
38
    def run(self):
39
        if self._target is not None:
40
            self._return = self._target(*self._args, **self._kwargs)
41

    
42
    def join(self, *args, **kwargs):
43
        super(threadWithReturn, self).join(*args, **kwargs)
44
        return self._return
45

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

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

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

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

    
109
                print
110
                sys.exit()
111
            except ImportError:
112
                print("Your platform does not seem to support OpenCL")
113
        
114
        elif opt == '-o':
115
            OutMetrology=True
116
            Metrology='OutMetro'
117
        elif opt == '-c':
118
            Curves=True
119
        elif opt in ("-d", "--device"):
120
            Devices.append(int(arg))
121
        elif opt in ("-g", "--gpustyle"):
122
            GpuStyle = arg
123
        elif opt in ("-m", "--marsaglia"):
124
            RNG = arg
125
        elif opt in ("-v", "--valuetype"):
126
            ValueType = arg
127
        elif opt in ("-i", "--iterations"):
128
            Iterations = numpy.uint64(arg)
129
        elif opt in ("-b", "--blocksbegin"):
130
            BlocksBegin = int(arg)
131
        elif opt in ("-e", "--blocksend"):
132
            BlocksEnd = int(arg)
133
        elif opt in ("-s", "--blocksstep"):
134
            BlocksStep = int(arg)
135
        elif opt in ("-f", "--threadsfirst"):
136
            ThreadsBegin = int(arg)
137
        elif opt in ("-l", "--threadslast"):
138
            ThreadsEnd = int(arg)
139
        elif opt in ("-t", "--threadsstep"):
140
            ThreadsStep = int(arg)
141
        elif opt in ("-r", "--redo"):
142
            Redo = int(arg)
143

    
144
    print("Devices Identification : %s" % Devices)
145
    print("GpuStyle used : %s" % GpuStyle)
146
    print("Iterations : %s" % Iterations)
147
    print("Number of Blocks on begin : %s" % BlocksBegin)
148
    print("Number of Blocks on end : %s" % BlocksEnd)
149
    print("Step on Blocks : %s" % BlocksStep)
150
    print("Number of Threads on begin : %s" % ThreadsBegin)
151
    print("Number of Threads on end : %s" % ThreadsEnd)
152
    print("Step on Threads : %s" % ThreadsStep)
153
    print("Number of redo : %s" % Redo)
154
    print("Metrology done out of XPU : %r" % OutMetrology)
155
    print("Type of Marsaglia RNG used : %s" % RNG)
156
    print("Type of variable : %s" % ValueType)
157

    
158
    if GpuStyle=='CUDA':
159
        try:
160
            # For PyCUDA import
161
            import pycuda.driver as cuda
162
            import pycuda.gpuarray as gpuarray
163
            import pycuda.autoinit
164
            from pycuda.compiler import SourceModule
165
        except ImportError:
166
            print("Platform does not seem to support CUDA")
167

    
168
    if GpuStyle=='OpenCL':
169
        try:
170
            # For PyOpenCL import
171
            import pyopencl as cl
172
            Id=0
173
            for platform in cl.get_platforms():
174
                for device in platform.get_devices():
175
                    deviceType=cl.device_type.to_string(device.type)
176
                    print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip()))
177

    
178
                    if Id in Devices:
179
                    # Set the Alu as detected Device Type
180
                        Alu[Id]=deviceType
181
                    Id=Id+1
182
        except ImportError:
183
            print("Platform does not seem to support OpenCL")
184

    
185
    print(Devices,Alu)
186
            
187
    BlocksList=range(BlocksBegin,BlocksEnd+BlocksStep,BlocksStep)
188
    ThreadsList=range(ThreadsBegin,ThreadsEnd+ThreadsStep,ThreadsStep)
189
    
190
    ExploredJobs=numpy.array([]).astype(numpy.uint32)
191
    ExploredBlocks=numpy.array([]).astype(numpy.uint32)
192
    ExploredThreads=numpy.array([]).astype(numpy.uint32)
193
    avgD=numpy.array([]).astype(numpy.float32)
194
    medD=numpy.array([]).astype(numpy.float32)
195
    stdD=numpy.array([]).astype(numpy.float32)
196
    minD=numpy.array([]).astype(numpy.float32)
197
    maxD=numpy.array([]).astype(numpy.float32)
198
    avgR=numpy.array([]).astype(numpy.float32)
199
    medR=numpy.array([]).astype(numpy.float32)
200
    stdR=numpy.array([]).astype(numpy.float32)
201
    minR=numpy.array([]).astype(numpy.float32)
202
    maxR=numpy.array([]).astype(numpy.float32)
203

    
204
    for Blocks,Threads in itertools.product(BlocksList,ThreadsList):
205
        
206
        ExploredJobs=numpy.append(ExploredJobs,Blocks*Threads)
207
        ExploredBlocks=numpy.append(ExploredBlocks,Blocks)
208
        ExploredThreads=numpy.append(ExploredThreads,Threads)
209

    
210
        IterationsMP=Iterations/len(Devices)
211
        if Iterations%len(Devices)!=0:
212
            IterationsMP+=1
213
        MyThreads=[]
214

    
215
        if OutMetrology: 
216
            DurationItem=numpy.array([]).astype(numpy.float32)
217
            Duration=numpy.array([]).astype(numpy.float32)
218
            Rate=numpy.array([]).astype(numpy.float32)
219
            for i in xrange(Redo):
220
                time_start=time.time()
221

    
222
                for Device in Devices:
223
                    InputCL={}
224
                    InputCL['Iterations']=IterationsMP
225
                    InputCL['Steps']=1
226
                    InputCL['Blocks']=Blocks
227
                    InputCL['Threads']=Threads
228
                    InputCL['Device']=Device
229
                    InputCL['RNG']=RNG
230
                    InputCL['ValueType']=ValueType
231
                    if GpuStyle=='CUDA':
232
                        try:
233
                            MyThread=threadWithReturn(target=MetropolisCUDA, args=(InputCL,))
234
                        except:
235
                            print("Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads))
236
                    elif GpuStyle=='OpenCL':
237
                        try:
238
                            MyThread=threadWithReturn(target=MetropolisOpenCL, args=(InputCL,))
239
                        except:
240
                            print("Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads)            )
241
                    
242
                    print("Start on #%i device..." % Device)
243
                    MyThread.start()
244
                    MyThreads.append(MyThread)
245

    
246
                NewIterations=0
247
                Inside=0
248
                for MyThread in MyThreads:
249
                    OutputCL=MyThread.join()
250
                    NewIterations+=OutputCL['NewIterations']
251
                    Inside+=OutputCL['Inside']
252
                print("Pi equals:",4./NewIterations*Inside)
253

    
254
                Duration=numpy.append(Duration,time.time()-time_start)
255
                Rate=numpy.append(Rate,NewIterations/Duration[-1])
256
                
257
        else:
258
            time_start=time.time()
259
            for Device in Devices:
260
                InputCL={}
261
                InputCL['Iterations']=IterationsMP
262
                InputCL['Steps']=Redo
263
                InputCL['Blocks']=Blocks
264
                InputCL['Threads']=Threads
265
                InputCL['Device']=Device
266
                InputCL['RNG']=RNG
267
                InputCL['ValueType']=ValueType
268
                if GpuStyle=='CUDA':
269
                    try:
270
                        MyThread=threadWithReturn(target=MetropolisCUDA, args=(InputCL,))
271
                    except:
272
                        print("Problem with (%i,%i) // computations on Cuda" % (Blocks,Threads))
273
                elif GpuStyle=='OpenCL':
274
                    try:
275
                        MyThread=threadWithReturn(target=MetropolisOpenCL, args=(InputCL,))
276
                    except:
277
                        print("Problem with (%i,%i) // computations on OpenCL" % (Blocks,Threads))
278
                    
279
                print("Start on #%i device..." % Device)
280
                MyThread.start()
281
                MyThreads.append(MyThread)
282

    
283
            NewIterations=0
284
            Inside=0
285
            for MyThread in MyThreads:
286
                OutputCL=MyThread.join()
287
                NewIterations+=OutputCL['NewIterations']
288
                Inside+=OutputCL['Inside']
289
            Duration=time.time()-time_start
290
            print("Pi equals:",4./NewIterations*Inside)
291
            Rate=1./Duration*NewIterations
292
            
293
        avgD=numpy.append(avgD,numpy.average(Duration))
294
        medD=numpy.append(medD,numpy.median(Duration))
295
        stdD=numpy.append(stdD,numpy.std(Duration))
296
        minD=numpy.append(minD,numpy.min(Duration))
297
        maxD=numpy.append(maxD,numpy.max(Duration))
298
        avgR=numpy.append(avgR,numpy.average(Rate))
299
        medR=numpy.append(medR,numpy.median(Rate))
300
        stdR=numpy.append(stdR,numpy.std(Rate))
301
        minR=numpy.append(minR,numpy.min(Rate))
302
        maxR=numpy.append(maxR,numpy.max(Rate))
303

    
304
        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]))
305
        
306
        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))
307
        ToSave=[ ExploredBlocks,ExploredThreads,avgD,medD,stdD,minD,maxD,avgR,medR,stdR,minR,maxR ]
308
        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')
309

    
310
    if Fit:
311
        FitAndPrint(ExploredJobs,median,Curves)