Repository navigation
Description
Feature
Motivation
Currently, any library which needs to exchange data with NumPy needs to have it as a dependency. This issue will allow moving away from that approach to a more Pythonic standards-based approach leveraging the DLPack Library, as described in the Array API standard. This is also mentioned in and a prerequisite for NEP 47, although it can be discussed and integrated independently of it as well, the only caveat being that if the NEP is accepted; adopting DLPack is a given.
DLPack is a small C header-only library with a stable ABI.
Changes needed to NumPy
The numpy.ndarray type will need to gain two new methods:
__dlpack__: This will return aPyCapsulewith a DLPack struct.__dlpack_device__: This one will always return the CPU device for NumPy.
And the NumPy namespace will gain one extra function:
from_dlpack: This will consume aPyCapsulecontaining a DLPack struct and create anumpy.ndarraybased on that. It will raise aRuntimeErroron all unsupported configurations of the object.
Relevant issues/discussion:
- [RFC] Adopt DLPack as cross-language C ABI stable data structure for array exchange data-apis/consortium-feedback#1
- Array API docs
- Links to existing implementations: [RFC] Adopt DLPack as cross-language C ABI stable data structure for array exchange data-apis/consortium-feedback#1 (comment)
- PyTorch in-progress PR: Adds DLPack support pytorch/pytorch#57110
- Discussion on the DLPack issue tracker: Import DLPack tensors directly into NumPy (without going via PyTorch or TF) dmlc/dlpack#55
Edit: Previously this issue said from_dlpack was a method, that has been corrected.
Activity
mattip commentedon May 14, 2021
For other commenters: the discussion at data-apis/consortium-feedback#1 is quite lengthy but does include answers to many questions like object lifetime management. It is helpful to understand the context. Many of my concerns were addressed there.
A side issue is the struct itself: the header mentions "[The data] pointer is always aligned to 256 bytes as in CUDA". If this is a hard requirement, NEP 49 may help achieve this in a zero-copy manner.
I think this can be done separately from #18585.
seberg commentedon May 14, 2021
I have tried to look through the discussion. I still don't understand why the "consumed exactly once" is important (the PyCapsule is reference counted and can clean up on delete, so the memory management seems fine? – although maybe that is tricky without reference counts). But maybe there is something about streams or so that I just don't see right now.
Would NumPy be able to just use the
offsetto "make it fit" even if that meansdatapoints to some random (earlier) place?For the API, I think, I am still a bit confused about view vs. copy. If
__dlpack__can return either a view or a copy, it would be nice if it could indicate so? Either as an inputcopy={None, True, False}or as an additional return flag (or even both).Most of the current protocols don't have this problem, the one that does is
__array__and it would be nice to have it there!Especially, if the alignment of the memory allocation in NumPy can lead to a copy return instead of a view, that seems like it must at least be easy to check (I guess
np.may_share_memorymight work). Since there is no good way to "predict" what is going to happen.But, in general I think it just needs a good PR. Inn the end I don't really want to worry about it too much, if other projects already implemented basically the same thing (and it seems like they did). So long NumPy isn't the odd one out, due to being the only one that has to copy for reasons like alignment or byte-swapping.
rgommers commentedon May 15, 2021
Exactly, it's not that important. It came from before we improved the Python API; the old way of doing it in other libraries was:
At that point you had a (non-useful) PyCapsule object floating around in the users code, and then doing
x3 = from_dlpack(capsule)somewhere else in the code would of course lead to problems. Using__dlpack__avoids this by design.hameerabbasi commentedon May 15, 2021
I think we can make this a keyword-only argument without breaking compat with the existing protocol, and default it to
None. Perhaps it can be in a future version, but that may need to be discussed separately.I believe not, in that case the allocation still isn't "aligned" unfortunately.
For other commenters, this is due to the by-element strides of DLPack instead of the by-bytes.
hameerabbasi commentedon May 15, 2021
This is, indeed, a sticking point. I do not know how to resolve this. Perhaps this restriction could be clarified or removed if the rationale didn't apply to CPU data pointers.
cc @tqchen would you happen to know the answer?
rgommers commentedon May 15, 2021
Why would we want this? Semantics of a program using DLPack should not rely on view vs. copy (avoid in-place ops). The protocol tries to return a view for performance reasons, but it may not always be possible for all libraries - and then it will return a view. Having an explicit
copy=keyword seems like a mistake to me.hameerabbasi commentedon May 15, 2021
Usually, performance. Maybe one may want the flexibility of a different path when a view isn't possible, e.g., perform operation in the existing library rather than moving it to a new one using DLPack.
Or, conversely, one may want to specify a copy because in-place ops are needed for an algorithm/function (I guess one can always do
x = x.copy()or similar, but that's an extra LOC).Of course, the default would be
None, i.e., we don't guarantee either and then everything you said applies.rgommers commentedon May 15, 2021
Performance is already optimal, it default to zero copy.
Exactly. That's about zero characters extra, so if you want to do something numpy-specific, use that. There are libraries that don't even have the concept of a view, and the buffer protocol and
__array_interface__don't have a copy keyword either. Adding a copy keyword doesn't make sense to me.seberg commentedon May 15, 2021
But that is not a stated requirement anywhere, I found yet? And apparently NumPy cannot always export zero copy (which is fine, but then we need an additional
np.export_dlpack(...)ornp.ensure_dlpack_exportablefunction to do the copy if necessary)?If the user wants to copy the data, they may have to do so twice, because they don't know whether the original array-like was copied already. Either because the exporter does so always, or because it does so "if necessary" like NumPy would apparently.
Further, the buffer protocol also supports signaling read only export. JAX could use that to allow a no-copy export when given?
Could you explain why this such a strong preference that it doesn't matter to think about how you could allow both exports transparently? What about copy on write semantics, or just plain old numpy style usage?
Fair enough, it might help with memory management. It also might help a bit to ensure that only a single consumers will end up writing to the data. (I guess this doesn't relaly matter if we assume all exports are zero-copy, though.)
rgommers commentedon May 15, 2021
Hmm, I'll have a look at where the most obvious place is to mention this. DLPack works just like the buffer protocol, except:
I don't think that is true. And I reviewed the implementations in other libraries like CuPy, MXNet, PyTorch and JAX a while back, and can't remember anything regarding the 256 byte alignment thing.
There may be more exotic libraries that perhaps could be forced to make a copy, e.g. Vaex has a concept of "virtual columns" where data is basically a string expression rather than it living in memory. In that case, zero-copy access isn't possible.
Another thing that can happen is that NumPy has, say, an array with odd strides. And then JAX and TensorFlow can't represent that, they only have contiguous arrays internally - hence they make a copy on the consumer side.
But for our purposes, I think there isn't too much magic - just think of it as an enhanced buffer protocol.
rgommers commentedon May 15, 2021
I hadn't noticed the comment (https://github.com/dmlc/dlpack/blob/main/include/dlpack/dlpack.h#L130) before. It talks about CUDA and OpenCL, and the only mention in the issue tracker is dmlc/dlpack#1 (comment), which talks about vector types like
float4for accelerators. It's not clear that the comment was meant to apply to CPU.PEP 3118 also briefly mentions alignment: " The default endian is
@which means native data-types and alignment. If un-aligned, native data-types are requested, then the endian specification is '^'.". Requiring alignment maybe makes sense, but why would one need 256-byte alignment on CPU?rgommers commentedon May 15, 2021
Oh wait, this explains it (from issue description of data-apis/consortium-feedback#1):
That should solve the issue?
rgommers commentedon May 15, 2021
I think that's more of a problem than a feature in the buffer protocol actually, and it reflects that it was written mostly from a "NumPy needs/design" point of view. Most libraries simply do not have a read-only array/tensor data structure, so if you create an array in such a library with
from_dlpack, what are you supposed to do with areadonly = 1flag?5 remaining items
hameerabbasi commentedon May 15, 2021
I believe there are some (admittedly rare) cases I see where NumPy must copy: The strides inside DLPack assume a unit of array elements, and those inside NumPy assume a unit of bytes, which is more flexible. One can find cases where zero-copy isn't possible, and one can see these if all elements of
arr.stridesaren't a multiple ofarr.dtype.itemsize. Concrete examples I can find are:So, yes, it's possible, rare IMO, and can be easily predicted by checking for
all(s % arr.itemsize == 0 for s in arr.strides).But what I see as the more pressing matter I should clarify is the alignment: Should one just round down the pointer to the next 256 bytes and also add the "round down" amount to the offset?
leofang commentedon May 16, 2021
On my cell, so please forgive me for leaving only a drive-by comment: please ignore the alignment stuff. If we are talking about host-device copies, it's an implementation detail (of CUDA, HIP, or any sane memory pool implementation sitting on top). CUDA/HIP's copy APIs do not care about alignments. DLPack does not. CUDA Array Interface does not. No one does.
Another thing is I seem to recall we agreed in a Array API meeting that if copy is needed, it's best for the user to handle it explicitly. I can try to look up a note on this later.
seberg commentedon May 16, 2021
Thanks for clearing that up Ralf and @leofang, sorry for missing the link to the comment where it was more clearly defined. I am not concerned about NumPy providing
__dlpack__then. Forcing the user to copy on weird strides or dtypes seems totally fine.@leofang: If a copy is never done, that is good. My concern is mainly that it should be predictable. Although, never might even be nicer. (The array api says it can return a view or copy,
but it doesn't specify who would be making that copy, the exporter, importer, or either/both, I guess the copy is expected to be made by the exporter only currently).@rgommers, sorry if you feel I am just blocking your producitivity by making up moot issues and proposing changes to something that you have settled for yourself. Maybe I am late to the party, but maybe can I have a bit of time to think out loud? I am happy be pointed to a different place/issue, if you think this is a terrible place...
To be clear, I am still just exploring limitations, and how those limitations could be removed. The
copy=argument is a thing we had discussed for__array__()because of napari, so it didn't come out of nowhere, it always addressed at least the napari use-case below.And yes, I may have had the wrong impression that this API still could be modified more easily if new use-cases/problems come up, easier than the buffer-protocol at least. And just because I am discussing possible new API, doesn't mean I am trying to shut down adding the current as is.
The limitations as use-cases, instead of "missing API" are:
Napari wants to show a numpy or cupy array that is will be updated in-place by the user. It would be nice if it can inform the user when a function is not compatible with the input (i.e. the plot will never update if a copy was exported, confusing the user).EDIT: I misremembered the napari story. Pytorch refused to do the copy, napari wanted to force a copy (signal that it is OK if a copy is made). So, "napari" is not right, but we still decide that in-place modification (or viewing of mutable data) via DLPack import is discouraged (the user has to deal with the fact that it will not always work, a library that might want to do it can only document that fact).np.ndarray.from_dlpack(jax_tensor)what shouldl NumPy do? If it came from Vaex, or anther library with writeable-view semantics, we can create a normal array view. But if it is a JAX one, Numpy should either copy the data, or set the array to readonly. Otherwise, the user might accidentally mutate the input array.Now you did dismiss a few of these as user-problems, or just not relevant enough (i.e. don't use DLPack if you write in-place algorithms or like writeable-view semantics). And the unnecessary copy is mitigated by Veax exposing a copy being uncommon, I guess?
But at least some still seem like (small?) user traps to me. And
it seemswe have to at least always set the new array to read-only in NumPy or risk interpreter crashes if a truly readonly buffer is passed (EDIT: but yes the array-standard does mention that non-writing is preferred). So the "no writeable-view" actually becomes a hard requirement, rather than a soft preference).Is adding one or two bits of information to DLPack on the table or are all of these small issues that we just want to live with?
And with that, sorry for a way too long post...
seberg commentedon May 16, 2021
About the buffer protocol: You are right, I guess. The buffer protocol has only the "release function". And that could be enough to allow deleting the original object, but it is not specified to be a valid. (By passing a new, different "owner" object out during buffer creation. CPython's memoryviews would work with that happily, but NumPy doesn't.)
So yes, unlike DLPack, the buffer protocol doesn't quite allow deleting the original exporting object. So maybe the "release" function is not a proper "delete" function in that sense.
rgommers commentedon May 16, 2021
This is the thing - if you propose changes on this issue tracker, you're talking to others who then have to spend time responding to your proposals. It's different from "thinking out loud" (which I interpret as "to clarify things for yourself"). For me the appropriate places to take notes or clarify things for myself are a piece of paper, a HackMD doc, my own fork, etc. - and then ask clarifying questions first rather than make new proposals immediately. The bandwidth differential we have (you're full-time on NumPy, I'm struggling to find enough time) makes the impact of that worse.
I think this is an important communication issue that comes up more often that I'd like. It'd be great if we could chat about it a little , maybe a call in the next few days - I'll ping you on Slack.
The DLPack maintainers are quite responsive, and significant changes have already been made to DLPack itself (complex dtypes support, stream support, Python API, renaming struct fields for clarity, etc.). More changes, provided they fit in the DLPack design and have good rationales, are very welcome I'm sure. That said, it'd be great to get some experience with at least a prototype of the current design first - proposing changes not based on any experience with the protocol seems a little odd.
rkern commentedon May 16, 2021
As annoying as it is to be on the receiving end of that, I have found that it has always been the case that the fault was mine, as the proposer. It's not your audience's fault that they weren't following all of your deliberations in real-time that would have shown how you worked out their problem cases. If it's not clearly laid out in the final proposal, it's a fair question. A ton of the PRNG design work went on in the default
BitGeneratormega-thread, but I'd never refer people back to it except to prove that we did talk about something, not what the answer is. If their question isn't explained onnumpy.org, then it's a fair one to ask and be answered.Every new audience is a new discussion. You can short-circuit that discussion by drafting the proposal expansively and clearly. For whatever benefits the DLPack maintainers have gotten by keeping their RFCs strictly in Github issues, it does mean that there's no such document for you to use to forestall questions.
rgommers commentedon May 16, 2021
Thanks @rkern, that's all very fair. NEP 47, the array API docs and docs in the DLPack can all certainly be improved.
Definitely, please ask those questions. Ask to see a PR first so you can play with it. And point out which are the important doc gaps to fill. It's simply kind of hard if that's mostly skipped over and we jump straight to an API extension proposal.
rkern commentedon May 16, 2021
Agreed. There can be multiple reasons for the disconnect (the proposal isn't what you think it is, there's a disagreement about what the consequences of the proposal actually are, or there's a disagreement about whether the consequences are desirable). A counter-proposal is only appropriate once the disconnect is revealed, if not resolved.
AFAICT, there's nothing that prevents a prototype from being made outside of numpy first. There might just be a little wrapper object in the way until support lands in a release of numpy.
Such a prototype package would be useful in production in order to support older versions of numpy, regardless. It's not going to solve all use cases (you won't be able to write "NEP 47-generic" functions with it), but a number of use cases involving explicit conversions can be handled. A small third-party prototype will make the discussions concrete and even premature counter-proposals more tolerable to discuss.
leofang commentedon May 19, 2021
First, replying to myself:
I think it's clear that host-device transfer should raise in NumPy's case. Now, let me move to Robert's above reply:
Can we please not do this outside NumPy? Two reasons:
to_dlpack/from_dlpack) that have been implemented in virtually all other major libraries as far as NEP 47 / Array API is concerned, including CuPy / PyTorch / TensorFlow and JAX. Apart from the deleter behavior which no one got it right in the first shot AFAIK, it actually works ok with little user complaints. I think PyTorch supports CPU tensors so I would recommend to peek at their implementation to see how they handle the CPU-GPU case. Otherwise, it is fairly straightforward to support.to_dlpack(), only__dlpack__+__dlpack_device__+from_dlpack(). The dunder methods must live in NumPy as a result...rkern commentedon May 19, 2021
No, I saw that. But it's not essential for a prototype that can help work out some of the other details. I'm not saying you should maintain it forever (though it could be useful for working with current versions of numpy). It's noticeably easier to build and evaluate a small prototype package than it is to build and evaluate a branch of numpy, especially if what I want to test is how it relates to other packages, which have their own dependencies on versions of numpy.
eric-wieser commentedon May 25, 2021
I've only skimmed the conversation here, so apologies in advance if I'm repeating things
#19013 (comment) says
Are there technical reasons that we can't go through a PEP3118
memoryviewas an intermediary?That is, could a
pep3118_dlpacklibrary be written that provides all object supporting PEP3118 with dlpack support, not justnp.ndarray? Or is it impossible to writepep3118_dlpack.to_dlpackandpep3118_dlpack.from_dlpackcorrectly?hameerabbasi commentedon May 25, 2021
@eric-wieser I believe the answer is in #19013 (comment),
eric-wieser commentedon May 25, 2021
My questions is more along the lines of "is it possible to 'smuggle' simple
memoryviews through the dlpack interface and vice versa", and less about exactly what the conventions around the python API might look like - so I don't think that answers my question.seberg commentedon May 25, 2021
The feature set is a bit disjunct: the buffer-protocol supports much more, but doesn't support devices, but I don't think that is what you mean?
If there was a
dlpack.DLPackManagedTensorlibrary, then yeah... NumPy could effectively import that and useDLPackManagedTensor.from_buffer()andmemoryview(DLPAckManagedTensor)(I am assumingDLPackManagedTensorwould implement the buffer protocol).I am not sure the indirection is useful enough? Hopefully DLPack is just so simple that it doesn't matter too much? Effectively, NumPy would/could be exactly that library (although not the most elegant implementation)! As far as I can tell NumPy supports the full set of features that is supported by both DLPack and Memoryview.