Statistiques
| Révision :

root / ETSN / MyDFT_8.py @ 274

Historique | Voir | Annoter | Télécharger (11,26 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
    a_g.release()
132
    b_g.release()
133
    A_g.release()
134
    B_g.release()
135
    
136
    return(A_ocl,B_ocl)
137

    
138
# CUDA Silly complete operation
139
def CUDADFT(a_np,b_np,Device):
140
    # import pycuda.autoinit
141
    import pycuda.driver as drv
142
    from pycuda.compiler import SourceModule
143
    
144
    try:
145
        # For PyCUDA import
146
        import pycuda.driver as cuda
147
        from pycuda.compiler import SourceModule
148
        
149
        cuda.init()
150
        for Id in range(cuda.Device.count()):
151
            if Id==Device:
152
                XPU=cuda.Device(Id)
153
                print("GPU selected %s" % XPU.name())
154
        print
155

    
156
    except ImportError:
157
        print("Platform does not seem to support CUDA")
158

    
159
    Context=XPU.make_context()
160
        
161
    TimeIn=time.time()
162
    mod = SourceModule("""
163

164
#define PI 3.141592653589793
165

166
__global__ void MyDFT(float *A_g, float *B_g, const float *a_g,const float *b_g)
167
{
168
  const int gid = blockIdx.x;
169
  uint size = gridDim.x;
170
  float A=0.,B=0.;
171
  for (uint i=0; i<size;i++) 
172
  {
173
     A+=a_g[i]*cos(2.*PI*(float)(gid*i)/(float)size)-b_g[i]*sin(2.*PI*(float)(gid*i)/(float)size);
174
     B+=a_g[i]*sin(2.*PI*(float)(gid*i)/(float)size)+b_g[i]*cos(2.*PI*(float)(gid*i)/(float)size);
175
  }
176
  A_g[gid]=A;
177
  B_g[gid]=B;
178
}
179

180
""")
181
    Elapsed=time.time()-TimeIn
182
    print("Definition of kernel : %.3f" % Elapsed)
183

    
184
    TimeIn=time.time()
185
    MyDFT = mod.get_function("MyDFT")
186
    Elapsed=time.time()-TimeIn
187
    print("Synthesis of kernel : %.3f" % Elapsed)
188

    
189
    TimeIn=time.time()
190
    A_np = np.zeros_like(a_np)
191
    B_np = np.zeros_like(a_np)
192
    Elapsed=time.time()-TimeIn
193
    print("Allocation on Host for results : %.3f" % Elapsed)
194

    
195
    TimeIn=time.time()
196
    MyDFT(drv.Out(A_np), drv.Out(B_np), drv.In(a_np), drv.In(b_np),
197
          block=(1,1,1), grid=(a_np.size,1))
198
    Elapsed=time.time()-TimeIn
199
    print("Execution of kernel : %.3f" % Elapsed)
200

    
201
    Context.pop()
202
    Context.detach()
203
    
204
    return(A_np,B_np)
205

    
206
import sys
207
import time
208

    
209
if __name__=='__main__':
210

    
211
    GpuStyle='OpenCL'
212
    SIZE=1024
213
    Device=0
214

    
215
    import getopt
216

    
217
    HowToUse='%s -g <CUDA/OpenCL> -s <SizeOfVector> -d <DeviceId>'
218
    
219
    try:
220
        opts, args = getopt.getopt(sys.argv[1:],"hg:s:d:",["gpustyle=","size=","device="])
221
    except getopt.GetoptError:
222
        print(HowToUse % sys.argv[0])
223
        sys.exit(2)
224

    
225
    # List of Devices
226
    Devices=[]
227
    Alu={}
228
        
229
    for opt, arg in opts:
230
        if opt == '-h':
231
            print(HowToUse % sys.argv[0])
232

    
233
            print("\nInformations about devices detected under OpenCL API:")
234
            # For PyOpenCL import
235
            try:
236
                import pyopencl as cl
237
                Id=0
238
                for platform in cl.get_platforms():
239
                    for device in platform.get_devices():
240
                        #deviceType=cl.device_type.to_string(device.type)
241
                        deviceType="xPU"
242
                        print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
243
                        Id=Id+1
244

    
245
            except:
246
                print("Your platform does not seem to support OpenCL")
247

    
248
            print("\nInformations about devices detected under CUDA API:")
249
            # For PyCUDA import
250
            try:
251
                import pycuda.driver as cuda
252
                cuda.init()
253
                for Id in range(cuda.Device.count()):
254
                    device=cuda.Device(Id)
255
                    print("Device #%i of type GPU : %s" % (Id,device.name()))
256
                print
257
            except:
258
                print("Your platform does not seem to support CUDA")
259
        
260
            sys.exit()
261
        
262
        elif opt in ("-d", "--device"):
263
            Device=int(arg)
264
        elif opt in ("-g", "--gpustyle"):
265
            GpuStyle = arg
266
        elif opt in ("-s", "--size"):
267
            SIZE = int(arg)
268

    
269
    print("Device Selection : %i" % Device)
270
    print("GpuStyle used : %s" % GpuStyle)
271
    print("Size of complex vector : %i" % SIZE)
272

    
273
    if GpuStyle=='CUDA':
274
        try:
275
            # For PyCUDA import
276
            import pycuda.driver as cuda
277
            
278
            cuda.init()
279
            for Id in range(cuda.Device.count()):
280
                device=cuda.Device(Id)
281
                print("Device #%i of type GPU : %s" % (Id,device.name()))
282
                if Id in Devices:
283
                    Alu[Id]='GPU'
284
            
285
        except ImportError:
286
            print("Platform does not seem to support CUDA")
287

    
288
    if GpuStyle=='OpenCL':
289
        try:
290
            # For PyOpenCL import
291
            import pyopencl as cl
292
            Id=0
293
            for platform in cl.get_platforms():
294
                for device in platform.get_devices():
295
                    #deviceType=cl.device_type.to_string(device.type)
296
                    deviceType="xPU"
297
                    print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip()))
298

    
299
                    if Id in Devices:
300
                    # Set the Alu as detected Device Type
301
                        Alu[Id]=deviceType
302
                    Id=Id+1
303
        except ImportError:
304
            print("Platform does not seem to support OpenCL")
305

    
306
    
307
        
308
    a_np = np.ones(SIZE).astype(np.float32)
309
    b_np = np.ones(SIZE).astype(np.float32)
310

    
311
    C_np = np.zeros(SIZE).astype(np.float32)
312
    D_np = np.zeros(SIZE).astype(np.float32)
313
    C_np[0] = np.float32(SIZE)
314
    D_np[0] = np.float32(SIZE)
315
    
316
    # # Native & Naive Implementation
317
    # print("Performing naive implementation")
318
    # TimeIn=time.time()
319
    # c_np,d_np=MyDFT(a_np,b_np)
320
    # NativeElapsed=time.time()-TimeIn
321
    # NativeRate=int(SIZE/NativeElapsed)
322
    # print("NativeRate: %i" % NativeRate)
323
    # print("Precision: ",np.linalg.norm(c_np-C_np),np.linalg.norm(d_np-D_np)) 
324

    
325
    # # Native & Numpy Implementation
326
    # print("Performing Numpy implementation")
327
    # TimeIn=time.time()
328
    # e_np,f_np=NumpyDFT(a_np,b_np)
329
    # NumpyElapsed=time.time()-TimeIn
330
    # NumpyRate=int(SIZE/NumpyElapsed)
331
    # print("NumpyRate: %i" % NumpyRate)
332
    # print("Precision: ",np.linalg.norm(e_np-C_np),np.linalg.norm(f_np-D_np)) 
333
        
334
    # # Native & Numba Implementation
335
    # print("Performing Numba implementation")
336
    # TimeIn=time.time()
337
    # g_np,h_np=NumbaDFT(a_np,b_np)
338
    # NumbaElapsed=time.time()-TimeIn
339
    # NumbaRate=int(SIZE/NumbaElapsed)
340
    # print("NumbaRate: %i" % NumbaRate)
341
    # print("Precision: ",np.linalg.norm(g_np-C_np),np.linalg.norm(h_np-D_np)) 
342
    
343
    # OpenCL Implementation
344
    if GpuStyle=='OpenCL':
345
        print("Performing OpenCL implementation")
346
        TimeIn=time.time()
347
        i_np,j_np=OpenCLDFT(a_np,b_np,Device)
348
        OpenCLElapsed=time.time()-TimeIn
349
        OpenCLRate=int(SIZE/OpenCLElapsed)
350
        print("OpenCLRate: %i" % OpenCLRate)
351
        print("Precision: ",np.linalg.norm(i_np-C_np),
352
              np.linalg.norm(j_np-D_np)) 
353
    
354
    # CUDA Implementation
355
    if GpuStyle=='CUDA':
356
        print("Performing CUDA implementation")
357
        TimeIn=time.time()
358
        k_np,l_np=CUDADFT(a_np,b_np,Device)
359
        CUDAElapsed=time.time()-TimeIn
360
        CUDARate=int(SIZE/CUDAElapsed)
361
        print("CUDARate: %i" % CUDARate)
362
        print("Precision: ",np.linalg.norm(k_np-C_np),
363
              np.linalg.norm(l_np-D_np)) 
364