Skip to content

DOC: Added explanation document on interoperability - #20185

Merged
mattip merged 5 commits into
numpy:mainfrom
melissawm:add-interop-doc
Feb 2, 2022
Merged

mattip merged 5 commits into
numpy:mainfrom
melissawm:add-interop-doc

Conversation

@melissawm

@melissawm melissawm commented Oct 25, 2021 •

Copy link
Copy Markdown
Member

This document is an explanation on current interoperability features for NumPy, including examples with Pandas, CuPy, Dask and PyTorch.

It is very likely that this is incomplete or inaccurate, as I was learning while writing it, so feel free to suggest changes. I have added this document to the skip list in refguide_check.py because of the code involving other libraries which are not dependencies to our documentation (and don't need to be).

EDIT: rendered page here

@honno

honno commented Oct 28, 2021 •

Copy link
Copy Markdown
Member

Read this now—as a newbie on the existing interop features, I think the page does a great job in both outlining the avenues available and going through how other libraries actually use them.

It took me a second to appreciate how __array_interface__ and __array_struct__ are objects and all the other related dunder attributes are callables. Would it 1) help 2) be appropriate to replace all mention of the dunder functions with the () parenthesis at the end? e.g. replace all instances of __array__ with __array__(). I imagine this might look "ugly" or go against existing convention. Minor nitpick in any case heh.

@melissawm

Copy link
Copy Markdown
Member Author

Thanks @honno - indeed I think that's valuable, will do!

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an excellent document, very nicely done @melissawm !

One high-level thing that stood out to me in the discussion surrounding __array_ufunc__ vs. __array_function__. I feel the discussion here assumes that the reader has a firm grasp on what the difference between a ufunc and a "non-ufunc" numpy function is, which is perhaps not a safe assumption. One possible remedy could be to use the np.mean(np.exp) example to point out this distinction more explicitly (i.e. exp is a ufunc but mean is not).

Other than that I only had nits, mostly related to preferring internal sphinx/intersphinx links to external links for futureproofing. Definitely not a blocker though!

@rgommers

rgommers commented Nov 2, 2021

Copy link
Copy Markdown
Member

I feel the discussion here assumes that the reader has a firm grasp on what the difference between a ufunc and a "non-ufunc" numpy function is, which is perhaps not a safe assumption

Definitely not a safe assumption:)

@rgommers rgommers left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @melissawm, this is a very nice overview. I added some high level comments. One big picture comment on the whole doc: it would be good to make a better conceptual distinction between:

  1. Methods of turning a foreign object into an ndarray (buffer protocol et al.)
  2. Methods of deferring execution from a NumPy function to another array library (__array_ufunc__ et al.)

Those are very different things, and right now they are all called "protocol" and mixed together.

Finally, it would be appropriate to mention __array_wrap__, __array_finalize__ & co. That is a third type of feature set, meant to (a) use the numpy function implementation, and (b) then turn the return value back into an instance of the foreign object.

array-like object;
- ``__array__()``: a method returning the NumPy ndarray view of an array-like
object;
- ``__array_struct__``: a ``PyCapsule`` containing a pointer to a

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__array_struct__ is basically obsolete, I'd prefer to either remove it or otherwise to at least add in a note that it's legacy and should not be used for new code. Use the buffer protocol instead.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it would work better to add this note in the main array interface protocol page page, and not even mention it here.

The ``__array__`` protocol
~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``__array__`` protocol acts as a dispatch mechanism and ensures that any

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a dispatch mechanism I'd say. Dispatching means something like "deferring execution to an implementation elsewhere". That is not the case here. Instead let's just say it's a way to request the object to turn itself into a np.ndarray instance. The original object, and any attributes/behavior it may have had, is lost.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK - I rephrased it, let me know if it reads better.

@melissawm

melissawm commented Nov 2, 2021 •

Copy link
Copy Markdown
Member Author

Great - thanks for the reviews, folks! I will address those shortly.

Finally, it would be appropriate to mention __array_wrap__, __array_finalize__ & co. That is a third type of feature set, meant to (a) use the numpy function implementation, and (b) then turn the return value back into an instance of the foreign object.

I'll do a little research but they didn't turn up in my initial readings. Do you know of any sources for that besides the API docs?

@rgommers

rgommers commented Nov 2, 2021

Copy link
Copy Markdown
Member

@rgommers

rgommers commented Nov 2, 2021

Copy link
Copy Markdown
Member

@melissawm
melissawm marked this pull request as draft November 9, 2021 21:03
@leofang

leofang commented Nov 12, 2021

Copy link
Copy Markdown
Contributor

cc: @kmaehashi @emcastillo for vis

@melissawm
melissawm marked this pull request as ready for review November 23, 2021 15:28
@melissawm

Copy link
Copy Markdown
Member Author

I think this is ready for a second round of reviews.

@rgommers rgommers left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description of __array_wrap__ is a little misleading (that's the fault of the docs you reference). It focuses on "subtypes", which is a word to avoid anyway because with type annotations in Python 3 it now has a different meaning. But really subclasses/subtypes are not needed for this. Any object can implement this and it'll be called at the end - allowing "resetting" the output type to the correct container. A small demo to demonstrate:

>>> import torch
>>> t = torch.arange(4)
>>> np.abs(t)
tensor([0, 1, 2, 3])
>>> 
>>> wrap = lambda self, array: np.asarray(array)
>>> torch.Tensor.__array_wrap__ = wrap
>>> t = torch.arange(4)
>>> np.abs(t)
array([0, 1, 2, 3])

So PyTorch implements __array_wrap__ to be able to get tensors back. And if we modify it, we see that it's a simple Python method that does whatever you put inside. And torch.Tensor is not a subclass/subtype of numpy.ndarray.

@melissawm

Copy link
Copy Markdown
Member Author

Ah - thanks for that note, makes sense, I'll update accordingly. Do you think the current structure makes the distinctions between the groups of features that you had mentioned before clearer? Happy to re-work if this is not yet sufficient.

@rgommers

Copy link
Copy Markdown
Member

Do you think the current structure makes the distinctions between the groups of features that you had mentioned before clearer? Happy to re-work if this is not yet sufficient.

I think that looks quite good. Overall this is close to ready I'd say.

>>> t = torch.arange(4)
>>> np.abs(t)
tensor([0, 1, 2, 3])
>>> wrap = lambda self, array: np.asarray(array)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From this line on it's best to delete the example (only keep until tensor([0, 1, 2, 3])). I included it to show you that it really was __array_wrap__ that is responsible for creating the tensor return type, but now the example looks like this is somehow normal usage.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the docstring get a pragma to be ignored in doctests? I don't think we want to import tensorflow

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added this page to the refguide exclude list as none of it is very useful to run as doctests.

.. note::

:obj:`__array_struct__` is considered legacy and should not be used for new
code. Use the :py:doc:`buffer protocol <c-api/buffer>` instead.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we deprecate it? I think also ndarray.dlpack could be mentioned as an alternative, although I see it is not part of the documentation ...

Checking for uses of __array_struct__ I found only pygame, and opened pygame/pygame#2949 to ask about removing it

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds like a good idea to me

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I add a deprecation note here? Or wait until it is actually marked for deprecation?

protocol, it defines a way to access the contents of a NumPy array from other
C extensions.
3. The ``__array__()`` method, which asks an arbitrary object to convert
itself into an array.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add the __dlpack__() method

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, that is in a different section

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean adding a mention of __dlpack()__ in the arrays.interface doc? I can at least add a link to https://data-apis.org/array-api/latest/design_topics/data_interchange.html#dlpack-support

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe leave it out for now. I thought we had a tracking issue for finishing dlpack, including documentation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So long we don't have first-class consumer API, it doesn't really make sense to expose it any case. This should be added as part of making that consumer API first-class.

@mattip

mattip commented Feb 2, 2022

Copy link
Copy Markdown
Member

Let's put this in as-is and iterate on it as the 1.23 release progresses

@mattip
mattip merged commit 7a038c8 into numpy:main Feb 2, 2022
@mattip

mattip commented Feb 2, 2022

Copy link
Copy Markdown
Member

Thanks @melissawm

@astrojuanlu

astrojuanlu commented Feb 3, 2022 •

Copy link
Copy Markdown
Contributor

Is there a place where the dev docs (the main branch) get deployed? For now, downloading the CircleCI artifact for later :)

@Mukulikaa

Copy link
Copy Markdown
Contributor

Hey, @astrojuanlu, it's at https://numpy.org/devdocs/user/basics.interoperability.html.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants