Giter Club home page Giter Club logo

array-api-strict's Introduction

array-api-strict

array_api_strict is a strict, minimal implementation of the Python array API.

The purpose of array-api-strict is to provide an implementation of the array API for consuming libraries to test against so they can be completely sure their usage of the array API is portable.

It is not intended to be used by end-users. End-users of the array API should just use their favorite array library (NumPy, CuPy, PyTorch, etc.) as usual. It is also not intended to be used as a dependency by consuming libraries. Consuming library code should use the array-api-compat package to support the array API. Rather, it is intended to be used in the test suites of consuming libraries to test their array API usage.

array-api-strict currently supports the 2022.12 version of the standard. 2023.12 support is planned and is tracked by this issue.

See the documentation for more details https://data-apis.org/array-api-strict/

array-api-strict's People

Contributors

asmeurer avatar rgommers avatar dependabot[bot] avatar bvb93 avatar honno avatar charris avatar mattip avatar eirrgang avatar bwalshe avatar czgdp1807 avatar seberg avatar mtsokol avatar github-actions[bot] avatar arogozhnikov avatar sistaseetaram avatar alessiamarcolini avatar aktech avatar neutrinoceros avatar dimitripapadopoulos avatar francescelies avatar eltociear avatar illviljan avatar lucascolley avatar ngoldbaum avatar tirthasheshpatel avatar

Stargazers

Andreas Motl avatar Nikolaus Schlemm avatar Jeff Carpenter avatar Juan Luis Cano Rodríguez avatar  avatar  avatar

Watchers

 avatar Athan avatar

Forkers

asmeurer rgommers

array-api-strict's Issues

More strict type checking

In numpy.array_api, we said that type checking that inputs were Array was too much overhead, and we would just rely on the the type signatures and type checking to do this.

However, given that we are no longer thinking of this library as something that is used in production, I don't think we need to worry so much about the overhead of type checking. It might be a good idea to add explicit type checks to functions. This would prevent a sufficiently duck-typed object from silently passing through, although that's pretty unlikely since basically every function uses x._array on its input. The real reason would be to provide better error messages that AttributeError on bad inputs.

Maybe this can be done automatically from the type signatures using one of those fancy libraries I know nothing about.

Allow changing the default dtypes

See https://data-apis.org/array-api/latest/API_specification/data_types.html#default-data-types and https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.default_dtypes.html#array_api.info.default_dtypes.

We should add flags to the set_array_api_strict_flags to configure these away from the NumPy defaults.

One concern here is that some instances of moving from float64 to float32, we might have to just downcast the result from NumPy, meaning the computation will still happen in float64, producing a result that could be different from a library that actually does everything in float32. This should likely be worked around wherever possible by downcasting the input before computing rather than the output.

Only support NumPy 2.0 as a backend

Obviously not just yet, but once NumPy 2.0 is released and stable, we should drop support for NumPy 1.26 as a backend. That would allow us to remove all the compatibility code and only have code related to strictness.

The actual backend in array-api-strict doesn't really matter that much, but this would limit the usability for libraries that use NumPy internally in addition to the array API, so we should only do this once the ecosystem seems generally caught up on NumPy 2.0 support.

CuPy backend

We may want to move cupy.array_api to this library as a cupy backend. That would provide support for non-trivial device support, which is currently the one thing that can't really be checked that much through the usage of this library alone.

Support for older versions of the standard

Should we support older versions of the standard?

I don't think there's any point to supporting 2021.12, since no implementation actually supports it (including array-api-compat). However, as libraries actually start implementing the standard, being able to support multiple versions here could be useful.

For now, we could just tell people to install older versions of array-api-strict. But if people actually test against old versions of the standard, I would much rather just support them at once here than trying to support backport versions.

Plus, the __array_namespace__ method has the version flag specifically for this sort of thing.

By the way, if you were to ask the same question for array-api-compat, or any actual implementation for that manner, I would say no, unless the standard ends up adopting some serious backwards incompatible changes in some future version. But there could be an argument for the strict implementation to have this.

MAINT: copy semantics shim

Probably not surprising; in scipy/scipy#20172 I noticed what looks like a requirement for at least a small copy argument pass-through shim with NumPy main here because of (currently) a single test in SciPy. In that PR I was able to patch similar errors with fairly crude copy=None pass-through type shims, though in this library it may actually need to do something useful (the intended purpose) if the copy arg really needs to be respected I suppose.

============================================================================================ FAILURES =============================================================================================
______________________________________________________________________________ test_dispatch_to_unrecognize_library _______________________________________________________________________________
[gw22] linux -- Python 3.11.2 /home/treddy/python_venvs/py_311_scipy_dev/bin/python
scipy/special/tests/test_support_alternative_backends.py:25: in test_dispatch_to_unrecognize_library
    res = f(xp.asarray(x))
        f          = <function get_array_special_func.<locals>.f at 0x7f404756a2a0>
        x          = [1, 2, 3]
        xp         = <module 'array_api_strict' from '/home/treddy/python_venvs/py_311_scipy_dev/lib/python3.11/site-packages/array_api_strict/__init__.py'>
scipy/special/_support_alternative_backends.py:33: in f
    array_args = [np.asarray(arg) for arg in array_args]
        args       = (Array([1, 2, 3], dtype=array_api_strict.int64),)
        array_args = (Array([1, 2, 3], dtype=array_api_strict.int64),)
        f_scipy    = <ufunc 'ndtr'>
        kwargs     = {}
        n_array_args = 1
        other_args = ()
        xp         = <module 'array_api_strict' from '/home/treddy/python_venvs/py_311_scipy_dev/lib/python3.11/site-packages/array_api_strict/__init__.py'>
scipy/special/_support_alternative_backends.py:33: in <listcomp>
    array_args = [np.asarray(arg) for arg in array_args]
E   TypeError: Array.__array__() got an unexpected keyword argument 'copy'
        .0         = <tuple_iterator object at 0x7f4062090cd0>
        arg        = Array([1, 2, 3], dtype=array_api_strict.int64)
===================================================================================== short test summary info =====================================================================================
FAILED scipy/special/tests/test_support_alternative_backends.py::test_dispatch_to_unrecognize_library - TypeError: Array.__array__() got an unexpected keyword argument 'copy'

array-api-strict creates an empty iterable rather than raising an error

For example:

In [47]: import array_api_strict as xp

In [48]: x = xp.ones((2,2))

In [49]: list(iter(x))
Out[49]: []

I think this is because __getitem__ raises a IndexError

In [47]: import array_api_strict as xp

In [48]: x = xp.ones((2,2))

In [49]: list(iter(x))
Out[49]: []

In [50]: x.__getitem__(0)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[50], line 1
----> 1 x.__getitem__(0)

File ~/miniconda3/envs/scipy-dev-pytorch/lib/python3.11/site-packages/array_api_strict/_array_object.py:588, in Array.__getitem__(self, key)
    583 """
    584 Performs the operation __getitem__.
    585 """
    586 # Note: Only indices required by the spec are allowed. See the
    587 # docstring of _validate_index
--> 588 self._validate_index(key)
    589 if isinstance(key, Array):
    590     # Indexing self._array with array_api_strict arrays can be erroneous
    591     key = key._array

File ~/miniconda3/envs/scipy-dev-pytorch/lib/python3.11/site-packages/array_api_strict/_array_object.py:374, in Array._validate_index(self, key)
    370 elif n_ellipsis == 0:
    371     # Note boolean masks must be the sole index, which we check for
    372     # later on.
    373     if not key_has_mask and n_single_axes < self.ndim:
--> 374         raise IndexError(
    375             f"{self.ndim=}, but the multi-axes index only specifies "
    376             f"{n_single_axes} dimensions. If this was intentional, "
    377             "add a trailing ellipsis (...) which expands into as many "
    378             "slices (:) as necessary - this is what np.ndarray arrays "
    379             "implicitly do, but such flat indexing behaviour is not "
    380             "specified in the Array API."
    381         )
    383 if n_ellipsis == 0:
    384     indexed_shape = self.shape

IndexError: self.ndim=2, but the multi-axes index only specifies 1 dimensions. If this was intentional, add a trailing ellipsis (...) which expands into as many slices (:) as necessary - this is what np.ndarray arrays implicitly do, but such flat indexing behaviour is not specified in the Array API.

which is meant for out of bounds, instead I think we should be raising a TypeError.
image

This can be reproduced also in the following example

In [51]: class A:
    ...:     def __getitem__(self, key):
    ...:         raise IndexError
    ...:

In [52]: list(iter(A()))
Out[52]: []

Real documentation

Real documentation will be useful for array-api-strict, especially as we start to implement more features like #8. We can just copy the docs skeleton from array-api-compat.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.