Statistiques
| Révision :

root / ETSN / MyDFT_7.py @ 275

Historique | Voir | Annoter | Télécharger (10,74 ko)

1
#!/usr/bin/env python3
2

    
3
import numpy as np
4
import pyopencl as cl
5
from numpy import pi,cos,sin
6

    
7
# Naive Discrete Fourier Transform
8
def MyDFT(x,y):
9
    size=x.shape[0]
10
    X=np.zeros(size).astype(np.float32)
11
    Y=np.zeros(size).astype(np.float32)
12
    for i in range(size):
13
        for j in range(size):
14
            X[i]=X[i]+x[j]*cos(2.*pi*i*j/size)-y[j]*sin(2.*pi*i*j/size)
15
            Y[i]=Y[i]+x[j]*sin(2.*pi*i*j/size)+y[j]*cos(2.*pi*i*j/size)
16
    return(X,Y)
17

    
18
# Numpy Discrete Fourier Transform
19
def NumpyDFT(x,y):
20
    size=x.shape[0]
21
    X=np.zeros(size).astype(np.float32)
22
    Y=np.zeros(size).astype(np.float32)
23
    nj=np.multiply(2.0*np.pi/size,np.arange(size)).astype(np.float32)
24
    for i in range(size):
25
        X[i]=np.sum(np.subtract(np.multiply(np.cos(i*nj),x),np.multiply(np.sin(i*nj),y)))
26
        Y[i]=np.sum(np.add(np.multiply(np.sin(i*nj),x),np.multiply(np.cos(i*nj),y)))
27
    return(X,Y)
28

    
29
# Numba Discrete Fourier Transform
30
import numba
31
@numba.njit(parallel=True)
32
def NumbaDFT(x,y):
33
    size=x.shape[0]
34
    X=np.zeros(size).astype(np.float32)
35
    Y=np.zeros(size).astype(np.float32)
36
    nj=np.multiply(2.0*np.pi/size,np.arange(size)).astype(np.float32)
37
    for i in numba.prange(size):
38
        X[i]=np.sum(np.subtract(np.multiply(np.cos(i*nj),x),np.multiply(np.sin(i*nj),y)))
39
        Y[i]=np.sum(np.add(np.multiply(np.sin(i*nj),x),np.multiply(np.cos(i*nj),y)))
40
    return(X,Y)
41

    
42
# OpenCL complete operation
43
def OpenCLDFT(a_np,b_np,Device):
44

    
45
    Id=0
46
    HasXPU=False
47
    for platform in cl.get_platforms():
48
        for device in platform.get_devices():
49
            if Id==Device:
50
                XPU=device
51
                print("CPU/GPU selected: ",device.name.lstrip())
52
                HasXPU=True
53
            Id+=1
54
            # print(Id)
55

    
56
    if HasXPU==False:
57
        print("No XPU #%i found in all of %i devices, sorry..." % (Device,Id-1))
58
        sys.exit()           
59

    
60
    try:
61
        ctx = cl.Context(devices=[XPU])
62
        queue = cl.CommandQueue(ctx,properties=cl.command_queue_properties.PROFILING_ENABLE)
63
    except:
64
        print("Crash during context creation")
65

    
66
    TimeIn=time.time()
67
    # Copy from Host to Device using pointers
68
    mf = cl.mem_flags
69
    a_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=a_np)
70
    b_g = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=b_np)
71
    Elapsed=time.time()-TimeIn
72
    print("Copy from Host 2 Device : %.3f" % Elapsed)
73

    
74
    TimeIn=time.time()
75
    # Definition of kernel under OpenCL
76
    prg = cl.Program(ctx, """
77

78
#define PI 3.141592653589793
79

80
__kernel void MyDFT(
81
    __global const float *a_g, __global const float *b_g, __global float *A_g, __global float *B_g)
82
{
83
  int gid = get_global_id(0);
84
  uint size = get_global_size(0);
85
  float A=0.,B=0.;
86
  for (uint i=0; i<size;i++) 
87
  {
88
     A+=a_g[i]*cos(2.*PI*(float)(gid*i)/(float)size)-b_g[i]*sin(2.*PI*(float)(gid*i)/(float)size);
89
     B+=a_g[i]*sin(2.*PI*(float)(gid*i)/(float)size)+b_g[i]*cos(2.*PI*(float)(gid*i)/(float)size);
90
  }
91
  A_g[gid]=A;
92
  B_g[gid]=B;
93
}
94
""").build()
95
    Elapsed=time.time()-TimeIn
96
    print("Building kernels : %.3f" % Elapsed)
97
    
98
    TimeIn=time.time()
99
    # Memory allocation on Device for result
100
    A_ocl = np.empty_like(a_np)
101
    B_ocl = np.empty_like(a_np)
102
    Elapsed=time.time()-TimeIn
103
    print("Allocation on Host for results : %.3f" % Elapsed)
104

    
105
    A_g = cl.Buffer(ctx, mf.WRITE_ONLY, A_ocl.nbytes)
106
    B_g = cl.Buffer(ctx, mf.WRITE_ONLY, B_ocl.nbytes)
107
    Elapsed=time.time()-TimeIn
108
    print("Allocation on Device for results : %.3f" % Elapsed)
109

    
110
    TimeIn=time.time()
111
    # Synthesis of function "sillysum" inside Kernel Sources
112
    knl = prg.MyDFT  # Use this Kernel object for repeated calls
113
    Elapsed=time.time()-TimeIn
114
    print("Synthesis of kernel : %.3f" % Elapsed)
115

    
116
    TimeIn=time.time()
117
    # Call of kernel previously defined 
118
    CallCL=knl(queue, a_np.shape, None, a_g, b_g, A_g, B_g)
119
    # 
120
    CallCL.wait()
121
    Elapsed=time.time()-TimeIn
122
    print("Execution of kernel : %.3f" % Elapsed)
123

    
124
    TimeIn=time.time()
125
    # Copy from Device to Host
126
    cl.enqueue_copy(queue, A_ocl, A_g)
127
    cl.enqueue_copy(queue, B_ocl, B_g)
128
    Elapsed=time.time()-TimeIn
129
    print("Copy from Device 2 Host : %.3f" % Elapsed)
130

    
131
    # Liberation of memory
132
    a_g.release()
133
    b_g.release()
134
    A_g.release()
135
    B_g.release()
136
    
137
    return(A_ocl,B_ocl)
138

    
139
# CUDA Silly complete operation
140
def CUDADFT(a_np,b_np):
141
    import pycuda.autoinit
142
    import pycuda.driver as drv
143

    
144
    from pycuda.compiler import SourceModule
145
    TimeIn=time.time()
146
    mod = SourceModule("""
147

148
#define PI 3.141592653589793
149

150
__global__ void MyDFT(float *A_g, float *B_g, const float *a_g,const float *b_g)
151
{
152
  const int gid = blockIdx.x;
153
  uint size = gridDim.x;
154
  float A=0.,B=0.;
155
  for (uint i=0; i<size;i++) 
156
  {
157
     A+=a_g[i]*cos(2.*PI*(float)(gid*i)/(float)size)-b_g[i]*sin(2.*PI*(float)(gid*i)/(float)size);
158
     B+=a_g[i]*sin(2.*PI*(float)(gid*i)/(float)size)+b_g[i]*cos(2.*PI*(float)(gid*i)/(float)size);
159
  }
160
  A_g[gid]=A;
161
  B_g[gid]=B;
162
}
163

164
""")
165
    Elapsed=time.time()-TimeIn
166
    print("Definition of kernel : %.3f" % Elapsed)
167

    
168
    TimeIn=time.time()
169
    MyDFT = mod.get_function("MyDFT")
170
    Elapsed=time.time()-TimeIn
171
    print("Synthesis of kernel : %.3f" % Elapsed)
172

    
173
    TimeIn=time.time()
174
    A_np = np.zeros_like(a_np)
175
    B_np = np.zeros_like(a_np)
176
    Elapsed=time.time()-TimeIn
177
    print("Allocation on Host for results : %.3f" % Elapsed)
178

    
179
    TimeIn=time.time()
180
    MyDFT(drv.Out(A_np), drv.Out(B_np), drv.In(a_np), drv.In(b_np),
181
          block=(1,1,1), grid=(a_np.size,1))
182
    Elapsed=time.time()-TimeIn
183
    print("Execution of kernel : %.3f" % Elapsed)
184
    return(A_np,B_np)
185

    
186
import sys
187
import time
188

    
189
if __name__=='__main__':
190

    
191
    GpuStyle='OpenCL'
192
    SIZE=1024
193
    Device=0
194

    
195
    import getopt
196

    
197
    HowToUse='%s -g <CUDA/OpenCL> -s <SizeOfVector> -d <DeviceId>'
198
    
199
    try:
200
        opts, args = getopt.getopt(sys.argv[1:],"hg:s:d:",["gpustyle=","size=","device="])
201
    except getopt.GetoptError:
202
        print(HowToUse % sys.argv[0])
203
        sys.exit(2)
204

    
205
    # List of Devices
206
    Devices=[]
207
    Alu={}
208
        
209
    for opt, arg in opts:
210
        if opt == '-h':
211
            print(HowToUse % sys.argv[0])
212

    
213
            print("\nInformations about devices detected under OpenCL API:")
214
            # For PyOpenCL import
215
            try:
216
                import pyopencl as cl
217
                Id=0
218
                for platform in cl.get_platforms():
219
                    for device in platform.get_devices():
220
                        #deviceType=cl.device_type.to_string(device.type)
221
                        deviceType="xPU"
222
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
223
                        Id=Id+1
224

    
225
            except:
226
                print("Your platform does not seem to support OpenCL")
227

    
228
            print("\nInformations about devices detected under CUDA API:")
229
            # For PyCUDA import
230
            try:
231
                import pycuda.driver as cuda
232
                cuda.init()
233
                for Id in range(cuda.Device.count()):
234
                    device=cuda.Device(Id)
235
                    print("Device #%i of type GPU : %s" % (Id,device.name()))
236
                print
237
            except:
238
                print("Your platform does not seem to support CUDA")
239
        
240
            sys.exit()
241
        
242
        elif opt in ("-d", "--device"):
243
            Device=int(arg)
244
        elif opt in ("-g", "--gpustyle"):
245
            GpuStyle = arg
246
        elif opt in ("-s", "--size"):
247
            SIZE = int(arg)
248

    
249
    print("Device Selection : %i" % Device)
250
    print("GpuStyle used : %s" % GpuStyle)
251
    print("Size of complex vector : %i" % SIZE)
252

    
253
    if GpuStyle=='CUDA':
254
        try:
255
            # For PyCUDA import
256
            import pycuda.driver as cuda
257
            
258
            cuda.init()
259
            for Id in range(cuda.Device.count()):
260
                device=cuda.Device(Id)
261
                print("Device #%i of type GPU : %s" % (Id,device.name()))
262
                if Id in Devices:
263
                    Alu[Id]='GPU'
264
            
265
        except ImportError:
266
            print("Platform does not seem to support CUDA")
267

    
268
    if GpuStyle=='OpenCL':
269
        try:
270
            # For PyOpenCL import
271
            import pyopencl as cl
272
            Id=0
273
            for platform in cl.get_platforms():
274
                for device in platform.get_devices():
275
                    #deviceType=cl.device_type.to_string(device.type)
276
                    deviceType="xPU"
277
                    print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip()))
278

    
279
                    if Id in Devices:
280
                    # Set the Alu as detected Device Type
281
                        Alu[Id]=deviceType
282
                    Id=Id+1
283
        except ImportError:
284
            print("Platform does not seem to support OpenCL")
285

    
286
    
287
        
288
    a_np = np.ones(SIZE).astype(np.float32)
289
    b_np = np.ones(SIZE).astype(np.float32)
290

    
291
    C_np = np.zeros(SIZE).astype(np.float32)
292
    D_np = np.zeros(SIZE).astype(np.float32)
293
    C_np[0] = np.float32(SIZE)
294
    D_np[0] = np.float32(SIZE)
295
    
296
    # # Native & Naive Implementation
297
    # print("Performing naive implementation")
298
    # TimeIn=time.time()
299
    # c_np,d_np=MyDFT(a_np,b_np)
300
    # NativeElapsed=time.time()-TimeIn
301
    # NativeRate=int(SIZE/NativeElapsed)
302
    # print("NativeRate: %i" % NativeRate)
303
    # print("Precision: ",np.linalg.norm(c_np-C_np),np.linalg.norm(d_np-D_np)) 
304

    
305
    # # Native & Numpy Implementation
306
    # print("Performing Numpy implementation")
307
    # TimeIn=time.time()
308
    # e_np,f_np=NumpyDFT(a_np,b_np)
309
    # NumpyElapsed=time.time()-TimeIn
310
    # NumpyRate=int(SIZE/NumpyElapsed)
311
    # print("NumpyRate: %i" % NumpyRate)
312
    # print("Precision: ",np.linalg.norm(e_np-C_np),np.linalg.norm(f_np-D_np)) 
313
        
314
    # # Native & Numba Implementation
315
    # print("Performing Numba implementation")
316
    # TimeIn=time.time()
317
    # g_np,h_np=NumbaDFT(a_np,b_np)
318
    # NumbaElapsed=time.time()-TimeIn
319
    # NumbaRate=int(SIZE/NumbaElapsed)
320
    # print("NumbaRate: %i" % NumbaRate)
321
    # print("Precision: ",np.linalg.norm(g_np-C_np),np.linalg.norm(h_np-D_np)) 
322
    
323
    # OpenCL Implementation
324
    if GpuStyle=='OpenCL':
325
        print("Performing OpenCL implementation")
326
        TimeIn=time.time()
327
        i_np,j_np=OpenCLDFT(a_np,b_np,Device)
328
        OpenCLElapsed=time.time()-TimeIn
329
        OpenCLRate=int(SIZE/OpenCLElapsed)
330
        print("OpenCLRate: %i" % OpenCLRate)
331
        print("Precision: ",np.linalg.norm(i_np-C_np),
332
              np.linalg.norm(j_np-D_np)) 
333
    
334
    # # CUDA Implementation
335
    # print("Performing CUDA implementation")
336
    # TimeIn=time.time()
337
    # k_np,l_np=CUDADFT(a_np,b_np)
338
    # CUDAElapsed=time.time()-TimeIn
339
    # CUDARate=int(SIZE/CUDAElapsed)
340
    # print("CUDARate: %i" % CUDARate)
341
    # print("Precision: ",np.linalg.norm(k_np-C_np),np.linalg.norm(l_np-D_np)) 
342