Skip to content

ENH: dtype API needs a hook in np.save and np.load #24110

Closed

Description

@ngoldbaum

Currently if you try to use np.save and np.load with a new-style dtype, you'll get this error:

from stringdtype import StringDType
import numpy as np

arr = np.array(["hello", "world"], dtype=StringDType)
np.savez("arr.npz", arr)
with np.load("arr.npz") as data:
    larr = data['arr_0']
print(larr)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:661, in _read_array_header(fp, version, max_header_size)
    660 try:
--> 661     dtype = descr_to_dtype(d['descr'])
    662 except TypeError as e:

File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:306, in descr_to_dtype(descr)
    304 if isinstance(descr, str):
    305     # No padding removal needed
--> 306     return numpy.dtype(descr)
    307 elif isinstance(descr, tuple):
    308     # subtype, will always have a shape descr[1]

TypeError: data type '|\x0016' not understood

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Cell In[10], line 7
      5 np.savez("arr.npz", arr)
      6 with np.load("arr.npz") as data:
----> 7     larr = data['arr_0']
      8 print(larr)

File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/npyio.py:253, in NpzFile.__getitem__(self, key)
    251 if magic == format.MAGIC_PREFIX:
    252     bytes = self.zip.open(key)
--> 253     return format.read_array(bytes,
    254                              allow_pickle=self.allow_pickle,
    255                              pickle_kwargs=self.pickle_kwargs,
    256                              max_header_size=self.max_header_size)
    257 else:
    258     return self.zip.read(key)

File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:786, in read_array(fp, allow_pickle, pickle_kwargs, max_header_size)
    784 version = read_magic(fp)
    785 _check_version(version)
--> 786 shape, fortran_order, dtype = _read_array_header(
    787         fp, version, max_header_size=max_header_size)
    788 if len(shape) == 0:
    789     count = 1

File ~/.pyenv/versions/3.10.9-debug/lib/python3.10/site-packages/numpy/lib/format.py:664, in _read_array_header(fp, version, max_header_size)
    662 except TypeError as e:
    663     msg = "descr is not a valid dtype descriptor: {!r}"
--> 664     raise ValueError(msg.format(d['descr'])) from e
    666 return d['shape'], d['fortran_order'], dtype

ValueError: descr is not a valid dtype descriptor: '|\x0016'

So at a minimum we need to update these functions to save the correct descriptor metadata to allow reconstructing the descriptor in np.load.

For stringdtype we need sidecar storage, which might need a new revision to the npy file format spec to add extra metadata for the sidecar storage. However as a first pass we could just re-use the flag that's already in the file format spec that indicate the array data are stored in an inline pickle file.

Activity

  1. ngoldbaum commented on Jul 6, 2023

    @ngoldbaum
    MemberAuthor

    np.save constructs the header for an array in the header_data_from_array_1_0 function. There's a bit of indirection, but all non-legacy dtypes will end up being saved using the dtype.str typestring from the __array_interface__ protocol. This is a problem, because non-legacy dtypes don't yet have a typestring following that protocol.

    I could save some kind of ad-hoc string. I could save the descriptor as a pickle (although that won't help if allow_pickle is False). A more complete fix would be to implement #23500 and extend whatever we come up with there to the __array_interface__ protocol.

  2. rkern commented on Jul 6, 2023

    @rkern
    Member

    Truly supporting this probably really does require a NEP for a major revision of the NPY format, for which the time is probably right. Looking up the third-party dtype, possibly importing modules new to the process, is a significant change that needs discussion. The NPY format was initially designed to be very minimalistic. Extending it to be a container for fairly arbitrary contents (like the sidecar data) is an expansion of scope that needs to be weighed. There are also a lot of innovations in the ecosystem (more efficient pickle formats, Arrow, etc.) that are now worth weighing.

    In the short term, I do think that we can detect these custom dtypes and default to the pickle escape hatch, just as if we had an object dtype.

  3. ngoldbaum commented on Jul 6, 2023

    @ngoldbaum
    MemberAuthor

    In the short term, I do think that we can detect these custom dtypes and default to the pickle escape hatch, just as if we had an object dtype.

    One wrinkle is the dtype class needs to be reconstructed as well, so we'd either need to pickle the descriptor (ugly and breaks the data format, since the descr field in the header contains inline data) or add support in NumPy for loading custom data types from a string. Both approaches require an import of the extension defining the custom dtype, which you seemed dubious about.

    Would you be OK with something like the _dtype_from_buffer_fmt function in @seberg's comment here, which might import an arbitrary python module depending on the content of the format code?

  4. rkern commented on Jul 6, 2023

    @rkern
    Member

    Hmm, right. NEP time, then, if not PEP time.

  5. rkern commented on Jul 6, 2023

    @rkern
    Member

    One hack, that's still probably NEP-worthy, is to detect these dtypes and just write out the descr as if it were a dtype=object array. This would be a lie, on paper, but that information won't actually be used in the reconstructed array since np.load() would just unpickle the data there and return the unpickled object.

  6. added a commit that references this issue on Jul 12, 2023
    c6a449c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions