|
| 1 | +import pyopencl as cl |
| 2 | +import pyopencl.array as cl_array |
| 3 | +import numpy as np |
| 4 | +import numpy.linalg as la |
| 5 | + |
| 6 | +a = np.random.rand(500).astype(np.float32) |
| 7 | +b = np.random.rand(500).astype(np.float32) |
| 8 | + |
| 9 | + |
| 10 | +class SVMAllocator: |
| 11 | + def __init__(self, ctx, flags, alignment): |
| 12 | + self._context = ctx |
| 13 | + self._flags = flags |
| 14 | + self._alignment = alignment |
| 15 | + |
| 16 | + def __call__(self, nbytes): |
| 17 | + return cl.SVM(cl.svm_empty( |
| 18 | + ctx, self._flags, (nbytes,), np.int8, "C", self._alignment)) |
| 19 | + |
| 20 | + |
| 21 | +ctx = cl.create_some_context() |
| 22 | +queue = cl.CommandQueue(ctx) |
| 23 | + |
| 24 | +alloc = SVMAllocator(ctx, |
| 25 | + cl.svm_mem_flags.READ_WRITE | cl.svm_mem_flags.SVM_FINE_GRAIN_BUFFER, |
| 26 | + 0) |
| 27 | + |
| 28 | +a_dev = cl_array.to_device(queue, a, allocator=alloc) |
| 29 | +print("A_DEV", a_dev.data.mem.nbytes, a_dev.data.mem.__array_interface__) |
| 30 | +b_dev = cl_array.to_device(queue, b, allocator=alloc) |
| 31 | +dest_dev = cl_array.empty_like(a_dev) |
| 32 | +print("DEST", dest_dev.data.mem.__array_interface__) |
| 33 | + |
| 34 | +prg = cl.Program(ctx, """ |
| 35 | + __kernel void sum(__global const float *a, |
| 36 | + __global const float *b, __global float *c) |
| 37 | + { |
| 38 | + int gid = get_global_id(0); |
| 39 | + c[gid] = a[gid] + b[gid]; |
| 40 | + } |
| 41 | + """).build() |
| 42 | + |
| 43 | +knl = prg.sum # Use this Kernel object for repeated calls |
| 44 | +knl(queue, a.shape, None, a_dev.data, b_dev.data, dest_dev.data) |
| 45 | + |
| 46 | +# PROBLEM: numpy frees the temporary out of (a_dev+b_dev) before |
| 47 | +# we're done with it |
| 48 | +diff = (dest_dev - (a_dev+b_dev)).get() |
| 49 | +np.set_printoptions(linewidth=400) |
| 50 | +print(dest_dev) |
| 51 | +print((a_dev+b_dev).get()) |
| 52 | +print(diff) |
| 53 | +print(la.norm(diff)) |
| 54 | +print("A_DEV", a_dev.data.mem.__array_interface__) |
0 commit comments