Skip to content

Commit 54a0cab

Browse files
committed
Adding interop functionality with pyopencl
1 parent b5d5c87 commit 54a0cab

File tree

1 file changed

+73
-1
lines changed

1 file changed

+73
-1
lines changed

arrayfire/interop.py

Lines changed: 73 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
"""
1818

1919
from .array import *
20-
from .device import lock_array
20+
from .device import *
2121

2222
try:
2323
import numpy as np
@@ -117,3 +117,75 @@ def pycuda_to_af_array(pycu_arr):
117117
return pycuda_to_af_array(pycu_arr.copy())
118118
except:
119119
AF_PYCUDA_FOUND=False
120+
121+
try:
122+
import pyopencl.array as CLArray
123+
from .opencl import add_device_context as _add_device_context
124+
from .opencl import set_device_context as _set_device_context
125+
from .opencl import get_device_id as _get_device_id
126+
from .opencl import get_context as _get_context
127+
AF_PYOPENCL_FOUND=True
128+
129+
def pyopencl_to_af_array(pycl_arr):
130+
"""
131+
Convert pyopencl.gpuarray to arrayfire.Array
132+
133+
Parameters
134+
-----------
135+
pycl_arr : pyopencl.Array()
136+
137+
Returns
138+
----------
139+
af_arr : arrayfire.Array()
140+
"""
141+
142+
ctx = pycl_arr.context.int_ptr
143+
que = pycl_arr.queue.int_ptr
144+
dev = pycl_arr.queue.device.int_ptr
145+
146+
dev_idx = None
147+
ctx_idx = None
148+
for n in range(get_device_count()):
149+
set_device(n)
150+
dev_idx = _get_device_id()
151+
ctx_idx = _get_context()
152+
if (dev_idx == dev and ctx_idx == ctx):
153+
break
154+
155+
if (dev_idx == None or ctx_idx == None or
156+
dev_idx != dev or ctx_idx != ctx):
157+
_add_device_context(dev, ctx, que)
158+
_set_device_context(dev, ctx)
159+
160+
in_ptr = pycl_arr.base_data.int_ptr
161+
in_shape = pycl_arr.shape
162+
in_dtype = pycl_arr.dtype.char
163+
164+
if (pycl_arr.flags.f_contiguous):
165+
res = Array(in_ptr, in_shape, in_dtype, is_device=True)
166+
lock_array(res)
167+
return res
168+
elif (pycl_arr.flags.c_contiguous):
169+
if pycl_arr.ndim == 1:
170+
return Array(in_ptr, in_shape, in_dtype, is_device=True)
171+
elif pycl_arr.ndim == 2:
172+
shape = (in_shape[1], in_shape[0])
173+
res = Array(in_ptr, shape, in_dtype, is_device=True)
174+
lock_array(res)
175+
return reorder(res, 1, 0)
176+
elif pycl_arr.ndim == 3:
177+
shape = (in_shape[2], in_shape[1], in_shape[0])
178+
res = Array(in_ptr, shape, in_dtype, is_device=True)
179+
lock_array(res)
180+
return reorder(res, 2, 1, 0)
181+
elif pycl_arr.ndim == 4:
182+
shape = (in_shape[3], in_shape[2], in_shape[1], in_shape[0])
183+
res = Array(in_ptr, shape, in_dtype, is_device=True)
184+
lock_array(res)
185+
return reorder(res, 3, 2, 1, 0)
186+
else:
187+
raise RuntimeError("Unsupported ndim")
188+
else:
189+
return pyopencl_to_af_array(pycl_arr.copy())
190+
except:
191+
AF_PYOPENCL_FOUND=False

0 commit comments

Comments
 (0)