root / ETSN / MyDFT_8.py @ 277
Historique | Voir | Annoter | Télécharger (11,29 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,Device): |
141 |
# import pycuda.autoinit
|
142 |
import pycuda.driver as drv |
143 |
from pycuda.compiler import SourceModule |
144 |
|
145 |
try:
|
146 |
# For PyCUDA import
|
147 |
import pycuda.driver as cuda |
148 |
from pycuda.compiler import SourceModule |
149 |
|
150 |
cuda.init() |
151 |
for Id in range(cuda.Device.count()): |
152 |
if Id==Device:
|
153 |
XPU=cuda.Device(Id) |
154 |
print("GPU selected %s" % XPU.name())
|
155 |
print
|
156 |
|
157 |
except ImportError: |
158 |
print("Platform does not seem to support CUDA")
|
159 |
|
160 |
Context=XPU.make_context() |
161 |
|
162 |
TimeIn=time.time() |
163 |
mod = SourceModule("""
|
164 |
|
165 |
#define PI 3.141592653589793
|
166 |
|
167 |
__global__ void MyDFT(float *A_g, float *B_g, const float *a_g,const float *b_g)
|
168 |
{
|
169 |
const int gid = blockIdx.x;
|
170 |
uint size = gridDim.x;
|
171 |
float A=0.,B=0.;
|
172 |
for (uint i=0; i<size;i++)
|
173 |
{
|
174 |
A+=a_g[i]*cos(2.*PI*(float)(gid*i)/(float)size)-b_g[i]*sin(2.*PI*(float)(gid*i)/(float)size);
|
175 |
B+=a_g[i]*sin(2.*PI*(float)(gid*i)/(float)size)+b_g[i]*cos(2.*PI*(float)(gid*i)/(float)size);
|
176 |
}
|
177 |
A_g[gid]=A;
|
178 |
B_g[gid]=B;
|
179 |
}
|
180 |
|
181 |
""")
|
182 |
Elapsed=time.time()-TimeIn |
183 |
print("Definition of kernel : %.3f" % Elapsed)
|
184 |
|
185 |
TimeIn=time.time() |
186 |
MyDFT = mod.get_function("MyDFT")
|
187 |
Elapsed=time.time()-TimeIn |
188 |
print("Synthesis of kernel : %.3f" % Elapsed)
|
189 |
|
190 |
TimeIn=time.time() |
191 |
A_np = np.zeros_like(a_np) |
192 |
B_np = np.zeros_like(a_np) |
193 |
Elapsed=time.time()-TimeIn |
194 |
print("Allocation on Host for results : %.3f" % Elapsed)
|
195 |
|
196 |
TimeIn=time.time() |
197 |
MyDFT(drv.Out(A_np), drv.Out(B_np), drv.In(a_np), drv.In(b_np), |
198 |
block=(1,1,1), grid=(a_np.size,1)) |
199 |
Elapsed=time.time()-TimeIn |
200 |
print("Execution of kernel : %.3f" % Elapsed)
|
201 |
|
202 |
Context.pop() |
203 |
Context.detach() |
204 |
|
205 |
return(A_np,B_np)
|
206 |
|
207 |
import sys |
208 |
import time |
209 |
|
210 |
if __name__=='__main__': |
211 |
|
212 |
GpuStyle='OpenCL'
|
213 |
SIZE=1024
|
214 |
Device=0
|
215 |
|
216 |
import getopt |
217 |
|
218 |
HowToUse='%s -g <CUDA/OpenCL> -s <SizeOfVector> -d <DeviceId>'
|
219 |
|
220 |
try:
|
221 |
opts, args = getopt.getopt(sys.argv[1:],"hg:s:d:",["gpustyle=","size=","device="]) |
222 |
except getopt.GetoptError:
|
223 |
print(HowToUse % sys.argv[0])
|
224 |
sys.exit(2)
|
225 |
|
226 |
# List of Devices
|
227 |
Devices=[] |
228 |
Alu={} |
229 |
|
230 |
for opt, arg in opts: |
231 |
if opt == '-h': |
232 |
print(HowToUse % sys.argv[0])
|
233 |
|
234 |
print("\nInformations about devices detected under OpenCL API:")
|
235 |
# For PyOpenCL import
|
236 |
try:
|
237 |
import pyopencl as cl |
238 |
Id=0
|
239 |
for platform in cl.get_platforms(): |
240 |
for device in platform.get_devices(): |
241 |
#deviceType=cl.device_type.to_string(device.type)
|
242 |
deviceType="xPU"
|
243 |
print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip(),deviceType,device.name.lstrip()))
|
244 |
Id=Id+1
|
245 |
|
246 |
except:
|
247 |
print("Your platform does not seem to support OpenCL")
|
248 |
|
249 |
print("\nInformations about devices detected under CUDA API:")
|
250 |
# For PyCUDA import
|
251 |
try:
|
252 |
import pycuda.driver as cuda |
253 |
cuda.init() |
254 |
for Id in range(cuda.Device.count()): |
255 |
device=cuda.Device(Id) |
256 |
print("Device #%i of type GPU : %s" % (Id,device.name()))
|
257 |
print
|
258 |
except:
|
259 |
print("Your platform does not seem to support CUDA")
|
260 |
|
261 |
sys.exit() |
262 |
|
263 |
elif opt in ("-d", "--device"): |
264 |
Device=int(arg)
|
265 |
elif opt in ("-g", "--gpustyle"): |
266 |
GpuStyle = arg |
267 |
elif opt in ("-s", "--size"): |
268 |
SIZE = int(arg)
|
269 |
|
270 |
print("Device Selection : %i" % Device)
|
271 |
print("GpuStyle used : %s" % GpuStyle)
|
272 |
print("Size of complex vector : %i" % SIZE)
|
273 |
|
274 |
if GpuStyle=='CUDA': |
275 |
try:
|
276 |
# For PyCUDA import
|
277 |
import pycuda.driver as cuda |
278 |
|
279 |
cuda.init() |
280 |
for Id in range(cuda.Device.count()): |
281 |
device=cuda.Device(Id) |
282 |
print("Device #%i of type GPU : %s" % (Id,device.name()))
|
283 |
if Id in Devices: |
284 |
Alu[Id]='GPU'
|
285 |
|
286 |
except ImportError: |
287 |
print("Platform does not seem to support CUDA")
|
288 |
|
289 |
if GpuStyle=='OpenCL': |
290 |
try:
|
291 |
# For PyOpenCL import
|
292 |
import pyopencl as cl |
293 |
Id=0
|
294 |
for platform in cl.get_platforms(): |
295 |
for device in platform.get_devices(): |
296 |
#deviceType=cl.device_type.to_string(device.type)
|
297 |
deviceType="xPU"
|
298 |
print("Device #%i from %s of type %s : %s" % (Id,platform.vendor.lstrip().rstrip(),deviceType,device.name.lstrip().rstrip()))
|
299 |
|
300 |
if Id in Devices: |
301 |
# Set the Alu as detected Device Type
|
302 |
Alu[Id]=deviceType |
303 |
Id=Id+1
|
304 |
except ImportError: |
305 |
print("Platform does not seem to support OpenCL")
|
306 |
|
307 |
|
308 |
|
309 |
a_np = np.ones(SIZE).astype(np.float32) |
310 |
b_np = np.ones(SIZE).astype(np.float32) |
311 |
|
312 |
C_np = np.zeros(SIZE).astype(np.float32) |
313 |
D_np = np.zeros(SIZE).astype(np.float32) |
314 |
C_np[0] = np.float32(SIZE)
|
315 |
D_np[0] = np.float32(SIZE)
|
316 |
|
317 |
# # Native & Naive Implementation
|
318 |
# print("Performing naive implementation")
|
319 |
# TimeIn=time.time()
|
320 |
# c_np,d_np=MyDFT(a_np,b_np)
|
321 |
# NativeElapsed=time.time()-TimeIn
|
322 |
# NativeRate=int(SIZE/NativeElapsed)
|
323 |
# print("NativeRate: %i" % NativeRate)
|
324 |
# print("Precision: ",np.linalg.norm(c_np-C_np),np.linalg.norm(d_np-D_np))
|
325 |
|
326 |
# # Native & Numpy Implementation
|
327 |
# print("Performing Numpy implementation")
|
328 |
# TimeIn=time.time()
|
329 |
# e_np,f_np=NumpyDFT(a_np,b_np)
|
330 |
# NumpyElapsed=time.time()-TimeIn
|
331 |
# NumpyRate=int(SIZE/NumpyElapsed)
|
332 |
# print("NumpyRate: %i" % NumpyRate)
|
333 |
# print("Precision: ",np.linalg.norm(e_np-C_np),np.linalg.norm(f_np-D_np))
|
334 |
|
335 |
# # Native & Numba Implementation
|
336 |
# print("Performing Numba implementation")
|
337 |
# TimeIn=time.time()
|
338 |
# g_np,h_np=NumbaDFT(a_np,b_np)
|
339 |
# NumbaElapsed=time.time()-TimeIn
|
340 |
# NumbaRate=int(SIZE/NumbaElapsed)
|
341 |
# print("NumbaRate: %i" % NumbaRate)
|
342 |
# print("Precision: ",np.linalg.norm(g_np-C_np),np.linalg.norm(h_np-D_np))
|
343 |
|
344 |
# OpenCL Implementation
|
345 |
if GpuStyle=='OpenCL': |
346 |
print("Performing OpenCL implementation")
|
347 |
TimeIn=time.time() |
348 |
i_np,j_np=OpenCLDFT(a_np,b_np,Device) |
349 |
OpenCLElapsed=time.time()-TimeIn |
350 |
OpenCLRate=int(SIZE/OpenCLElapsed)
|
351 |
print("OpenCLRate: %i" % OpenCLRate)
|
352 |
print("Precision: ",np.linalg.norm(i_np-C_np),
|
353 |
np.linalg.norm(j_np-D_np)) |
354 |
|
355 |
# CUDA Implementation
|
356 |
if GpuStyle=='CUDA': |
357 |
print("Performing CUDA implementation")
|
358 |
TimeIn=time.time() |
359 |
k_np,l_np=CUDADFT(a_np,b_np,Device) |
360 |
CUDAElapsed=time.time()-TimeIn |
361 |
CUDARate=int(SIZE/CUDAElapsed)
|
362 |
print("CUDARate: %i" % CUDARate)
|
363 |
print("Precision: ",np.linalg.norm(k_np-C_np),
|
364 |
np.linalg.norm(l_np-D_np)) |
365 |
|