Skip to content

Commit fd3cd70

Browse files
committed
Merge branch 'main' into test_all
2 parents 1fad293 + e600449 commit fd3cd70

File tree

5 files changed

+61
-66
lines changed

5 files changed

+61
-66
lines changed

array_api_compat/common/_helpers.py

Lines changed: 17 additions & 31 deletions
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

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,6 @@
6363
finfo = get_xp(cp)(_aliases.finfo)
6464
iinfo = get_xp(cp)(_aliases.iinfo)
6565

66-
_copy_default = object()
67-
6866

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

11197

11298
def astype(

cupy-xfails.txt

Lines changed: 0 additions & 3 deletions
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

Lines changed: 14 additions & 10 deletions
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

Lines changed: 22 additions & 0 deletions
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)