-
Notifications
You must be signed in to change notification settings - Fork 35
Implement isdtype() #32
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
0bef982
Add isdtype implementation for numpy/cupy with some initial testing
asmeurer fa772de
Fix test skipping for cupy
asmeurer a375e9d
Test complex dtypes in test_isdtype
asmeurer 7c7c02e
Test additional dtypes in test_isdtype
asmeurer fc90e1b
Add isdtype support for pytorch
asmeurer a8c92e5
Return instead of skipping (so there are no skips in the test output)
asmeurer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,7 @@ | ||
from __future__ import annotations | ||
|
||
from functools import wraps | ||
from builtins import all as builtin_all | ||
from builtins import all as builtin_all, any as builtin_any | ||
|
||
from ..common._aliases import (UniqueAllResult, UniqueCountsResult, | ||
UniqueInverseResult, | ||
|
@@ -18,13 +18,17 @@ | |
import torch | ||
array = torch.Tensor | ||
|
||
_array_api_dtypes = { | ||
torch.bool, | ||
_int_dtypes = { | ||
torch.uint8, | ||
torch.int8, | ||
torch.int16, | ||
torch.int32, | ||
torch.int64, | ||
} | ||
|
||
_array_api_dtypes = { | ||
torch.bool, | ||
*_int_dtypes, | ||
torch.float32, | ||
torch.float64, | ||
} | ||
|
@@ -602,6 +606,43 @@ def tensordot(x1: array, x2: array, /, *, axes: Union[int, Tuple[Sequence[int], | |
x1, x2 = _fix_promotion(x1, x2, only_scalar=False) | ||
return torch.tensordot(x1, x2, dims=axes, **kwargs) | ||
|
||
|
||
def isdtype( | ||
dtype: Dtype, kind: Union[Dtype, str, Tuple[Union[Dtype, str], ...]], | ||
*, _tuple=True, # Disallow nested tuples | ||
) -> bool: | ||
""" | ||
Returns a boolean indicating whether a provided dtype is of a specified data type ``kind``. | ||
|
||
Note that outside of this function, this compat library does not yet fully | ||
support complex numbers. | ||
|
||
See | ||
https://data-apis.org/array-api/latest/API_specification/generated/array_api.isdtype.html | ||
for more details | ||
""" | ||
if isinstance(kind, tuple) and _tuple: | ||
return builtin_any(isdtype(dtype, k, _tuple=False) for k in kind) | ||
elif isinstance(kind, str): | ||
if kind == 'bool': | ||
return dtype == torch.bool | ||
elif kind == 'signed integer': | ||
return dtype in _int_dtypes and dtype.is_signed | ||
elif kind == 'unsigned integer': | ||
return dtype in _int_dtypes and not dtype.is_signed | ||
elif kind == 'integral': | ||
return dtype in _int_dtypes | ||
elif kind == 'real floating': | ||
return dtype.is_floating_point | ||
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. Is this the correct way to check for torch dtype categories? 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. This should be good, yes. |
||
elif kind == 'complex floating': | ||
return dtype.is_complex | ||
elif kind == 'numeric': | ||
return isdtype(dtype, ('integral', 'real floating', 'complex floating')) | ||
else: | ||
raise ValueError(f"Unrecognized data type kind: {kind!r}") | ||
else: | ||
return dtype == kind | ||
|
||
__all__ = ['result_type', 'can_cast', 'permute_dims', 'bitwise_invert', 'add', | ||
'atan2', 'bitwise_and', 'bitwise_left_shift', 'bitwise_or', | ||
'bitwise_right_shift', 'bitwise_xor', 'divide', 'equal', | ||
|
@@ -612,4 +653,4 @@ def tensordot(x1: array, x2: array, /, *, axes: Union[int, Tuple[Sequence[int], | |
'nonzero', 'where', 'arange', 'eye', 'linspace', 'full', 'ones', | ||
'zeros', 'empty', 'expand_dims', 'astype', 'broadcast_arrays', | ||
'unique_all', 'unique_counts', 'unique_inverse', 'unique_values', | ||
'matmul', 'matrix_transpose', 'vecdot', 'tensordot'] | ||
'matmul', 'matrix_transpose', 'vecdot', 'tensordot', 'isdtype'] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
from importlib import import_module | ||
|
||
import pytest | ||
|
||
def import_(library): | ||
if 'cupy' in library: | ||
return pytest.importorskip(library) | ||
return import_module(library) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
""" | ||
isdtype is not yet tested in the test suite, and it should extend properly to | ||
non-spec dtypes | ||
""" | ||
|
||
from ._helpers import import_ | ||
|
||
import pytest | ||
|
||
# Check the known dtypes by their string names | ||
|
||
def _spec_dtypes(library): | ||
if library == 'torch': | ||
# torch does not have unsigned integer dtypes | ||
return { | ||
'bool', | ||
'complex64', | ||
'complex128', | ||
'uint8', | ||
'int8', | ||
'int16', | ||
'int32', | ||
'int64', | ||
'float32', | ||
'float64', | ||
} | ||
else: | ||
return { | ||
'bool', | ||
'complex64', | ||
'complex128', | ||
'float32', | ||
'float64', | ||
'int16', | ||
'int32', | ||
'int64', | ||
'int8', | ||
'uint16', | ||
'uint32', | ||
'uint64', | ||
'uint8', | ||
} | ||
|
||
dtype_categories = { | ||
'bool': lambda d: d == 'bool', | ||
'signed integer': lambda d: d.startswith('int'), | ||
'unsigned integer': lambda d: d.startswith('uint'), | ||
'integral': lambda d: dtype_categories['signed integer'](d) or | ||
dtype_categories['unsigned integer'](d), | ||
'real floating': lambda d: 'float' in d, | ||
'complex floating': lambda d: d.startswith('complex'), | ||
'numeric': lambda d: dtype_categories['integral'](d) or | ||
dtype_categories['real floating'](d) or | ||
dtype_categories['complex floating'](d), | ||
} | ||
|
||
def isdtype_(dtype_, kind): | ||
# Check a dtype_ string against kind. Note that 'bool' technically has two | ||
# meanings here but they are both the same. | ||
if kind in dtype_categories: | ||
res = dtype_categories[kind](dtype_) | ||
else: | ||
res = dtype_ == kind | ||
assert type(res) is bool | ||
return res | ||
|
||
@pytest.mark.parametrize("library", ["cupy", "numpy", "torch"]) | ||
def test_isdtype_spec_dtypes(library): | ||
xp = import_('array_api_compat.' + library) | ||
|
||
isdtype = xp.isdtype | ||
|
||
for dtype_ in _spec_dtypes(library): | ||
for dtype2_ in _spec_dtypes(library): | ||
dtype = getattr(xp, dtype_) | ||
dtype2 = getattr(xp, dtype2_) | ||
res = isdtype_(dtype_, dtype2_) | ||
assert isdtype(dtype, dtype2) is res, (dtype_, dtype2_) | ||
|
||
for cat in dtype_categories: | ||
res = isdtype_(dtype_, cat) | ||
assert isdtype(dtype, cat) == res, (dtype_, cat) | ||
|
||
# Basic tuple testing (the array-api testsuite will be more complete here) | ||
for kind1_ in [*_spec_dtypes(library), *dtype_categories]: | ||
for kind2_ in [*_spec_dtypes(library), *dtype_categories]: | ||
kind1 = kind1_ if kind1_ in dtype_categories else getattr(xp, kind1_) | ||
kind2 = kind2_ if kind2_ in dtype_categories else getattr(xp, kind2_) | ||
kind = (kind1, kind2) | ||
|
||
res = isdtype_(dtype_, kind1_) or isdtype_(dtype_, kind2_) | ||
assert isdtype(dtype, kind) == res, (dtype_, (kind1_, kind2_)) | ||
|
||
additional_dtypes = [ | ||
'float16', | ||
'float128', | ||
'complex256', | ||
'bfloat16', | ||
] | ||
|
||
@pytest.mark.parametrize("library", ["cupy", "numpy", "torch"]) | ||
@pytest.mark.parametrize("dtype_", additional_dtypes) | ||
def test_isdtype_additional_dtypes(library, dtype_): | ||
xp = import_('array_api_compat.' + library) | ||
|
||
isdtype = xp.isdtype | ||
|
||
if not hasattr(xp, dtype_): | ||
return | ||
# pytest.skip(f"{library} doesn't have dtype {dtype_}") | ||
|
||
dtype = getattr(xp, dtype_) | ||
for cat in dtype_categories: | ||
res = isdtype_(dtype_, cat) | ||
assert isdtype(dtype, cat) == res, (dtype_, cat) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
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 there a better way to test if a torch dtype is integral?
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.
There isn't. Based on dtype properties it would be:
which looks worse and may also not be foolproof. The check you have will need explicit updating if for example
uint16
is added to PyTorch, but that's okay (nothing like that is in the pipeline AFAIK).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.
Hopefully this function itself would be added to pytorch by then.