Skip to content

Commit e600449

Browse files
authored
ENH: Simplify CuPy asarray and to_device (#314)
reviewed at #314
1 parent 52e01be commit e600449

File tree

5 files changed

+61
-66
lines changed

5 files changed

+61
-66
lines changed

array_api_compat/common/_helpers.py

+17-31
Original file line numberDiff line numberDiff line change
@@ -775,42 +775,28 @@ def _cupy_to_device(
775775
/,
776776
stream: int | Any | None = None,
777777
) -> _CupyArray:
778-
import cupy as cp # pyright: ignore[reportMissingTypeStubs]
779-
from cupy.cuda import Device as _Device # pyright: ignore
780-
from cupy.cuda import stream as stream_module # pyright: ignore
781-
from cupy_backends.cuda.api import runtime # pyright: ignore
778+
import cupy as cp
782779

783-
if device == x.device:
784-
return x
785-
elif device == "cpu":
780+
if device == "cpu":
786781
# allowing us to use `to_device(x, "cpu")`
787782
# is useful for portable test swapping between
788783
# host and device backends
789784
return x.get()
790-
elif not isinstance(device, _Device):
791-
raise ValueError(f"Unsupported device {device!r}")
792-
else:
793-
# see cupy/cupy#5985 for the reason how we handle device/stream here
794-
prev_device: Any = runtime.getDevice() # pyright: ignore[reportUnknownMemberType]
795-
prev_stream = None
796-
if stream is not None:
797-
prev_stream: Any = stream_module.get_current_stream() # pyright: ignore
798-
# stream can be an int as specified in __dlpack__, or a CuPy stream
799-
if isinstance(stream, int):
800-
stream = cp.cuda.ExternalStream(stream) # pyright: ignore
801-
elif isinstance(stream, cp.cuda.Stream): # pyright: ignore[reportUnknownMemberType]
802-
pass
803-
else:
804-
raise ValueError("the input stream is not recognized")
805-
stream.use() # pyright: ignore[reportUnknownMemberType]
806-
try:
807-
runtime.setDevice(device.id) # pyright: ignore[reportUnknownMemberType]
808-
arr = x.copy()
809-
finally:
810-
runtime.setDevice(prev_device) # pyright: ignore[reportUnknownMemberType]
811-
if stream is not None:
812-
prev_stream.use()
813-
return arr
785+
if not isinstance(device, cp.cuda.Device):
786+
raise TypeError(f"Unsupported device type {device!r}")
787+
788+
if stream is None:
789+
with device:
790+
return cp.asarray(x)
791+
792+
# stream can be an int as specified in __dlpack__, or a CuPy stream
793+
if isinstance(stream, int):
794+
stream = cp.cuda.ExternalStream(stream)
795+
elif not isinstance(stream, cp.cuda.Stream):
796+
raise TypeError(f"Unsupported stream type {stream!r}")
797+
798+
with device, stream:
799+
return cp.asarray(x)
814800

815801

816802
def _torch_to_device(

array_api_compat/cupy/_aliases.py

+8-22
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,6 @@
6464
finfo = get_xp(cp)(_aliases.finfo)
6565
iinfo = get_xp(cp)(_aliases.iinfo)
6666

67-
_copy_default = object()
68-
6967

7068
# asarray also adds the copy keyword, which is not present in numpy 1.0.
7169
def asarray(
@@ -79,7 +77,7 @@ def asarray(
7977
*,
8078
dtype: Optional[DType] = None,
8179
device: Optional[Device] = None,
82-
copy: Optional[bool] = _copy_default,
80+
copy: Optional[bool] = None,
8381
**kwargs,
8482
) -> Array:
8583
"""
@@ -89,25 +87,13 @@ def asarray(
8987
specification for more details.
9088
"""
9189
with cp.cuda.Device(device):
92-
# cupy is like NumPy 1.26 (except without _CopyMode). See the comments
93-
# in asarray in numpy/_aliases.py.
94-
if copy is not _copy_default:
95-
# A future version of CuPy will change the meaning of copy=False
96-
# to mean no-copy. We don't know for certain what version it will
97-
# be yet, so to avoid breaking that version, we use a different
98-
# default value for copy so asarray(obj) with no copy kwarg will
99-
# always do the copy-if-needed behavior.
100-
101-
# This will still need to be updated to remove the
102-
# NotImplementedError for copy=False, but at least this won't
103-
# break the default or existing behavior.
104-
if copy is None:
105-
copy = False
106-
elif copy is False:
107-
raise NotImplementedError("asarray(copy=False) is not yet supported in cupy")
108-
kwargs['copy'] = copy
109-
110-
return cp.array(obj, dtype=dtype, **kwargs)
90+
if copy is None:
91+
return cp.asarray(obj, dtype=dtype, **kwargs)
92+
else:
93+
res = cp.array(obj, dtype=dtype, copy=copy, **kwargs)
94+
if not copy and res is not obj:
95+
raise ValueError("Unable to avoid copy while creating an array as requested")
96+
return res
11197

11298

11399
def astype(

cupy-xfails.txt

-3
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,6 @@ array_api_tests/test_array_object.py::test_scalar_casting[__index__(int64)]
1111
# testsuite bug (https://github.com/data-apis/array-api-tests/issues/172)
1212
array_api_tests/test_array_object.py::test_getitem
1313

14-
# copy=False is not yet implemented
15-
array_api_tests/test_creation_functions.py::test_asarray_arrays
16-
1714
# attributes are np.float32 instead of float
1815
# (see also https://github.com/data-apis/array-api/issues/405)
1916
array_api_tests/test_data_type_functions.py::test_finfo[float32]

tests/test_common.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from array_api_compat import (
1818
device, is_array_api_obj, is_lazy_array, is_writeable_array, size, to_device
1919
)
20+
from array_api_compat.common._helpers import _DASK_DEVICE
2021
from ._helpers import all_libraries, import_, wrapped_libraries, xfail
2122

2223

@@ -189,23 +190,26 @@ class C:
189190

190191

191192
@pytest.mark.parametrize("library", all_libraries)
192-
def test_device(library, request):
193+
def test_device_to_device(library, request):
193194
if library == "ndonnx":
194-
xfail(request, reason="Needs ndonnx >=0.9.4")
195+
xfail(request, reason="Stub raises ValueError")
196+
if library == "sparse":
197+
xfail(request, reason="No __array_namespace_info__()")
195198

196199
xp = import_(library, wrapper=True)
200+
devices = xp.__array_namespace_info__().devices()
197201

198-
# We can't test much for device() and to_device() other than that
199-
# x.to_device(x.device) works.
200-
202+
# Default device
201203
x = xp.asarray([1, 2, 3])
202204
dev = device(x)
203205

204-
x2 = to_device(x, dev)
205-
assert device(x2) == device(x)
206-
207-
x3 = xp.asarray(x, device=dev)
208-
assert device(x3) == device(x)
206+
for dev in devices:
207+
if dev is None: # JAX >=0.5.3
208+
continue
209+
if dev is _DASK_DEVICE: # TODO this needs a better design
210+
continue
211+
y = to_device(x, dev)
212+
assert device(y) == dev
209213

210214

211215
@pytest.mark.parametrize("library", wrapped_libraries)

tests/test_cupy.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import pytest
2+
from array_api_compat import device, to_device
3+
4+
xp = pytest.importorskip("array_api_compat.cupy")
5+
from cupy.cuda import Stream
6+
7+
8+
def test_to_device_with_stream():
9+
devices = xp.__array_namespace_info__().devices()
10+
streams = [
11+
Stream(),
12+
Stream(non_blocking=True),
13+
Stream(null=True),
14+
Stream(ptds=True),
15+
123, # dlpack stream
16+
]
17+
18+
a = xp.asarray([1, 2, 3])
19+
for dev in devices:
20+
for stream in streams:
21+
b = to_device(a, dev, stream=stream)
22+
assert device(b) == dev

0 commit comments

Comments
 (0)