-
Notifications
You must be signed in to change notification settings - Fork 52
DLPack and readonly/immutable arrays #191
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
Comments
Just a drop-by comment (on my cell): CuPy currently does not support the readonly flag and does not have any plan afaik. |
Thanks for the summary Sebastian!
Let me add one other example you gave to make it more concrete: an ndarray that's backed by a HDF5 file opened in read-only mode. There's other ways to get read-only arrays (
I think you wrote this with a certain scenario in mind, but just to be sure: this is not the case in general. There are in-place operators, and item and slice assignment is supported. Also, DLPack is a memory sharing protocol, and there's in principle nothing that forbids writing to that shared memory. The only thing the array API says is:
I agree, this is not ideal. It's also very much nontrivial to implement (see, e.g., pytorch/pytorch#44027). For PyTorch it may still come at least, for JAX and TensorFlow I don't think there's any chance of that. So given that this doesn't exist in most libraries, the options are:
Import as read-only is possible for NumPy, but not for PyTorch - so it's not a general solution. Always copy goes against the main purpose of the protocol I think.
This makes sense to me, in particular for arrays that are backed by memory-mapped files. There's other cases here for other libraries, like lazy data structures. If the protocol is for in-memory data sharing, the data should be in memory. That does still leave the question if the copy should be made by the library, or if the library should raise and make the user do it. |
Dask also doesn't quite support it, right? It's only able to hold numpy arrays with the writeable flag set, but there's no support at the And even in NumPy it's a fairly niche feature imho - I'd say the "open a file in read-only mode" is the main use case. It's important enough for people that do a lot of their work with HDF5/NetCDF files to carefully consider, but I'd not say this is an "ecosystem wide user problem".
This would not help much compared to the situation now. Take a library like PyTorch, what is it supposed to do when it sees a read-only bit? It has no way to create read-only tensors, so it still has exactly the same set of choices 1-4 as I listed above. Same for JAX - it only has one kind of array, so nothing changes. |
DLPack support was removed from the specification for Concerns are still applicable for the buffer protocol and its support for "readonly". However, it would not seem that there's anything further we need to address in the spec. If there is, feel free to reopen this issue to continue the discussion. |
We had some more recent discussion in a NumPy community meeting, and I think that aligned with the outcome here - removing DLPack support from
Good point. Since it's older, there are no/fewer concerns about the readonly behavior of the buffer protocol, but yes it's a potential footgun still. Anyway that existed for a long time before, so I'm happy to leave that as is and leave it up to libraries to deal with the readonly flag by raising a warning, an exception or by ignoring it as they see fit. |
Reopen this issue to address readonly tensors. As discussed in the Jan-6-2022 meeting, it is preferable to still export readonly tensors and let the consumer decide how to handle in some way. So, the above comment
would not be fully applicable. The exporter should not raise. This issue will close numpy/numpy#20742. |
Agreed, with "libraries" I meant importers. The buffer protocol has a readonly flag, so there's no problem for exporters. |
I have been reading lengthy discussions about the problems of sharing buffers between different array libraries: all points are very much appreciated. It seems to me that the fundamental cause of the issue boils down to "incomplete" design choices of these libraries when considering the problem of buffer sharing, even when their design may be complete within the objectives of a particular library. I have a couple of suggestions how to alleviate this without requiring changes in the design of the libraries but rather introducing an intention bit to For instance, PyTorch tensors are always writable that enables efficient usage of computational resources, however, practice has shown that such a design is far from optimal as there exists use cases also within the objectives of PyTorch where one would wish to set PyTorch tensors non-writable. As an example, the indices of sparse tensors must be immutable by definition but currently it is fairly easy to crash Python as the indices can be arbitrarily mutated by users or as some side-effect of a software bug (see e.g. pytorch/pytorch#44027 (comment)). Jax represents another side of the spectrum where arrays are immutable by design of operating with pure functions. But even here one could argue that the Jax design is incomplete with respect to tasks that do not require pure functions assumption, say, initializing an array with computation results that may be obtained from using some another array library. In general, the life time of an array buffer consists of (i) memory allocation, (ii) initialization, (iii) updates, (iv) usage, and finally, (v) memory release. In life stages (ii) and (iii), the arrays must mutable while in the stage (iv) the array ought to be immutable. Allowing multiple switching between updates and usage stages is expected. In the terms of the array life time, the current PyTorch implementation considers immutable array usage irrelevant while the current Jax design fuses initialization into array construction phase and disallows updates. Disclaimer: I don't mean to imply that these libraries ought to change their behavior, although, in some cases such as PyTorch, it would be beneficial. I would expect that the current design choices of libraries (that may change in time in any direction) ought not to restrict array API standard but rather unify these. For instance, extending dlpack protocol with a read-only flag makes lot of sense to me as it will enable implementing sensible buffer sharing approaches between array libraries that otherwise may have contradicting designs. For instance, when a jax.Array buffer is exported via dlpack protocol with read-only flag set to True, the PyTorch ought to have a choice to import it via copy (when it is known that PyTorch is going to update buffers) or via view (when it is known that PyTorch is going to use the buffer as input data only). The choice can be defined as a keyword argument to The current behavior is unhealthy in many ways indeed. For instance, dlpack protocol can be misused to expose immutable data to mutations (another example is jax-ml/jax#19123). Or, when jax.Array is exported to PyTorch via |
dlpack already provides the read-only flag in the new DLManagedTensorVersioned struct: |
Yes but we need a handshaking mechanism in Python before introducing the support, part of which is what #602 intends to address. |
Agreed, we should finally get gh-602 merged. I don't think simply having access to that flag matters too much for readonly behavior by itself though. I don't quite agree that the current state is that unhealthy. There aren't many bug reports, and for those that there are it's usually user error in the same way as doing a mutation on a view by accident in pytorch-only or numpy-only and that modifying the base tensor/array as well. jax-ml/jax#19123 is also simply that, it is not a real world bug.
The problems invariably occur by accident. So if PyTorch had true read-only tensors, that would help increase robustness against unintended mutations a lot. And then no new keyword is needed, JAX arrays would always translate to PyTorch readonly tensors. But if it's up to the user to write |
Agreed that jax-ml/jax#19123 or any user misuse of mutating immutable data can be considered not a real bug when it is documented as undefined behavior. If it is not a bug then it must be a weakness of the co-operativity between array libraries that (i) allows misuse and (ii) there exists no good alternative that enable strict correctness - existing arrays libraries are not always compatible (yet) in exchanging data bidirectionally. Re |
I'd say it's a weakness (limitation is a nicer word probably) of the library in itself. There really isn't any difference between this unwanted mutation happening in CuPy-only or PyTorch-only code (e.g., the sparse tensor indices example you gave) vs. unwanted mutation on a tensor that happened to come in via DLPack.
I don't think that's the case? There's no sign of read-only handling in dlpack.h or DLConvertor.cpp, and the docstring correctly explains that the data is always exposed as shared memory. I did a quick check with latest JAX + PyTorch 2.0, and things work as expected, no exception. An exception is thrown for NumPy read-only arrays though (but those are quite rare, and the user can simply flip the flag on the input numpy array if this happens): https://github.com/pytorch/pytorch/blob/035e55822ad123b02fbd9d91e1185f5c07af0ddd/torch/csrc/utils/tensor_numpy.cpp#L427-L429.
That would be the wrong decision I think, that would make interop between CuPy and JAX completely useless/impossible. The fact remains that if you have one library that is only read-only and one that is never read-only, you only have only a couple of choices independent of whether there are flags/keywords:
JAX used to do (1) and users complained about this, so JAX changed to (2). This works much better, with few complaints AFAIK. So it looks to me like, in the absence of evidence of too many bug reports, that state should stay that way. You simply cannot have complete robustness as well as zero-copy behavior with the current state of JAX -> PyTorch/CuPy interop. Forcing users to make a copy when a readonly flag is set would just go back to (1). Adding a keyword to |
Sorry, my bad. It was |
Ah yes, that is an inconsistency - probably should be changed in PyTorch to align with the DLPack behavior. |
While we are at (2), it is because (i) the current DLManagedTensor does not have read-only flag and (ii) the view-functionality is required for performance. |
We should add advice not to do that then.
It's of use mainly if a library actually has a read-only mode. So it will definitely help if NumPy is the consumer, but it won't change too much for PyTorch/CuPy. |
FYI CuPy is investigating the readonly support: cupy/cupy#8118. I think with #602 merged, we can close this issue now? |
Interesting, thanks for sharing.
Agreed. We have a readonly flag in the latest DLPack version now, plus a way to upgrade to it with |
To be clear, does |
No, you have to set |
The answer right now is: undefined. Unless you pass |
Ok. What is the correct way to handle the following consumer scenario:
If we only use I suppose I am looking for something along the lines of the (Perhaps the answer is that we should just use |
If you don't explicitly use the
I'm not sure why that would be. If that's actually happening, it's probably a bug (assuming they're CPU arrays). Nothing should be missing; if there's a real-world problem can you give some actual code? |
Checkout the first commit of scipy/scipy#20085 :) |
The first commit contains nothing related, the second commit changes >>> import numpy as np
>>> import jax.numpy as jnp
>>>
>>> x = jnp.arange(3)
>>> y = np.asarray(x)
>>> y.flags.writeable
False |
Sorry, the (Checking out the first commit allows you to see the errors which occur without introducing the |
I think this statement ought to be more explicit in the standard, say, via an additional note:
Otherwise, a non-copy exchange of data becomes impossible between producers that do no support writable arrays (say, JaX) and consumers that do not support read-only arrays (say, PyTorch). |
I'll have a look, thanks. This isn't really DLPack related, because the exact same thing should happen with NumPy read-only arrays. Also, with a few exceptions, all APIs in SciPy should not be modifying their input arrays, so I guess there'll be a zero-copy way to work around the exact problem here. Let's continue this on the SciPy PR - I'll try your code and comment there.
Sure, that seems useful to me. That'll be a note that simply documents the way things currently work anyway I believe. Let me open a PR for that. "should" as a recommendation is probably right here, rather than "must" - but let's leave that level of detail for the PR. |
This is a follow-up to the discussion in data-apisgh-191. It's a recommendation rather than a hard requirement to allow implementers some choice. That said, this is how things worked in practice before DLPack 1.0 as well, since there was no flag to represent read-only. Experience with JAX showed that exposing shared memory was preferred by users over raising or always making a copy of the data on the producer side.
Done in gh-749. |
This is a follow-up to the discussion in gh-191. It's a recommendation rather than a hard requirement to allow implementers some choice. That said, this is how things worked in practice before DLPack 1.0 as well, since there was no flag to represent read-only. Experience with JAX showed that exposing shared memory was preferred by users over raising or always making a copy of the data on the producer side.
Sorry if there is some more discussion (or just clarification) in the pipeline. But I still think this is important, so here is an issue :). I realize that there was some related discussion in JAX before, but I am not clear how deep it really was. (I have talked with Ralf about this – we disagree about how important this is – but I wonder what others think, and we need to at least have an issue/clear decision somwhere.)
The problem (and current state/issues also with the buffer protocol that supports "readonly")
NumPy (and the buffer protocol) has readonly (
writeable=False
arrays). NumPy actually has a slight distinction (I do not think the matters, though):The current situation in the "buffer protocol" (and array protocols) world is that NumPy supports a writeable and readonly arrays, JAX is immutable (and thus readonly), while PyTorch is always writable:
JAX to NumPy works correctly:
NumPy to JAX ignores that NumPy is writeable when importing (same for
memoryview
):PyTorch also breaks the first part when talking to JAX (although you have to go via ndarray, I guess):
And NumPy arrays can be backed by truly read-only memory:
This is in a world where "readonly" information exists, but JAX and PyTorch don't support it, and we leave it up to the user to know about these limitations. Because of that pretty severe limitation PyTorch decides to give that scary (and ugly) warning.
JAX tries to protect the user during export – although not in DLPack – but silently accepts that it is the users problem during import.
I do realize that within the "array API", you are not supposed to write to an array. So within the "array API" world everything is read-only and that would solve the problem. But that feels like a narrow view to me: we want DLPack to be widely adopted and most Array API users are also NumPy, PyTorch, JAX, etc. users (or interact with them). So they should expect to interact with NumPy where mutability is common. Also
__dlpack__
could very much be more generally useful than the Array API itself.Both JAX (immutable) and PyTorch (always writeable) have limitations that their users must be aware of when exchanging data currently. But it feels strange to me to force these limitations on NumPy. Especially, I do not like them in
np.asarray(dlpack_object)
. To get around the limitations innp.asarray
we would have to:Clarifying something like that is probably sufficient, at least for now.
But IMO, the proper fix is to add a read-only bit to DLPack (or the
__dlpack__
protocol). Adding that (not awkwardly) requires either extending the API (e.g. having a new struct to query metadata) or breaking ABI. I don't know what the solution is, but whatever it is, I would expect that DLPack is future-proofed anyway.Once DLPack is future-proofed, the decision of adding a flag could also be deferred to a future version…
As is, I am not sure NumPy should aim to talk preferably in
__dlpack__
in the future (whether likely to happen or not). Rather, it feels like NumPy should support DLPack mainly for the sake of those who choose to use it. (Unlike the buffer-protocol, which users use without even knowing, e.g. when writingcython
typed memoryviews.)Neither JAX nor pytorch currently quite support "readonly" properly (and maybe never will). But I do not think that limitation is an argument against supporting it properly in
__dlpack__
. NumPy, dask,cupy, cython (typed memoryviews) do support it properly after all. It seems almost like turning a PyTorch "user problem" into an ecosystem wide "user problem"?Of course, NumPy can continue talking buffer-protocol with cython, and many others (and likely will do in any case). And I can live with the limitations at least in an
np.from_dlpack
. But I don't like them innp.asarray()
, and they just seem like unnecessary issues to me. (In that case, I may still prefer not to export readonly arrays.)Or am I the only person who thinks this is an important problem that we have to solve for the user, rather than expect the user to be aware of the limitations?
EDIT: xref discussion about it at cupy, that was mentioning that nobody supports the readonly flag which
__cuda_array_interface__
actually includes, and asked for support to cupy. (I am not sure why C-level matters – unless it is high level C-API – the Python API is what matters most? NumPy has aPyArray_FailUnlessWriteable()
function for this in the public API.)The text was updated successfully, but these errors were encountered: