Skip to content

Usm ndrray array protocol must raise #1964

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* Improved performance of `tensor.cumulative_sum`, `tensor.cumulative_prod`, `tensor.cumulative_logsumexp` as well as performance of boolean indexing [gh-1923](https://github.com/IntelPython/dpctl/pull/1923)
* Improved performance of `tensor.min`, `tensor.max`, `tensor.logsumexp`, `tensor.reduce_hypot` for floating point type arrays by at least 2x [gh-1932](https://github.com/IntelPython/dpctl/pull/1932)
* Extended `tensor.asarray` to support objects that implement `__usm_ndarray__` property to be interpreted as `usm_ndarray` objects [gh-1959](https://github.com/IntelPython/dpctl/pull/1959)
* `dpctl.tensor.usm_ndarray` object disallows implicit conversions to NumPy array [gh-1964](https://github.com/IntelPython/dpctl/pull/1964)

### Fixed

Expand Down
15 changes: 15 additions & 0 deletions dpctl/tensor/_usmarray.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1552,6 +1552,21 @@ cdef class usm_ndarray:
def __repr__(self):
return usm_ndarray_repr(self)

def __array__(self, dtype=None, /, *, copy=None):
"""NumPy's array protocol method to disallow implicit conversion.

Without this definition, `numpy.asarray(usm_ar)` converts
usm_ndarray instance into NumPy array with data type `object`
and every element being 0d usm_ndarray.

https://github.com/IntelPython/dpctl/pull/1384#issuecomment-1707212972
"""
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):
"""
Expand Down
9 changes: 9 additions & 0 deletions dpctl/tests/test_usm_ndarray_ctor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2659,3 +2659,12 @@ def test_setitem_copy_as_contig_alignment(dt):
x[1:, ...] = vals
assert dpt.all(x[0] == 0)
assert dpt.all(x[1:, :] == vals)


def test_asarray_property():
get_queue_or_skip()

x = dpt.ones(11, dtype="i4")

with pytest.raises(TypeError):
np.asarray(x)
Loading