<div dir="ltr"><div>Hi all,</div><div><br></div><div>Here is a NEP, written together with Stephan Hoyer and Aaron Meurer, for discussion on adoption of the array API standard (<a href="https://data-apis.github.io/array-api/latest/">https://data-apis.github.io/array-api/latest/</a>). This will add a new <code>numpy.array_api</code> submodule containing that standardized API. The main purpose of this API is to be able to write code that is 
portable to other array/tensor libraries like CuPy, PyTorch, JAX, 
TensorFlow, Dask, and MXNet.</div><div>

<p>We expect this NEP to remain in draft state for quite a while, while 
we're gaining experience with using it in downstream libraries, discuss 
adding it to other array libraries, and finishing some of the loose ends
 (e.g., specifications for linear algebra functions that aren't merged 
yet, see <a href="https://github.com/data-apis/array-api/pulls">https://github.com/data-apis/array-api/pulls</a>) in the API standard itself.</p>
<p>See <a rel="nofollow" href="https://mail.python.org/pipermail/numpy-discussion/2020-November/081181.html">https://mail.python.org/pipermail/numpy-discussion/2020-November/081181.html</a> for an initial discussion about this topic.</p><p>Please keep high-level discussion here and detailed comments on <a href="https://github.com/numpy/numpy/pull/18456">https://github.com/numpy/numpy/pull/18456</a>. Also, you can access a rendered version of the NEP from that PR (see PR description for how), which may be helpful.</p></div><div>Cheers,<br></div><div>Ralf<br></div><div><br></div><div><br></div><div>Abstract<br>--------<br><br>We propose to adopt the `Python array API standard`_, developed by the<br>`Consortium for Python Data API Standards`_. Implementing this as a separate<br>new namespace in NumPy will allow authors of libraries which depend on NumPy<br>as well as end users to write code that is portable between NumPy and all<br>other array/tensor libraries that adopt this standard.<br><br>.. note::<br><br>    We expect that this NEP will remain in a draft state for quite a while.<br>    Given the large scope we don't expect to propose it for acceptance any<br>    time soon; instead, we want to solicit feedback on both the high-level<br>    design and implementation, and learn what needs describing better in this<br>    NEP or changing in either the implementation or the array API standard<br>    itself.<br><br><br>Motivation and Scope<br>--------------------<br><br>Python users have a wealth of choice for libraries and frameworks for<br>numerical computing, data science, machine learning, and deep learning. New<br>frameworks pushing forward the state of the art in these fields are appearing<br>every year. One unintended consequence of all this activity and creativity<br>has been fragmentation in multidimensional array (a.k.a. tensor) libraries -<br>which are the fundamental data structure for these fields. Choices include<br>NumPy, Tensorflow, PyTorch, Dask, JAX, CuPy, MXNet, and others.<br><br>The APIs of each of these libraries are largely similar, but with enough<br>differences that it’s quite difficult to write code that works with multiple<br>(or all) of these libraries. The array API standard aims to address that<br>issue, by specifying an API for the most common ways arrays are constructed<br>and used. The proposed API is quite similar to NumPy's API, and deviates mainly<br>in places where (a) NumPy made design choices that are inherently not portable<br>to other implementations, and (b) where other libraries consistently deviated<br>from NumPy on purpose because NumPy's design turned out to have issues or<br>unnecessary complexity.<br><br>For a longer discussion on the purpose of the array API standard we refer to<br>the `Purpose and Scope section of the array API standard <<a href="https://data-apis.github.io/array-api/latest/purpose_and_scope.html">https://data-apis.github.io/array-api/latest/purpose_and_scope.html</a>>`__<br>and the two blog posts announcing the formation of the Consortium [1]_ and<br>the release of the first draft version of the standard for community review [2]_.<br><br>The scope of this NEP includes:<br><br>- Adopting the 2021 version of the array API standard<br>- Adding a separate namespace, tentatively named ``numpy.array_api``<br>- Changes needed/desired outside of the new namespace, for example new dunder<br>  methods on the ``ndarray`` object<br>- Implementation choices, and differences between functions in the new<br>  namespace with those in the main ``numpy`` namespace<br>- A new array object conforming to the array API standard<br>- Maintenance effort and testing strategy<br>- Impact on NumPy's total exposed API surface and on other future and<br>  under-discussion design choices<br>- Relation to existing and proposed NumPy array protocols<br>  (``__array_ufunc__``, ``__array_function__``, ``__array_module__``).<br>- Required improvements to existing NumPy functionality<br><br>Out of scope for this NEP are:<br><br>- Changes in the array API standard itself. Those are likely to come up<br>  during review of this NEP, but should be upstreamed as needed and this NEP<br>  subsequently updated.<br><br><br>Usage and Impact<br>----------------<br><br>*This section will be fleshed out later, for now we refer to the use cases given<br>in* `the array API standard Use Cases section <<a href="https://data-apis.github.io/array-api/latest/use_cases.html">https://data-apis.github.io/array-api/latest/use_cases.html</a>>`__<br><br>In addition to those use cases, the new namespace contains functionality that<br>is widely used and supported by many array libraries. As such, it is a good<br>set of functions to teach to newcomers to NumPy and recommend as "best<br>practice". That contrasts with NumPy's main namespace, which contains many<br>functions and objects that have been superceded or we consider mistakes - but<br>that we can't remove because of backwards compatibility reasons.<br><br>The usage of the ``numpy.array_api`` namespace by downstream libraries is<br>intended to enable them to consume multiple kinds of arrays, *without having<br>to have a hard dependency on all of those array libraries*:<br><br>.. image:: _static/nep-0047-library-dependencies.png<br><br>Adoption in downstream libraries<br>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br><br>The prototype implementation of the ``array_api`` namespace will be used with<br>SciPy, scikit-learn and other libraries of interest that depend on NumPy, in<br>order to get more experience with the design and find out if any important<br>parts are missing.<br><br>The pattern to support multiple array libraries is intended to be something<br>like::<br><br>    def somefunc(x, y):<br>        # Retrieves standard namespace. Raises if x and y have different<br>        # namespaces.  See Appendix for possible get_namespace implementation<br>        xp = get_namespace(x, y)<br>        out = xp.mean(x, axis=0) + 2*xp.std(y, axis=0)<br>        return out<br><br>The ``get_namespace`` call is effectively the library author opting in to<br>using the standard API namespace, and thereby explicitly supporting<br>all conforming array libraries.<br><br><br>The ``asarray`` / ``asanyarray`` pattern<br>````````````````````````````````````````<br><br>Many existing libraries use the same ``asarray`` (or ``asanyarray``) pattern<br>as NumPy itself does; accepting any object that can be coerced into a ``np.ndarray``.<br>We consider this design pattern problematic - keeping in mind the Zen of<br>Python, *"explicit is better than implicit"*, as well as the pattern being<br>historically problematic in the SciPy ecosystem for ``ndarray`` subclasses<br>and with over-eager object creation. All other array/tensor libraries are<br>more strict, and that works out fine in practice. We would advise authors of<br>new libraries to avoid the ``asarray`` pattern. Instead they should either<br>accept just NumPy arrays or, if they want to support multiple kinds of<br>arrays, check if the incoming array object supports the array API standard<br>by checking for ``__array_namespace__`` as shown in the example above.<br><br>Existing libraries can do such a check as well, and only call ``asarray`` if<br>the check fails. This is very similar to the ``__duckarray__`` idea in<br>:ref:`NEP30`.<br><br><br>.. _adoption-application-code:<br><br>Adoption in application code<br>~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br><br>The new namespace can be seen by end users as a cleaned up and slimmed down<br>version of NumPy's main namespace. Encouraging end users to use this<br>namespace like::<br><br>    import numpy.array_api as xp<br><br>    x = xp.linspace(0, 2*xp.pi, num=100)<br>    y = xp.cos(x)<br><br>seems perfectly reasonable, and potentially beneficial - users get offered only<br>one function for each purpose (the one we consider best-practice), and they<br>then write code that is more easily portable to other libraries.<br><br><br>Backward compatibility<br>----------------------<br><br>No deprecations or removals of existing NumPy APIs or other backwards<br>incompatible changes are proposed.<br><br><br>High-level design<br>-----------------<br><br>The array API standard consists of approximately 120 objects, all of which<br>have a direct NumPy equivalent. This figure shows what is included at a high level:<br><br>.. image:: _static/nep-0047-scope-of-array-API.png<br><br>The most important changes compared to what NumPy currently offers are:<br><br>- A new array object which:<br><br>    - conforms to the casting rules and indexing behaviour specified by the<br>      standard,<br>    - does not have methods other than dunder methods,<br>    - does not support the full range of NumPy indexing behaviour. Advanced<br>      indexing with integers is not supported. Only boolean indexing<br>      with a single (possibly multi-dimensional) boolean array is supported.<br>      An indexing expression that selects a single element returns a 0-D array<br>      rather than a scalar.<br><br>- Functions in the ``array_api`` namespace:<br><br>    - do not accept ``array_like`` inputs, only NumPy arrays and Python scalars<br>    - do not support ``__array_ufunc__`` and ``__array_function__``,<br>    - use positional-only and keyword-only parameters in their signatures,<br>    - have inline type annotations,<br>    - may have minor changes to signatures and semantics of individual<br>      functions compared to their equivalents already present in NumPy,<br>    - only support dtype literals, not format strings or other ways of<br>      specifying dtypes<br><br>- DLPack_ support will be added to NumPy,<br>- New syntax for "device support" will be added, through a ``.device``<br>  attribute on the new array object, and ``device=`` keywords in array creation<br>  functions in the ``array_api`` namespace,<br>- Casting rules that differ from those NumPy currently has. Output dtypes can<br>  be derived from input dtypes (i.e. no value-based casting), and 0-D arrays<br>  are treated like >=1-D arrays.<br>- Not all dtypes NumPy has are part of the standard. Only boolean, signed and<br>  unsigned integers, and floating-point dtypes up to ``float64`` are supported.<br>  Complex dtypes are expected to be added in the next version of the standard.<br>  Extended precision, string, void, object and datetime dtypes, as well as<br>  structured dtypes, are not included.<br><br>Improvements to existing NumPy functionality that are needed include:<br><br>- Add support for stacks of matrices to some functions in ``numpy.linalg``<br>  that are currently missing such support.<br>- Add the ``keepdims`` keyword to ``np.argmin`` and ``np.argmax``.<br>- Add a "never copy" mode to ``np.asarray``.<br><br><br>Functions in the ``array_api`` namespace<br>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br><br>Let's start with an example of a function implementation that shows the most<br>important differences with the equivalent function in the main namespace::<br><br>    def max(x: array, /, *,<br>            axis: Optional[Union[int, Tuple[int, ...]]] = None,<br>            keepdims: bool = False<br>        ) -> array:<br>        """<br>        Array API compatible wrapper for :py:func:`np.max <numpy.max>`.<br>        """<br>        return np.max._implementation(x, axis=axis, keepdims=keepdims)<br><br>This function does not accept ``array_like`` inputs, only ``ndarray``. There<br>are multiple reasons for this. Other array libraries all work like this.<br>Letting the user do coercion of lists, generators, or other foreign objects<br>separately results in a cleaner design with less unexpected behaviour.<br>It's higher-performance - less overhead from ``asarray`` calls. Static typing<br>is easier. Subclasses will work as expected. And the slight increase in verbosity<br>because users have to explicitly coerce to ``ndarray`` on rare occasions<br>seems like a small price to pay.<br><br>This function does not support ``__array_ufunc__`` nor ``__array_function__``.<br>These protocols serve a similar purpose as the array API standard module itself,<br>but through a different mechanisms. Because only ``ndarray`` instances are accepted,<br>dispatching via one of these protocols isn't useful anymore.<br><br>This function uses positional-only parameters in its signature. This makes code<br>more portable - writing ``max(x=x, ...)`` is no longer valid, hence if other<br>libraries call the first parameter ``input`` rather than ``x``, that is fine.<br>The rationale for keyword-only parameters (not shown in the above example) is<br>two-fold: clarity of end user code, and it being easier to extend the signature<br>in the future with keywords in the desired order.<br><br>This function has inline type annotations. Inline annotations are far easier to<br>maintain than separate stub files. And because the types are simple, this will<br>not result in a large amount of clutter with type aliases or unions like in the<br>current stub files NumPy has.<br><br><br>DLPack support for zero-copy data interchange<br>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br><br>The ability to convert one kind of array into another kind is valuable, and<br>indeed necessary when downstream libraries want to support multiple kinds of<br>arrays. This requires a well-specified data exchange protocol. NumPy already<br>supports two of these, namely the buffer protocol (i.e., PEP 3118), and<br>the ``__array_interface__`` (Python side) / ``__array_struct__`` (C side)<br>protocol. Both work similarly, letting the "producer" describe how the data<br>is laid out in memory so the "consumer" can construct its own kind of array<br>with a view on that data.<br><br>DLPack works in a very similar way. The main reasons to prefer DLPack over<br>the options already present in NumPy are:<br><br>1. DLPack is the only protocol with device support (e.g., GPUs using CUDA or<br>   ROCm drivers, or OpenCL devices). NumPy is CPU-only, but other array<br>   libraries are not. Having one protocol per device isn't tenable, hence<br>   device support is a must.<br>2. Widespread support. DLPack has the widest adoption of all protocols, only<br>   NumPy is missing support. And the experiences of other libraries with it<br>   are positive. This contrasts with the protocols NumPy does support, which<br>   are used very little - when other libraries want to interoperate with<br>   NumPy, they typically use the (more limited, and NumPy-specific)<br>   ``__array__`` protocol.<br><br>Adding support for DLPack to NumPy entails:<br><br>- Adding a ``ndarray.__dlpack__`` method<br>- Adding a ``from_dlpack`` function, which takes as input an object<br>  supporting ``__dlpack__``, and returns an ``ndarray``.<br><br>DLPack is currently a ~200 LoC header, and is meant to be included directly, so<br>no external dependency is needed. Implementation should be straightforward.<br><br><br>Syntax for device support<br>~~~~~~~~~~~~~~~~~~~~~~~~~<br><br>NumPy itself is CPU-only, so it clearly doesn't have a need for device support.<br>However, other libraries (e.g. TensorFlow, PyTorch, JAX, MXNet) support<br>multiple types of devices: CPU, GPU, TPU, and more exotic hardware.<br>To write portable code on systems with multiple devices, it's often necessary<br>to create new arrays on the same device as some other array, or check that<br>two arrays live on the same device. Hence syntax for that is needed.<br><br>The array object will have a ``.device`` attribute which enables comparing<br>devices of different arrays (they only should compare equal if both arrays are<br>from the same library and it's the same hardware device). Furthermore,<br>``device=`` keywords in array creation functions are needed. For example::<br><br>    def empty(shape: Union[int, Tuple[int, ...]], /, *,<br>              dtype: Optional[dtype] = None,<br>              device: Optional[device] = None) -> array:<br>        """<br>        Array API compatible wrapper for :py:func:`np.empty <numpy.empty>`.<br>        """<br>        return np.empty(shape, dtype=dtype, device=device)<br><br>The implementation for NumPy may be as simple as setting the device attribute to<br>the string ``'cpu'`` and raising an exception if array creation functions<br>encounter any other value.<br><br><br>Dtypes and casting rules<br>~~~~~~~~~~~~~~~~~~~~~~~~<br><br>The supported dtypes in this namespace are boolean, 8/16/32/64-bit signed and<br>unsigned integer, and 32/64-bit floating-point dtypes. These will be added to<br>the namespace as dtype literals with the expected names (e.g., ``bool``,<br>``uint16``, ``float64``).<br><br>The most obvious omissions are the complex dtypes. The rationale for the lack<br>of complex support in the first version of the array API standard is that several<br>libraries (PyTorch, MXNet) are still in the process of adding support for<br>complex dtypes. The next version of the standard is expected to include ``complex64``<br>and ``complex128`` (see `this issue <<a href="https://github.com/data-apis/array-api/issues/102">https://github.com/data-apis/array-api/issues/102</a>>`__<br>for more details).<br><br>Specifying dtypes to functions, e.g. via the ``dtype=`` keyword, is expected<br>to only use the dtype literals. Format strings, Python builtin dtypes, or<br>string representations of the dtype literals are not accepted - this will<br>improve readability and portability of code at little cost.<br><br>Casting rules are only defined between different dtypes of the same kind. The<br>rationale for this is that mixed-kind (e.g., integer to floating-point)<br>casting behavior differs between libraries. NumPy's mixed-kind casting<br>behavior doesn't need to be changed or restricted, it only needs to be<br>documented that if users use mixed-kind casting, their code may not be<br>portable.<br><br>.. image:: _static/nep-0047-casting-rules-lattice.png<br><br>*Type promotion diagram. Promotion between any two types is given by their<br>join on this lattice. Only the types of participating arrays matter, not<br>their values. Dashed lines indicate that behaviour for Python scalars is<br>undefined on overflow. Boolean, integer and floating-point dtypes are not<br>connected, indicating mixed-kind promotion is undefined.*<br><br>The most important difference between the casting rules in NumPy and in the<br>array API standard is how scalars and 0-dimensional arrays are handled. In<br>the standard, array scalars do not exist and 0-dimensional arrays follow the<br>same casting rules as higher-dimensional arrays.<br><br>See the `Type Promotion Rules section of the array API standard <<a href="https://data-apis.github.io/array-api/latest/API_specification/type_promotion.html">https://data-apis.github.io/array-api/latest/API_specification/type_promotion.html</a>>`__<br>for more details.<br><br>.. note::<br><br>    It is not clear what the best way is to support the different casting rules<br>    for 0-dimensional arrays and no value-based casting. One option may be to<br>    implement this second set of casting rules, keep them private, mark the<br>    array API functions with a private attribute that says they adhere to<br>    these different rules, and let the casting machinery check whether for<br>    that attribute.<br><br>    This needs discussion.<br><br><br>Indexing<br>~~~~~~~~<br><br>An indexing expression that would return a scalar with ``ndarray``, e.g.<br>``arr_2d[0, 0]``, will return a 0-D array with the new array object. There are<br>several reasons for that: array scalars are largely considered a design mistake<br>which no other array library copied; it works better for non-CPU libraries<br>(typically arrays can live on the device, scalars live on the host); and it's<br>simply a consistent design. To get a Python scalar out of a 0-D array, one can<br>simply use the builtin for the type, e.g. ``float(arr_0d)``.<br><br>The other `indexing modes in the standard <<a href="https://data-apis.github.io/array-api/latest/API_specification/indexing.html">https://data-apis.github.io/array-api/latest/API_specification/indexing.html</a>>`__<br>do work largely the same as they do for ``numpy.ndarray``. One noteworthy<br>difference is that clipping in slice indexing (e.g., ``a[:n]`` where ``n`` is<br>larger than the size of the first axis) is unspecified behaviour, because<br>that kind of check can be expensive on accelerators.<br><br>The lack of advanced indexing, and boolean indexing being limited to a single<br>n-D boolean array, is due to those indexing modes not being suitable for all<br>types of arrays or JIT compilation. Their absence does not seem to be<br>problematic; if a user or library author wants to use them, they can do so<br>through zero-copy conversion to ``numpy.ndarray``. This will signal correctly<br>to whomever reads the code that it is then NumPy-specific rather than portable<br>to all conforming array types.<br><br><br><br>The array object<br>~~~~~~~~~~~~~~~~<br><br>The array object in the standard does not have methods other than dunder<br>methods. The rationale for that is that not all array libraries have methods<br>on their array object (e.g., TensorFlow does not). It also provides only a<br>single way of doing something, rather than have functions and methods that<br>are effectively duplicate.<br><br>Mixing operations that may produce views (e.g., indexing, ``nonzero``)<br>in combination with mutation (e.g., item or slice assignment) is<br>`explicitly documented in the standard to not be supported <<a href="https://data-apis.github.io/array-api/latest/design_topics/copies_views_and_mutation.html">https://data-apis.github.io/array-api/latest/design_topics/copies_views_and_mutation.html</a>>`__.<br>This cannot easily be prohibited in the array object itself; instead this will<br>be guidance to the user via documentation.<br><br>The standard current does not prescribe a name for the array object itself.<br>We propose to simply name it ``ndarray``. This is the most obvious name, and<br>because of the separate namespace should not clash with ``numpy.ndarray``.<br><br><br>Implementation<br>--------------<br><br>.. note::<br><br>    This section needs a lot more detail, which will gradually be added when<br>    the implementation progresses.<br><br>A prototype of the ``array_api`` namespace can be found in<br><a href="https://github.com/data-apis/numpy/tree/array-api/numpy/_array_api">https://github.com/data-apis/numpy/tree/array-api/numpy/_array_api</a>.<br>The docstring in its ``__init__.py`` has notes on completeness of the<br>implementation. The code for the wrapper functions also contains ``# Note:``<br>comments everywhere there is a difference with the NumPy API.<br>Two important parts that are not implemented yet are the new array object and<br>DLPack support. Functions may need changes to ensure the changed casting rules<br>are respected.<br><br>The array object<br>~~~~~~~~~~~~~~~~<br><br>Regarding the array object implementation, we plan to start with a regular<br>Python class that wraps a ``numpy.ndarray`` instance. Attributes and methods<br>can forward to that wrapped instance, applying input validation and<br>implementing changed behaviour as needed.<br><br>The casting rules are probably the most challenging part. The in-progress<br>dtype system refactor (NEPs 40-43) should make implementing the correct casting<br>behaviour easier - it is already moving away from value-based casting for<br>example.<br><br><br>The dtype objects<br>~~~~~~~~~~~~~~~~~<br><br>We must be able to compare dtypes for equality, and expressions like these must<br>be possible::<br><br>    np.array_api.some_func(..., dtype=x.dtype)<br><br>The above implies it would be nice to have ``np.array_api.float32 ==<br>np.array_api.ndarray(...).dtype``.<br><br>Dtypes should not be assumed to have a class hierarchy by users, however we are<br>free to implement it with a class hierarchy if that's convenient. We considered<br>the following options to implement dtype objects:<br><br>1. Alias dtypes to those in the main namespace. E.g., ``np.array_api.float32 =<br>   np.float32``.<br>2. Make the dtypes instances of ``np.dtype``. E.g., ``np.array_api.float32 =<br>   np.dtype(np.float32)``.<br>3. Create new singleton classes with only the required methods/attributes<br>   (currently just ``__eq__``).<br><br>It seems like (2) would be easiest from the perspective of interacting with<br>functions outside the main namespace. And (3) would adhere best to the<br>standard.<br><br>TBD: the standard does not yet have a good way to inspect properties of a<br>dtype, to ask questions like "is this an integer dtype?". Perhaps this is easy<br>enough to do for users, like so::<br><br>    def _get_dtype(dt_or_arr):<br>        return dt_or_arr.dtype if hasattr(dt_or_arr, 'dtype') else dt_or_arr<br><br>    def is_floating(dtype_or_array):<br>        dtype = _get_dtype(dtype_or_array)<br>        return dtype in (float32, float64)<br><br>    def is_integer(dtype_or_array):<br>        dtype = _get_dtype(dtype_or_array)<br>        return dtype in (uint8, uint16, uint32, uint64, int8, int16, int32, int64)<br><br>However it could make sense to add to the standard. Note that NumPy itself<br>currently does not have a great for asking such questions, see<br>`gh-17325 <<a href="https://github.com/numpy/numpy/issues/17325">https://github.com/numpy/numpy/issues/17325</a>>`__.<br><br><br></div></div>