Repository navigation
Open
Labels
Description
Describe the issue:
See title: serializing a string array to a buffer and trying to deserialize it fails.
No matter if if the problem is generic or about using None as na_object, the error message is wrong:
I’m not trying to create an object array.
Reproduce the code example:
import numpy as np
string_dtype = np.dtypes.StringDType(na_object=None)
buf = np.array([[None], ["bcdef"]], dtype=dtype).tobytes()
np.frombuffer(buf, dtype=string_dtype)Error message:
ValueError
----> 6 np.frombuffer(buf, dtype=string_dtype)
ValueError: cannot create an OBJECT array from memory bufferPython and NumPy Versions:
2.0.0
3.12.4 (main, Jun 7 2024, 06:33:07) [GCC 14.1.1 20240522]
Runtime Environment:
[{'numpy_version': '2.0.0',
'python': '3.12.4 (main, Jun 7 2024, 06:33:07) [GCC 14.1.1 20240522]',
'uname': uname_result(system='Linux', node='gnosis', release='6.9.8-zen1-1-zen', version='#1 ZEN SMP PREEMPT_DYNAMIC Fri, 05 Jul 2024 22:11:01 +0000', machine='x86_64')},
{'simd_extensions': {'baseline': ['SSE', 'SSE2', 'SSE3'],
'found': ['SSSE3',
'SSE41',
'POPCNT',
'SSE42',
'AVX',
'F16C',
'FMA3',
'AVX2'],
'not_found': ['AVX512F',
'AVX512CD',
'AVX512_KNL',
'AVX512_KNM',
'AVX512_SKX',
'AVX512_CLX',
'AVX512_CNL',
'AVX512_ICL',
'AVX512_SPR']}},
{'architecture': 'Zen',
'filepath': '/usr/lib/libopenblas.so.0.3',
'internal_api': 'openblas',
'num_threads': 16,
'prefix': 'libopenblas',
'threading_layer': 'openmp',
'user_api': 'blas',
'version': '0.3.27'},
{'filepath': '/usr/lib/libgomp.so.1.0.0',
'internal_api': 'openmp',
'num_threads': 16,
'prefix': 'libgomp',
'user_api': 'openmp',
'version': None}]Context for the issue:
No response
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsOpen
Activity
seberg commentedon Jul 9, 2024
The error is correct, you can't dump objects to bytes reasonably (yes, it does it, but the result is raw pointers). And you can even less read a
StringDTypefrom it, since it contains references (to the dtype side storage).The only odd thing here is that it prints
OBJECTwhen it should say "that contain references" (and of course the first part should maybe fail already).[-]BUG: trying to read StringDType array from buffer results in “cannot create an OBJECT array from memory buffer”[/-][+]DOC: improve StringDType error in from buffer results[/+][-]DOC: improve StringDType error in from buffer results[/-][+]ENH: improve StringDType error in from buffer results[/+]flying-sheep commentedon Jul 9, 2024
So numpy tries to serialize the
na_objector what?seberg commentedon Jul 9, 2024
Right but
StringDTypeis the same here, in that it cannot be dumped since the array contains references and you get the references only.flying-sheep commentedon Jul 9, 2024
Hm, so apparently quite some of my assumptions were wrong. I assumed
csr_matrixor so.frombufferhas adtypeparameter that isn’tNoneby default, therefore there is no way to tellfrombufferto get dtype from the data, therefore I assumed it’s not in there.Are both of these wrong?
/edit: I found this now https://numpy.org/neps/nep-0055-string_dtype.html#serialization
seberg commentedon Jul 9, 2024
They are both partially right, but your assumption about what
tobytes()does is very wrong. It refers only the main array buffer which is the offsets in your view (but it's not actually plain offsets).flying-sheep commentedon Jul 9, 2024
I see, thank you. So I guess I'll also file thr feature request predicted as
in NEP55
ngoldbaum commentedon Jul 9, 2024
Yeah, unfortunately this would require a format update for the npy file format and I didn't want to take that on just to ship StringDType. See #24110, #25374, and #25498 for all the discussion we had about this when I realized it would require a change to the npy file format.
mullenkamp commentedon Jul 29, 2025
Hi,
So just to be clear, there's no way to serialize a StringDType array (to bytes) in a way that can be parsed back into a new StringDType array (aside from pickle)?
ngoldbaum commentedon Jul 29, 2025
Nope and me and others are very aware this is an issue. See #29229 for our latest take on this. @seberg and I are also looking at if we can update the buffer protocol to allow e.g. cython to parse numpy buffers. See https://discuss.python.org/t/buffer-protocol-and-arbitrary-data-types/26256/13 and da-woods/cython#5 for the latest on that.
ngoldbaum commentedon Jul 29, 2025
Can you share a little more what you're trying to do? Are you limited to only using Python APIs or can you use the numpy C API too?
mullenkamp commentedon Jul 29, 2025
Thank you very much for your quick reply with those links. I have to admit, some of those technical details are currently beyond my knowledge...
My use case is that I'm converting numpy arrays to bytes (which is then compressed using zstandard) then stored on disk or on S3. These bytes (representing a single array) will either be appended on a single file or stored separately. I then retrieve those arrays as needed for my processing and analysis.
I'm sure I can use a fancier/more complicated python package to do this, but I like to make things simple.
Unfortunately, I've never written any C code, so I'm limited to python in this case.
The variable length strings are handy, because you don't have to know the bit length ahead of time (if more data is appended later).
flying-sheep commentedon Jul 30, 2025
OK, so basically all this means that you still can’t store string arrays using nothing but numpy’s codecs. If you use numpy’s
saveandload, you still need to haveallow_pickle=Trueset.I think pickles are pretty stable these days, but if you want rock-solid future-proof storage, you’re still going to need to use something like hdf5, zarr or arrow(/parquet).
TBF, using one of these codecs is simpler than what numpy does, because Python pickles are much more complex than a well-specified codec that can’t hold basically arbitrary objects defined by an interpreted language.
(@team please correct me if I’m being inaccurate in any detail here)
ngoldbaum commentedon Jul 30, 2025
You can store a pickle as bytes too:
Both h5py and zarr have support for StringDType in recent versions and I would look at those for any "real" data storage.
I think the fact that
tobytes()doesn't consider references is probably a bug? This is probably not what anyone wants:Note how the output is different for the first two items. This is because the strings aren't immortal, and a new PyObject instance is allocated every time you create a python string containing that data. tobytes() for object arrays just prints out the value of the PyObject pointer, which can change if an object is deallocated and then reallocated, for example.
(incidentally None is immortal so the last item is the same in both serializations)
Both StringDType and object arrays are arrays of references and we need better support for them in NumPy in general. We have an opportunity to solve this for all new DTypes we might ever want to add to NumPy in the future, which might include other arrays of references. I'd prefer to work on that instead of one-off fixes for StringDType.
I think the work @MaanasArora is spearheading the first step - we need to define what exactly is needed for producers and consumers of ndarray buffers and we need to make sure parsers fail gracefully if they're handed data they don't understand. Once that is all well-defined we can then write serializers and deserializers that conform to the spec. At that point it may also make sense to update the npy file format or just say more advanced uses that are currently unsupported require other solutions like zarr or h5py. We should also make the npy format work with dtypes where it makes sense right now, like bfloat16 or a quad precision dtype.
mullenkamp commentedon Jul 30, 2025
Thank you very much @ngoldbaum (and @flying-sheep) for your detailed reply. I 100% agree with your assessment and proposed approach.
I had assumed that the
tobytes()method should return the bytes directly associated with the data in the array rather than pointers to some other object. And thattobytes()should raise an exception if it cannot serialize the data to bytes (e.g.objectdtype). But this is coming from the perspective thatnp.frombuffershould be able to parse any output fromtobytes(). This is definitely implied in the docs for both functions (hence the "Inverse of this operation" reference).I recognize that this is purely my opinion, and you all should follow through with what you think is appropriate from the overall numpy scope.
Thanks again!
seberg commentedon Jul 31, 2025
I would be fine to deprecate or warn that
tobytes()is pretty useless if a dtype has references. In practice it doesn't round-trip anyway, sincefrombytes()will correctly reject it.Not sure if there are users who want it to just work (mostly) for some dtype with references for some weird reason.
For round-tripping, it seems not too worrying to me, since it fails later pretty clearly (sure could say "references" rather than "object" (or the actual dtype), but I guess someone may use
tobytes()for something else (hashing?) and not realize that it isn't reliable; unless they actually don't care that it isn't reliable...(If we change things here, then we should probably keep it in synch with buffer-protocol export without a format/dtype.)
MaanasArora commentedon Aug 4, 2025
Yes, the error could be clearer, but I think it makes sense that getting bytes from the buffer protocol (
tobytes) maybe wouldn't be expected to work correctly when dtypes start using in-memory references - if we change things we would have to consider all the different ways that the references are put into place and perhapstobytesisn't the best place for that (given it is synced with the buffer protocol as @seberg mentioned).As @ngoldbaum mentioned we've been working on starting to define a schema that acts as a contract for the data needed to read and write for array serialization (in #29229), so maybe that's a better place to make sure we have the correct data / bytes; and tools like Zarr will probably be better specialized to handle serialization than any changes we do in these NumPy methods itself right now.
I still think there's something nice about keeping
tobytesworking; I'm just wondering how we can do it minimally, and I think the answer could be clearer when we have some of the new serialization in place! So improving the error message for now could be a good short-term solution.