Skip to content

Commit a4023cc

Browse files
authored
ENH: Generation of compatable device and dtype pairs for test_from_dlpack (#443)
reviewed at #443
1 parent 5d0b701 commit a4023cc

3 files changed

Lines changed: 43 additions & 36 deletions

File tree

array_api_tests/dtype_helpers.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,31 @@ def is_scalar(x):
199199
return isinstance(x, (int, float, complex, bool))
200200

201201

202+
def is_device_dlpack_compatible(device):
203+
"""If device is dlpack compatible, return True, else False"""
204+
# XXX: there seems to be no better way than try-catch for __dlpack_device__()
205+
206+
x = xp.empty(2, device=device)
207+
try:
208+
x.__dlpack_device__()
209+
except:
210+
# case in point: torch.device(type="meta") raises
211+
# ValueError: Unknown device type meta for Dlpack
212+
return False
213+
else:
214+
# no exception => device is compatible (or a cuda device)
215+
return True
216+
217+
218+
def is_dtype_device_compatible(dtype, device):
219+
try:
220+
xp.asarray([0], dtype=dtype, device=device)
221+
except Exception:
222+
return False
223+
else:
224+
return True
225+
226+
202227
def complex_dtype_for(dtyp):
203228
"""Complex dtype for a float or complex."""
204229
if dtyp in complex_dtypes:

array_api_tests/hypothesis_helpers.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,13 @@ def arrays(dtype, *args, elements=None, **kwargs) -> SearchStrategy[Array]:
9393

9494
_dtype_categories = [(xp.bool,), dh.uint_dtypes, dh.int_dtypes, dh.real_float_dtypes, dh.complex_dtypes]
9595
_sorted_dtypes = [d for category in _dtype_categories for d in category]
96+
_device_dtype_pairs = [
97+
(dtype, device)
98+
for dtype in _sorted_dtypes
99+
for device in xp.__array_namespace_info__().devices()
100+
if dh.is_device_dlpack_compatible(device)
101+
if dh.is_dtype_device_compatible(dtype, device)
102+
]
96103

97104
def _dtypes_sorter(dtype_pair: Tuple[DataType, DataType]):
98105
dtype1, dtype2 = dtype_pair
@@ -199,6 +206,7 @@ def oneway_broadcastable_shapes(draw) -> OnewayBroadcastableShapes:
199206
# Use these instead of xps.scalar_dtypes, etc. because it skips dtypes from
200207
# ARRAY_API_TESTS_SKIP_DTYPES
201208
all_dtypes = sampled_from(_sorted_dtypes)
209+
device_dtype_pairs = sampled_from(_device_dtype_pairs)
202210
all_int_dtypes = sampled_from(dh.all_int_dtypes)
203211
int_dtypes = sampled_from(dh.int_dtypes) # signed ints
204212
uint_dtypes = sampled_from(dh.uint_dtypes)

array_api_tests/test_dlpack.py

Lines changed: 10 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,6 @@ class DLPackDeviceEnum(Enum):
2121
ONE_API = 14
2222

2323

24-
def _compatible_devices(devices):
25-
"""Given a list of devices, filter out dlpack-incompatible ones."""
26-
# XXX: there seems to be no better way than try-catch for __dlpack_device__()
27-
28-
# XXX: this process actually fails with CuPy because CuPy ignores the device= argument
29-
# cf https://github.com/data-apis/array-api-compat/issues/337 and
30-
# https://github.com/cupy/cupy/issues/9848
31-
# Luckily, CuPy only supports CUDA devices, and they are all compatible.
32-
compatible_ = []
33-
for device in devices:
34-
x = xp.empty(2, device=device)
35-
try:
36-
x.__dlpack_device__()
37-
except:
38-
# case in point: torch.device(type="meta") raises
39-
# ValueError: Unknown device type meta for Dlpack
40-
pass
41-
else:
42-
# no exception => device is compatible
43-
compatible_.append(device)
44-
return compatible_
45-
46-
4724
@given(dtype=hh.all_dtypes, data=st.data())
4825
def test_dlpack_device(dtype, data):
4926
"""Test the array object __dlpack_device__ method."""
@@ -88,27 +65,24 @@ def test_dunder_dlpack(x, copy_kw, max_version_kw, dl_device_kw, data):
8865

8966

9067
@given(
91-
x=hh.arrays(dtype=hh.all_dtypes, shape=hh.shapes(min_dims=1, max_side=2)),
68+
dtype_device_pair=hh.device_dtype_pairs,
9269
copy_kw=hh.kwargs(copy=st.booleans()),
9370
data=st.data()
9471
)
95-
def test_from_dlpack(x, copy_kw, data):
72+
def test_from_dlpack(copy_kw, data, dtype_device_pair):
9673
# TODO: 1. test copy; 2. generate inputs on non-default devices;
9774
# 3. test for copy=False cross-device transfers
9875
# 4. test 0D arrays / numpy scalars (the latter do not support dlpack ATM)
99-
76+
dtype, device = dtype_device_pair
77+
x = data.draw(hh.arrays(dtype=dtype, shape=hh.shapes(min_dims=1, max_side=2)))
10078
copy = copy_kw["copy"] if copy_kw else None
101-
if copy is False:
102-
# XXX there is no way to tell if a no-copy cross-device transfer is meant to succeed
103-
devices = [x.device]
79+
# XXX there is no way to tell if a no-copy cross-device transfer is meant to succeed
80+
tgt_device = x.device if copy is False else device
81+
if data.draw(st.booleans()):
82+
tgt_device_kw = {"device": tgt_device}
10483
else:
105-
devices = xp.__array_namespace_info__().devices()
106-
devices = _compatible_devices(devices)
107-
108-
tgt_device_kw = data.draw(
109-
hh.kwargs(device=st.sampled_from(devices) | st.none())
110-
)
111-
tgt_device = tgt_device_kw['device'] if tgt_device_kw else None
84+
tgt_device_kw = {}
85+
tgt_device = tgt_device_kw.get("device")
11286

11387
repro_snippet = ph.format_snippet(
11488
f"y = from_dlpack({x!r}, **tgt_device_kw, **copy_kw) with {tgt_device_kw=} and {copy_kw=}"

0 commit comments

Comments
 (0)