Coder Social home page Coder Social logo

array-api-compat's People

Contributors

adonath avatar asmeurer avatar dependabot[bot] avatar ev-br avatar kadykov avatar lithomas1 avatar lucascolley avatar matthewfeickert avatar neilgirdhar avatar rgommers avatar thomasjpfan avatar tupui avatar tylerjereddy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

array-api-compat's Issues

Support for 2023.12

This is a tracking issue for 2023.12 support in array-api-compat.

The list of changes for 2023.12 is at https://data-apis.org/array-api/latest/changelog.html#v2023-12

Currently, we don't have test suite support for 2023.12 (data-apis/array-api-tests#249), so it's hard to implement full support. However, if there are any known differences for a given library and 2023.12, we can implement a wrapper for them, especially if this is blocking anyone's real world usage. Please comment below if this is the case for you.

Note that any function that is already implemented in upstream libraries will already work with array-api-compat, since it only extends the existing library namespaces. So this is only necessary if some upstream function or behavior is different from what is written in the 2023.12 standard.

Remove "cpu" device

Right now we have and support "cpu" as a device for all supported libraries in the to_device() helper. In particular, we allow to_device(cupy_array, "cpu") to convert a CuPy array to a NumPy array.

This was implemented as a way to portably move an array to the host device, as per data-apis/array-api#626. However, it looks like that issue is going to be resolved in a different way, by adding a device keyword to from_dlpack data-apis/array-api#741.

So I propose we remove this behavior, as it extends things in a way that isn't specified by the standard. Since I'm not sure who is using this, we may want to issue a deprecation warning first.

CC @tylerjereddy @leofang

rename or alias `get_namespace` to `array_namespace`

Having a function array_namespace seems more intuitive than get_namespace, mainly due to symmetry with e.g. repr(), str(), iter(), next(), since array_namespace(x) returns x.__array_namespace__() if it exists, and does something sensible if it does not.

Implement torch.take with `axis` argument

I suspect take's axis argument will be needed at some point. Can we add a simple implementation for PyTorch?

def take(array, indices, *, axis):
    key = [slice(None)] * array.ndim
    key[axis] = indices
    return array[key]

Undefined type annotations in _helpers.py

My VScode with ruff extension showed that the Device and Array annotations in common/_helpers.py are undefined:

image

And from a quick look I think this is true. Maybe adopt ruff as a default linter / .pre-commit hook?

Compatibility problem with pytorch trace

torch.linalg.trace should work on stacks of matrices.

But this

import array_api_compat.torch as torch

a = torch.reshape(torch.arange(10*5*5), (10,5,5))
torch.linalg.trace(a)

throws RuntimeError: trace: expected a matrix, but got tensor with dim 3.

The pytorch's trace function doesn't handle stacks: see the docs.

Versioning

We need to think about how we want to version this. Do we want to use 1.0 style versions or date versioning? Are there any considerations that we should think about for the fact that many people will want to vendor this?

Actual docs

Right now the only docs are the README, but as we add more compatibility functions, it may be better to have some actual documentation.

torch.zeros can not pass shape as keyword argument

import array_api_compat
import torch

x = torch.asarray([1.0, 2.0, 3.0])
xp = array_api_compat.get_namespace(x)
xp.zeros(shape=(8, 4))
# TypeError: zeros() missing 1 required positional arguments: "size"

dtype from string helper function

numpy.dtype supports creating a dtype from a string, such as numpy.dtype('float32'). torch.dtype does not, and as far as I can tell array-api-compat has no general way to do this other than gettar on the entire API namespace (which is not safe).

It would be helpful to have a compatibility wrapper that allows loading of dtypes from strings. This is a particular problem in array-api-compat since there is no way for a function to transparently use array-api-compat internally with dtypes other than by using strings.

`array_api_compat.numpy.asarray(torch.Tensor)` returns a `torch.Tensor`

This feels like a bug to me. My expectation is that xp.asarray converts to an array object in the xp namespace if that operation is supported.

>>> import torch
>>> import array_api_compat.numpy
>>> x = torch.arange(10)
>>> array_api_compat.numpy.asarray(x)
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

New `fft` tests are failing in CI

For both NumPy and PyTorch, see for example gh-66. From one CI log:

FAILED array_api_tests/test_fft.py::test_fft - AssertionError: out.dtype=complex128, but should be complex64 [fft(float32)]
Falsifying example: test_fft(
    x=array([0., 0.], dtype=float32),
    data=data(...),
)
Draw 1 (n): None
Draw 2 (axis): 0
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'axis': 0, 'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BgZGJABYwMAABOAAU=') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_ifft - AssertionError: out.dtype=complex128, but should be complex64 [ifft(float32)]
Falsifying example: test_ifft(
    x=array([0., 0.], dtype=float32),
    data=data(...),
)
Draw 1 (n): None
Draw 2 (axis): 0
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'axis': 0, 'norm': 'ortho'}
Explanation:
    These lines were always and only run by failing examples:
        /home/runner/work/array-api-compat/array-api-compat/array-api-tests/array_api_tests/test_fft.py:91

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BgZGJABYwMAABOAAU=') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_fftn - AssertionError: out.dtype=complex128, but should be complex64 [fftn(float32)]
Falsifying example: test_fftn(
    x=array([0., 0.], dtype=float32),
    data=data(...),
)
Draw 1 (axes): None
Draw 2 (s): None
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BgZGJABYwMDAAAUwAF') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_ifftn - AssertionError: out.dtype=complex128, but should be complex64 [ifftn(float32)]
Falsifying example: test_ifftn(
    x=array([0., 0.], dtype=float32),
    data=data(...),
)
Draw 1 (axes): [0]
Draw 2 (s): (1,)
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'s': (1,), 'axes': [0], 'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BgZGJABoxABAAAUQAG') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_rfft - ExceptionGroup: Hypothesis found 2 distinct failures. (2 sub-exceptions)
FAILED array_api_tests/test_fft.py::test_irfft - AssertionError: out.dtype=float64, but should be complex64 [irfft(complex64)]
Falsifying example: test_irfft(
    x=array([0.+0.j, 0.+0.j], dtype=complex64),  # or any other generated value
    data=data(...),
)
Draw 1 (n): None
Draw 2 (axis): 0
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'axis': 0, 'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BkYsAJGBkAAHkABQ==') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_rfftn - ExceptionGroup: Hypothesis found 2 distinct failures. (2 sub-exceptions)
FAILED array_api_tests/test_fft.py::test_irfftn - AssertionError: out.dtype=float64, but should be complex64 [irfftn(complex64)]
Falsifying example: test_irfftn(
    x=array([0.+0.j, 0.+0.j], dtype=complex64),  # or any other generated value
    data=data(...),
)
Draw 1 (axes): None
Draw 2 (s): None
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BkYsAJGBkYAAB+AAU=') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_hfft - AssertionError: out.dtype=float64, but should be complex64 [hfft(float32)]
Falsifying example: test_hfft(
    x=array([0., 0.], dtype=float32),  # or any other generated value
    data=data(...),
)
Draw 1 (n): None
Draw 2 (axis): 0
Draw 3 (norm): 'ortho'
Draw 4 (kwargs): {'axis': 0, 'norm': 'ortho'}

You can reproduce this example by temporarily adding @reproduce_failure('6.88.4', b'AXicY2BgZGJABYwMAABOAAU=') as a decorator on your test case
FAILED array_api_tests/test_fft.py::test_ihfft - ExceptionGroup: Hypothesis found 2 distinct failures. (2 sub-exceptions)
= 10 failed, 1003 passed, 85 skipped, 33 xfailed, 2 xpassed, 41102 warnings in 1724.22s (0:28:44) =

That's because data-apis/array-api-tests#196 got merged 4 days ago. @honno could you have a look? If it's not easy to fix, maybe just add a skip for now?

Improve error message for invalid input

Right now, the error message passing an invalid object to array_namespace is

The input is not a supported array type

It would be more useful for debugging to say which class failed, I think. E.g.:

"generator" is not a supported array type
"map" is not a supported array type
"float" is not a supported array type

Add functions such as `take` to existing Array API spec if not implemented yet?

Should array-api-compat "update" the namespace for existing Array API arrays to the most recent spec? For example:

# Assume that `xp.take` is not implemented in the installed CuPy version
import cupy.array_api as xp
import array_api_compat

X = xp.asarray([1.0, 2.0])
xp = array_api_compat.get_namespace(X)

# Should this always be true?
assert hasattr(xp, "take")

Support for xp.linalg.lu (not yet part of the Array API spec)

Context adding LU factorization to the Array API spec:

Since numpy.linalg.lu does not exist yet (but scipy.linalg.lu does), @rgommers suggested working out an API candidate as part of array-api-compat first by reviewing the API choices and options implemented in various libraries targeting Array API support.

A short term implementation for numpy could probably delegate the work to scipy.linalg.lu in a first iteration.

Based on this work, numpy.linalg could subsequently be extended to directly implement the correct API to be submitted for a future revision of the spec.

Motivation: this is needed to add Array API support to the randomized linear algebra solver for the Principal Component Analysis estimator in scikit-learn:

Non exhaustive list of available implementations:

Related methods in scipy:

AttributeError: module 'array_api_compat.torch' has no attribute 'newaxis'

According to:

the namespace modules should expose an alias to None named newaxis to make indexing code more explicit.

However it seems to be missing in array-api-compat, at least for PyTorch:

>>> import array_api_compat.torch as xp
>>> xp.newaxis is None
Traceback (most recent call last):
  Cell In[6], line 1
    xp.newaxis
AttributeError: module 'array_api_compat.torch' has no attribute 'newaxis'

Note, the same snippet works with numpy:

>>> import array_api_compat.numpy as xp
>>> xp.newaxis is None
True

BUG: torch.std: UnboundLocalError

Found by @mdhaber in scipy/scipy#20285

In [1]: from array_api_compat import array_namespace

In [2]: import torch

In [3]: x = torch.asarray([1, 2, 3., 3, 4.5])

In [4]: x
Out[4]: tensor([1.0000, 2.0000, 3.0000, 3.0000, 4.5000])

In [5]: xp = array_namespace(x)

In [6]: xp
Out[6]: <module 'array_api_compat.torch' from '/Users/lucascolley/programming/array-api-compat/array_api_compat/torch/__init__.py'>

In [7]: xp.std(x, correction=1)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[7], line 1
----> 1 xp.std(x, correction=1)

File ~/programming/array-api-compat/array_api_compat/torch/_aliases.py:396, in std(x, axis, correction, keepdims, **kwargs)
    392     axis = (axis,)
    393 if axis is None:
    394     # torch doesn't support keepdims with axis=None
    395     # (https://github.com/pytorch/pytorch/issues/71209)
--> 396     res = torch.std(x, tuple(range(x.ndim)), correction=_correction, **kwargs)
    397     res = _axis_none_keepdims(res, x.ndim, keepdims)
    398     return res

UnboundLocalError: cannot access local variable '_correction' where it is not associated with a value

Avoid importing numpy.distutils

The follow import statement seems to by default import numpy.distutils which has been deprecated:

     import scipy._lib.array_api_compat.array_api_compat.numpy as array_api_compat_numpy
../../../micromamba/envs/test/lib/python3.11/site-packages/scipy/_lib/array_api_compat/array_api_compat/numpy/__init__.py:1: in <module>
    from numpy import *
../../../micromamba/envs/test/lib/python3.11/site-packages/numpy/__init__.py:331: in __getattr__
    import numpy.distutils as distutils
../../../micromamba/envs/test/lib/python3.11/site-packages/numpy/distutils/__init__.py:31: in <module>
    warnings.warn("\n\n"
E   DeprecationWarning:
E
E     `numpy.distutils` is deprecated since NumPy 1.23.0, as a result
E     of the deprecation of `distutils` itself. It will be removed for
E     Python >= 3.12. For older Python versions it will remain present.
E     It is recommended to use `setuptools < 60.0` for those Python versions.
E     For more details, see:
E       https://numpy.org/devdocs/reference/distutils_status_migration.html

I am guessing it is not needed for array-api-compat and would be great to avoid

JAX support

If you want support for other array libraries, or if you encounter any issues, please open an issue.

Okay, well here it is. I don't know if I'd have time to add it myself in the near future, but it would be great to have.

RFC: `scipy_namespace_for(xp)` helper?

Hello array-api-compat! Really great project and thanks for providing it. After several years of having internal libraries like this one, I have finally been able to switch to array-api-compat in many projects.

I have a suggestion for something that would be a valuable helper while SciPy fully transitions to supporting the array api. Right now, both CuPy and Jax have their own "scipy" submodules, in addition to SciPy itself of course. The issue is, as they are not standard, they are all in different places. CuPy's scipy is in cupyx.scipy and Jax's is in jax.scipy. NumPy doesn't have one, as the actual SciPy is that.

Would it be possible to add a function like scipy_namespace_for(xp) that simply returns the appropriate scipy submodule for a given array api (or raises an error for those that have none, like PyTorch)? This helps with writing array agnostic code. I'm happy to make a PR if this is fine with everyone.

The idea is that the following pattern could then be used:

xp = array_api_compat.array_namespace(x)
spx = array_api_compat.scipy_namespace_for(xp)

# do things

Test failure for `test_multiply` in pytorch-latest CI job

Observed in gh-59 and gh-61 with the same test case:
array_api_tests/test_operators_and_elementwise_functions.py::test_multiply[__imul__(x1, x2)]
just with different values. The reproducers:

FAILED array_api_tests/test_operators_and_elementwise_functions.py::test_multiply[__imul__(x1, x2)] - AssertionError: x1=(2+67138304j), but should be roughly (x1 * x2)=67138308j [__imul__()]
  x1=(9638+9638j), x2=(3483+3483j)
assert False
 +  where False = isclose(2.0, 0.0, 3.4028234663852886e+38)
 +    where 2.0 = (2+67138304j).real
 +    and   0.0 = 67138308j.real
Falsifying example: test_multiply(
    ctx=BinaryParamContext(<__imul__(x1, x2)>),
    data=data(...),
)
Draw 1 (x1): tensor(9638.+9638.j)
Draw 2 (x2): tensor(3483.+3483.j)

You can reproduce this example by temporarily adding @reproduce_failure('6.86.2', b'AXicY2eAA9Vl2JgMvLORmQA8GwLu') as a decorator on your test case

and

FAILED array_api_tests/test_operators_and_elementwise_functions.py::test_multiply[__imul__(x1, x2)] - AssertionError: x1=(-5+92034536j), but should be roughly (x1 * x2)=(-3+92034537j) [__imul__()]
  x1=(15339089+15339090j), x2=(3+3j)
assert False
 +  where False = isclose(-5.0, -3.0, 3.4028234663852886e+38)
 +    where -5.0 = (-5+92034536j).real
 +    and   -3.0 = (-3+92034537j).real
Falsifying example: test_multiply(
    ctx=BinaryParamContext(<__imul__(x1, x2)>),
    data=data(...),
)
Draw 1 (x1): tensor(15339089.+15339090.j)
Draw 2 (x2): tensor(3.+3.j)

You can reproduce this example by temporarily adding @reproduce_failure('6.86.1', b'AXicY2eAgVd8gQhmEAMCMCMzAVPvAqE=') as a decorator on your test case

A comment on gh-59 has a full traceback.

What to do for torch result_type()?

While working on scipy/scipy#18286 and tylerjereddy/scipy#70 to test passing through different array types in scipy.signal.welch() I ran into the same thing Ralf did a few years ago here: pytorch/pytorch#51284

Since that has been open for quite some time, should we add a shim to deal with torch.result_type only accepting numbers/tensors and not types proper? Or should downstream libs deal with this in their own way?

Traceback I saw was:

/home/tyler/python_310_scipy_dev_work/lib/python3.10/site-packages/array_api_compat-1.2-py3.10.egg/array_api_compat/torch/_aliases.py:124: in result_type
    return torch.result_type(x, y)
E   TypeError: result_type() received an invalid combination of arguments - got (Tensor, torch.dtype), but expected one of:
E    * (Tensor tensor, Tensor other)
E         didn't match because some of the arguments have invalid types: (Tensor, !torch.dtype!)
E    * (Number scalar, Tensor tensor)
E         didn't match because some of the arguments have invalid types: (!Tensor!, !torch.dtype!)
E    * (Tensor tensor, Number other)
E         didn't match because some of the arguments have invalid types: (Tensor, !torch.dtype!)
E    * (Number scalar1, Number scalar2)
E         didn't match because some of the arguments have invalid types: (!Tensor!, !torch.dtype!)
        arrays_and_dtypes = (tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]), torch.complex64)
        x          = tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
        xdt        = torch.float32
        y          = torch.complex64
        ydt        = torch.complex64

Should torch.reshape support integer shape?

torch.reshape requires an tuple as the shape:

import torch
import array_api_compat 

x = torch.asarray([1.0, 2.0])
xp = array_api_compat.get_namespace(x)

# works
xp.reshape(x, (-1,))

xp.reshape(x, -1)
# TypeError: reshape(): argument 'shape' (position 2) must be tuple of ints, not int

Note that integer shape works with numpy.array_api:

import numpy.array_api as np
import array_api_compat 

x = np.asarray([1.0, 2.0])
xp = array_api_compat.get_namespace(x)

xp.reshape(x, -1)

Seeking alternatives for setting array values with integer indexing

On a few occasions while using this library, I've bumped against the issue having to set array values using advanced indexing. Here is an example:

import numpy as np
import numpy.array_api as anp

def one_hot_np(array, num_classes):
    n = array.shape[0]
    categorical = np.zeros((n, num_classes))
    categorical[np.arange(n), array] = 1
    return categorical


def one_hot_anp(array, num_classes):
    one_hot = anp.zeros((array.shape[0], num_classes))
    indices = anp.stack(
        (anp.arange(array.shape[0]), anp.reshape(array, (-1,))), axis=-1
    )
    indices = anp.reshape(indices, shape=(-1, indices.shape[-1]))

    for idx in range(indices.shape[0]):
        one_hot[tuple(indices[idx, ...])] = 1

    return one_hot

I'm using the numpy.array_api namespace because it follows the API standard closely.

Is there a different (better) way of setting values of an array using integer (array) indices that adhere to the 2021.12 version of the array API standard?

For the example I gave, I'm aware that I can do something like this (but not with numpy.array_api namespace, as it only supports v2021.12):

import numpy as np
import numpy.array_api as anp

def one_hot(array, num_classes):
    id_arr = anp.eye(num_classes)
    return np.take(id_arr, array, axis=0)

But I have other cases in my codebase that follow the first pattern - looping through array indices and using basic indexing to set array values. For example, using the indices from xp.argsort to mark the top-k values. Is there a better way than looping through the indices?

RFC: `expand_dims` for tuple of axes

Hello all! I've just spent time converting a reasonably large code base to use array-api-compat. I was pleasantly surprised that nearly everything worked, but there was one particular function that didn't map smoothly. And that was expand_dims. The issue is not necessarily the problem of array-api-compat, but I thought I'd start here.

In the array API, expand_dims supports only a single axis (https://data-apis.org/array-api/latest/API_specification/generated/array_api.expand_dims.html) as opposed to a tuple of axes. This is different to NumPy, CuPy, and Jax, which support a tuple of axes. PyTorch, however, supports only a single axis. I don't know the justification for why the array API supports only a single axis as opposed to a tuple, but what it means is that expand_dims no longer works in many places.

In practice, expand_dims is just a light wrapper for reshape, see https://github.com/numpy/numpy/blob/3b246c6488cf246d488bbe5726ca58dc26b6ea74/numpy/lib/_shape_base_impl.py#L594. But I'd really rather not have to write my own version of expand_dims in every library now. Would array_api_compat be willing to provide a non-strict version of expand_dims that still supports a tuple of axes? Or has there been a clear discussion and decision that expand_dims will only support a single axis going forward, effectively making all users of expand_dims copy and paste the NumPy implementation?

Many thanks!

Add CI testing

We need to set up CI. Ideally we should run the test suite here (which is pretty small so far), and also the array-api-tests against NumPy (testing CuPy on CI likely isn't worth the effort).

torch binary operations broken for scalar inputs in `_fix_promotion`

The dtype promotion check in _fix_promotion does not correctly identify scalar inputs, and unconditionally accesses .dtype.
This breaks binary operators with float scalar inputs.

The can be fixed by accessing dtype via getattr with a None default or validating that the input is not a scalar.
Happy to provide a PR.

Minimal repo, in version 1.4, via:

import torch
import numpy
import array_api_compat as aac

aac.__version__ ()

t = torch.arange(10)
n = numpy.arange(10)

numpy.add(n, 1.0)
torch.add(t, 1.0)

aac.get_namespace(n).add(n, 1.0)
aac.get_namespace(t).add(t, 1.0)

Raises:

      9 torch.add(t, 1.0)
     11 aac.get_namespace(n).add(n, 1.0)
---> 12 aac.get_namespace(t).add(t, 1.0)

File ~/ab/main/.conda/lib/python3.10/site-packages/array_api_compat/torch/_aliases.py:91, in _two_arg.<locals>._f(x1, x2, **kwargs)
     89 @wraps(f)
     90 def _f(x1, x2, /, **kwargs):
---> 91     x1, x2 = _fix_promotion(x1, x2)
     92     return f(x1, x2, **kwargs)

File ~/ab/main/.conda/lib/python3.10/site-packages/array_api_compat/torch/_aliases.py:104, in _fix_promotion(x1, x2, only_scalar)
    103 def _fix_promotion(x1, x2, only_scalar=True):
--> 104     if x1.dtype not in _array_api_dtypes or x2.dtype not in _array_api_dtypes:
    105         return x1, x2
    106     # If an argument is 0-D pytorch downcasts the other argument

AttributeError: 'float' object has no attribute 'dtype'

Would expect equivalent behavior to torch.add.

See:
https://gist.github.com/asford/ee688d59f0747a6507b9670a83fa7c47

Should `numpy_array_api_compat` installable?

For testing, I added a pyproject.toml to this repo so I can install it and import it. I can see libraries vendoring this library, but I think it would be nice to have the option to install it as well.

Should numpy_array_api_compat install-able?

Suppress NumPy warnings for special case behaviour

The initial numpy.array_api PR numpy/numpy#18585 had folks happy with keeping NumPy-proper's warnings when spec-compliant operations were being done (usually/always special case behaviour). Giving the flexibility of a separate package, could we instead suppress these warnings? Really my one use case here is array-api-tests, where right now our "daily driver" array module is numpy.array_api which deluges us with warnings that obfuscate other things... we could suppress them on our end tbf, just ugh.

Support for NumPy 2.0

To support NumPy 2.0, we should

  • Add CI to test 2.0 nightlies. We can use python -m pip install --pre --upgrade --extra-index https://pypi.anaconda.org/scientific-python-nightly-wheels/simple numpy.

  • Decide if we want to support just NumPy 2.0 or both NumPy 2.0 and NumPy 1.26.

  • If we decide to support both, we should check if any of the wrappers here will break with 2.0 having fixed the underlying behavior. Otherwise, I don't think it's that important to wrap conditionally, unless there is a good reason to remove the wrapper when it isn't needed for performance.

  • If we aren't supporting both we can remove a good number of wrappers.

Personally I think we should support both, at least for the time being.

raise TypeError in get_namespace

This is a very minor point, but it has just tripped me up. The get_namespace helper could raise TypeError instead of ValueError when the arguments are of incompatible or inconsistent types, particularly since the values of the inputs are never inspected.

For reference:

exception TypeError

Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. [...]

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.

exception ValueError

Raised when an operation or function receives an argument that has the right type but an inappropriate value [...].

Pass keyword arguments through to wrapped functions

@rgommers mentioned this in the consortium meeting today, and I realized that this isn't actually the case. But it should be straightforward to add **kwargs to the wrappers and pass it through. For instance, np.asarray has the order argument and it should be possible to use it with array_api_compat.numpy.asarray.

Another slightly related point is that we should remove the wrapping for the pure rename aliases. The only reason I used wrappers there was to avoid the duplication between numpy and cupy, but this isn't really a big deal. A reason to fix this is that something like array_api_compat.numpy.asin isn't actually a ufunc, but it could be if we just set asin = np.arcsin.

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.