From 81db5e5e5b5cbe63d820f80c70f9781109beb6be Mon Sep 17 00:00:00 2001 From: Oleksandr Pavlyk <21087696+oleksandr-pavlyk@users.noreply.github.com> Date: Mon, 13 Jan 2025 11:00:53 -0600 Subject: [PATCH] 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. --- dpctl/tensor/_usmarray.pyx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/dpctl/tensor/_usmarray.pyx b/dpctl/tensor/_usmarray.pyx index f61651d4b3..150f0b3b65 100644 --- a/dpctl/tensor/_usmarray.pyx +++ b/dpctl/tensor/_usmarray.pyx @@ -1552,6 +1552,14 @@ cdef class usm_ndarray: def __repr__(self): return usm_ndarray_repr(self) + def __array__(self, dtype=None, copy=None): + "NumPy array protocol" + raise TypeError( + "Implicit conversion to a NumPy array is not allowed. " + "Use `dpctl.tensor.asnumpy` to copy data from this " + "`dpctl.tensor.usm_ndarray` instance to NumPy array" + ) + cdef usm_ndarray _real_view(usm_ndarray ary): """