-
Notifications
You must be signed in to change notification settings - Fork 11
ENH/TST: xp_assert_
enhancements
#267
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
Changes from 3 commits
1140a1a
054fba0
d7f7549
a6d2d8c
cb3c2d6
7347366
c80dd5e
f43f553
7cf08cc
868995f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -9,13 +9,15 @@ | |||||
from types import ModuleType | ||||||
from typing import cast | ||||||
|
||||||
import numpy as np | ||||||
import pytest | ||||||
|
||||||
from ._utils._compat import ( | ||||||
array_namespace, | ||||||
is_array_api_strict_namespace, | ||||||
is_cupy_namespace, | ||||||
is_dask_namespace, | ||||||
is_numpy_namespace, | ||||||
is_pydata_sparse_namespace, | ||||||
is_torch_namespace, | ||||||
) | ||||||
|
@@ -25,7 +27,11 @@ | |||||
|
||||||
|
||||||
def _check_ns_shape_dtype( | ||||||
actual: Array, desired: Array | ||||||
actual: Array, | ||||||
desired: Array, | ||||||
check_dtype: bool, | ||||||
check_shape: bool, | ||||||
check_scalar: bool, | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
) -> ModuleType: # numpydoc ignore=RT03 | ||||||
""" | ||||||
Assert that namespace, shape and dtype of the two arrays match. | ||||||
|
@@ -47,43 +53,62 @@ | |||||
msg = f"namespaces do not match: {actual_xp} != f{desired_xp}" | ||||||
assert actual_xp == desired_xp, msg | ||||||
|
||||||
actual_shape = actual.shape | ||||||
desired_shape = desired.shape | ||||||
if is_dask_namespace(desired_xp): | ||||||
# Dask uses nan instead of None for unknown shapes | ||||||
if any(math.isnan(i) for i in cast(tuple[float, ...], actual_shape)): | ||||||
actual_shape = actual.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
if any(math.isnan(i) for i in cast(tuple[float, ...], desired_shape)): | ||||||
desired_shape = desired.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
|
||||||
msg = f"shapes do not match: {actual_shape} != f{desired_shape}" | ||||||
assert actual_shape == desired_shape, msg | ||||||
|
||||||
msg = f"dtypes do not match: {actual.dtype} != {desired.dtype}" | ||||||
assert actual.dtype == desired.dtype, msg | ||||||
if check_shape: | ||||||
actual_shape = actual.shape | ||||||
desired_shape = desired.shape | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
if is_dask_namespace(desired_xp): | ||||||
# Dask uses nan instead of None for unknown shapes | ||||||
if any(math.isnan(i) for i in cast(tuple[float, ...], actual_shape)): | ||||||
actual_shape = actual.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
if any(math.isnan(i) for i in cast(tuple[float, ...], desired_shape)): | ||||||
desired_shape = desired.compute().shape # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
|
||||||
msg = f"shapes do not match: {actual_shape} != f{desired_shape}" | ||||||
assert actual_shape == desired_shape, msg | ||||||
|
||||||
if check_dtype: | ||||||
msg = f"dtypes do not match: {actual.dtype} != {desired.dtype}" | ||||||
assert actual.dtype == desired.dtype, msg | ||||||
|
||||||
if is_numpy_namespace(actual_xp) and check_scalar: | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. scalar sounds fine to me. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think I prefer |
||||||
# only NumPy distinguishes between scalars and arrays; we do if check_scalar. | ||||||
_msg = ( | ||||||
"array-ness does not match:\n Actual: " | ||||||
f"{type(actual)}\n Desired: {type(desired)}" | ||||||
) | ||||||
assert np.isscalar(actual) == np.isscalar(desired), _msg | ||||||
|
||||||
return desired_xp | ||||||
|
||||||
|
||||||
def _prepare_for_test(array: Array, xp: ModuleType) -> Array: | ||||||
""" | ||||||
Ensure that the array can be compared with xp.testing or np.testing. | ||||||
Ensure that the array can be compared with np.testing. | ||||||
|
||||||
This involves transferring it from GPU to CPU memory, densifying it, etc. | ||||||
""" | ||||||
if is_torch_namespace(xp): | ||||||
return array.cpu() # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
return np.asarray(array.cpu()) # type: ignore[attr-defined, return-value] # pyright: ignore[reportAttributeAccessIssue, reportUnknownArgumentType, reportReturnType] | ||||||
if is_pydata_sparse_namespace(xp): | ||||||
return array.todense() # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
if is_array_api_strict_namespace(xp): | ||||||
# Note: we deliberately did not add a `.to_device` method in _typing.pyi | ||||||
# even if it is required by the standard as many backends don't support it | ||||||
return array.to_device(xp.Device("CPU_DEVICE")) # type: ignore[attr-defined] # pyright: ignore[reportAttributeAccessIssue] | ||||||
# Note: nothing to do for CuPy, because it uses a bespoke test function | ||||||
if is_cupy_namespace(xp): | ||||||
return xp.asnumpy(array) | ||||||
mdhaber marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
return array | ||||||
|
||||||
|
||||||
def xp_assert_equal(actual: Array, desired: Array, err_msg: str = "") -> None: | ||||||
def xp_assert_equal( | ||||||
actual: Array, | ||||||
desired: Array, | ||||||
*, | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
err_msg: str = "", | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
check_dtype: bool = True, | ||||||
check_shape: bool = True, | ||||||
check_scalar: bool = False, | ||||||
) -> None: | ||||||
""" | ||||||
Array-API compatible version of `np.testing.assert_array_equal`. | ||||||
|
||||||
|
@@ -95,34 +120,56 @@ | |||||
The expected array (typically hardcoded). | ||||||
err_msg : str, optional | ||||||
Error message to display on failure. | ||||||
check_dtype, check_shape : bool, default: True | ||||||
Whether to check agreement between actual and desired dtypes and shapes | ||||||
check_scalar : bool, default: False | ||||||
NumPy only: whether to check agreement between actual and desired types - | ||||||
0d array vs scalar. | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
See Also | ||||||
-------- | ||||||
xp_assert_close : Similar function for inexact equality checks. | ||||||
numpy.testing.assert_array_equal : Similar function for NumPy arrays. | ||||||
""" | ||||||
xp = _check_ns_shape_dtype(actual, desired) | ||||||
xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar) | ||||||
actual = _prepare_for_test(actual, xp) | ||||||
desired = _prepare_for_test(desired, xp) | ||||||
np.testing.assert_array_equal(actual, desired, err_msg=err_msg) | ||||||
|
||||||
if is_cupy_namespace(xp): | ||||||
xp.testing.assert_array_equal(actual, desired, err_msg=err_msg) | ||||||
elif is_torch_namespace(xp): | ||||||
# PyTorch recommends using `rtol=0, atol=0` like this | ||||||
# to test for exact equality | ||||||
xp.testing.assert_close( | ||||||
actual, | ||||||
desired, | ||||||
rtol=0, | ||||||
atol=0, | ||||||
equal_nan=True, | ||||||
check_dtype=False, | ||||||
msg=err_msg or None, | ||||||
) | ||||||
else: | ||||||
import numpy as np # pylint: disable=import-outside-toplevel | ||||||
|
||||||
np.testing.assert_array_equal(actual, desired, err_msg=err_msg) | ||||||
def xp_assert_less( | ||||||
x: Array, | ||||||
y: Array, | ||||||
*, | ||||||
err_msg: str = "", | ||||||
check_dtype: bool = True, | ||||||
check_shape: bool = True, | ||||||
check_scalar: bool = False, | ||||||
) -> None: | ||||||
""" | ||||||
Array-API compatible version of `np.testing.assert_array_less`. | ||||||
|
||||||
Parameters | ||||||
---------- | ||||||
x, y : Array | ||||||
The arrays to compare according to ``x < y`` (elementwise). | ||||||
err_msg : str, optional | ||||||
Error message to display on failure. | ||||||
check_dtype, check_shape : bool, default: True | ||||||
Whether to check agreement between actual and desired dtypes and shapes | ||||||
check_scalar : bool, default: False | ||||||
NumPy only: whether to check agreement between actual and desired types - | ||||||
0d array vs scalar. | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
|
||||||
See Also | ||||||
-------- | ||||||
xp_assert_close : Similar function for inexact equality checks. | ||||||
numpy.testing.assert_array_equal : Similar function for NumPy arrays. | ||||||
""" | ||||||
xp = _check_ns_shape_dtype(x, y, check_dtype, check_shape, check_scalar) | ||||||
x = _prepare_for_test(x, xp) | ||||||
y = _prepare_for_test(y, xp) | ||||||
np.testing.assert_array_less(x, y, err_msg=err_msg) # type: ignore[call-overload] | ||||||
Check failure on line 172 in src/array_api_extra/_lib/_testing.py
|
||||||
|
||||||
|
||||||
def xp_assert_close( | ||||||
|
@@ -132,6 +179,9 @@ | |||||
rtol: float | None = None, | ||||||
atol: float = 0, | ||||||
err_msg: str = "", | ||||||
check_dtype: bool = True, | ||||||
check_shape: bool = True, | ||||||
check_scalar: bool = False, | ||||||
) -> None: | ||||||
""" | ||||||
Array-API compatible version of `np.testing.assert_allclose`. | ||||||
|
@@ -148,6 +198,11 @@ | |||||
Absolute tolerance. Default: 0. | ||||||
err_msg : str, optional | ||||||
Error message to display on failure. | ||||||
check_dtype, check_shape : bool, default: True | ||||||
Whether to check agreement between actual and desired dtypes and shapes | ||||||
check_scalar : bool, default: False | ||||||
NumPy only: whether to check agreement between actual and desired types - | ||||||
0d array vs scalar. | ||||||
|
||||||
See Also | ||||||
-------- | ||||||
|
@@ -159,7 +214,7 @@ | |||||
----- | ||||||
The default `atol` and `rtol` differ from `xp.all(xpx.isclose(a, b))`. | ||||||
""" | ||||||
xp = _check_ns_shape_dtype(actual, desired) | ||||||
xp = _check_ns_shape_dtype(actual, desired, check_dtype, check_shape, check_scalar) | ||||||
|
||||||
floating = xp.isdtype(actual.dtype, ("real floating", "complex floating")) | ||||||
if rtol is None and floating: | ||||||
|
@@ -173,26 +228,14 @@ | |||||
actual = _prepare_for_test(actual, xp) | ||||||
desired = _prepare_for_test(desired, xp) | ||||||
|
||||||
if is_cupy_namespace(xp): | ||||||
xp.testing.assert_allclose( | ||||||
actual, desired, rtol=rtol, atol=atol, err_msg=err_msg | ||||||
) | ||||||
elif is_torch_namespace(xp): | ||||||
xp.testing.assert_close( | ||||||
actual, desired, rtol=rtol, atol=atol, equal_nan=True, msg=err_msg or None | ||||||
) | ||||||
else: | ||||||
import numpy as np # pylint: disable=import-outside-toplevel | ||||||
|
||||||
# JAX/Dask arrays work directly with `np.testing` | ||||||
assert isinstance(rtol, float) | ||||||
lucascolley marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
np.testing.assert_allclose( # type: ignore[call-overload] # pyright: ignore[reportCallIssue] | ||||||
actual, # pyright: ignore[reportArgumentType] | ||||||
desired, # pyright: ignore[reportArgumentType] | ||||||
rtol=rtol, | ||||||
atol=atol, | ||||||
err_msg=err_msg, | ||||||
) | ||||||
# JAX/Dask arrays work directly with `np.testing` | ||||||
mdhaber marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||
np.testing.assert_allclose( # type: ignore[call-overload] # pyright: ignore[reportCallIssue] | ||||||
actual, # pyright: ignore[reportArgumentType] | ||||||
desired, # pyright: ignore[reportArgumentType] | ||||||
rtol=rtol, | ||||||
Check failure on line 235 in src/array_api_extra/_lib/_testing.py
|
||||||
atol=atol, | ||||||
err_msg=err_msg, | ||||||
) | ||||||
|
||||||
|
||||||
def xfail( | ||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this OK? Sometimes it was imported within test functions below.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Today it is OK, as this module is not imported automatically from the outer scope.
In the long run though, we want to move this module to public at which point it won't be a good design anymore (although it remains to be seen if any Array library in real life can achieve not to have numpy as a hard dependency...)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, I think it would be fine to make these public API once they are ready, with the caveat that NumPy is required. We are really striving for minimal runtime dependencies rather than test time dependencies downstream, at least for now.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This module heavily relies on
np.testing.assert*
anyway.We'll just need to add a test that
import array_api_extra
doesn't import numpy.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note to do this in a follow-up