Skip to content

Commit 81db5e5

Browse files
Implement usm_ndarray.__arrray__ method
The property raises TypeError informing user that implicit conversions from usm_ndarray to numpy.ndarray are not permitted. Explicit conversion using `dpctl.tensor.asnumpy` is advised. Disallowing implicit conversion prevents `np.asarray(usm_ar)` from creating an array of 0D usm_ndarray instances, because using it is very costly due to multitude of short-array transfers from GPU to host.
1 parent 0f3536b commit 81db5e5

File tree

1 file changed

+8
-0
lines changed

1 file changed

+8
-0
lines changed

dpctl/tensor/_usmarray.pyx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1552,6 +1552,14 @@ cdef class usm_ndarray:
15521552
def __repr__(self):
15531553
return usm_ndarray_repr(self)
15541554

1555+
def __array__(self, dtype=None, copy=None):
1556+
"NumPy array protocol"
1557+
raise TypeError(
1558+
"Implicit conversion to a NumPy array is not allowed. "
1559+
"Use `dpctl.tensor.asnumpy` to copy data from this "
1560+
"`dpctl.tensor.usm_ndarray` instance to NumPy array"
1561+
)
1562+
15551563

15561564
cdef usm_ndarray _real_view(usm_ndarray ary):
15571565
"""

0 commit comments

Comments
 (0)