Skip to content

numpy strings use too much memory #15347

Closed

Description

@ri938

We are trying to upgrade our company software to python3. After completing this we realised all our services were using too much memory and the reason is that the numpy unicode arrays uses 4x as much memory as the python2 numpy strings. This is because it uses 4 byte characters rather than 1 byte characters.

I know there is the bytestring np.bytes_ but it is not equivalent to a string and using this would require rewriting a substantial part of our codebase. For example you would have to convert it to a string anytime you wanted to use the column for our purposes. For example in order to check equality, to merge with other datasets etc.

Can you provide a way to have more memory efficient string arrays. At the moment we are likely to revert our codebase to python2 again and this is the only reason.

Activity

  1. eric-wieser commented on Jan 18, 2020

    @eric-wieser
    Member

    This has been discussed before - we've talked about adding Unicode encodings other than utf32, but the infrastructure to do that is still quite a way off.

    For example in order to check equality

    In this case, you can use my_bytes_arr == my_str_scalar.encode('utf8').

  2. eric-wieser commented on Jan 18, 2020

    @eric-wieser
    Member

    I know there is the bytestring np.bytes_ but it is not equivalent to a string

    It is exactly equivalent to what python2 called a string.

  3. ri938 commented on Jan 18, 2020

    @ri938
    Author

    I know there is way to perform actions on bytestrings but

    1. we have large string arrays and to repeatedly translate strings to and from bytestrings is slow
    2. it will require a large code rewrite to achieve this and so use lots of development time
  4. charris commented on Jan 18, 2020

    @charris
    Member

    Yep, NumPy uses utf-32 for unicode strings. That was to avoid problems in dealing with the different encodings. If Python 2 (ascii) was adequate before, may I suggest that you could use ordinary string arrays.

    In [9]: a = np.array(["hi", "world"], dtype='S')                                
    
    In [10]: a                                                                      
    Out[10]: array([b'hi', b'world'], dtype='|S5')
    

    The downside there is that the elements are interpreted as byte strings, but depending on your application that might be OK. Can you provide more details?

  5. ri938 commented on Jan 18, 2020

    @ri938
    Author

    there is no avoiding having to translate the arrays into strings at times and this is slow
    for example we want to put the arrays into pandas and then use that to merge on

  6. charris commented on Jan 18, 2020

    @charris
    Member

    So is the problem that pandas cannot use byte strings?

  7. ri938 commented on Jan 18, 2020

    @ri938
    Author

    well now bytestrings and strings cannot be merged without converting one to the other

  8. ri938 commented on Jan 18, 2020

    @ri938
    Author

    this is just an example to show that we will have to convert between the two numpy arrays regularly and its slow
    Our tables of numpy arrays take about 1s to convert between bytestring and string columns when we have to do that

  9. eric-wieser commented on Jan 18, 2020

    @eric-wieser
    Member

    It sounds like in your python2 code, all your strings are already bytestrings. Have you considered just keeping them as bytestrings everywhere in python 3, which means you'll have exactly as many conversions as you did before? That sounds less bad than being trapped in 2.

  10. ri938 commented on Jan 18, 2020

    @ri938
    Author

    I would have to look into this -- I will see how much of a rewrite this requires. Thanks for the help.

  11. charris commented on Jan 18, 2020

    @charris
    Member

    I suspect that this may be a common problem for some applications that are just now making the move to Python 3, so we would be happy to implement a solution if we could figure out what that was. I'm going to reopen this so you can keep us updated and make suggestions.

  12. ri938 commented on Jan 18, 2020

    @ri938
    Author

    Here is roughly our use case for future reference:

    • we have ordered dictionaries with numpy array values which we find is much more efficient than pandas in general (allthough we sometimes convert to a pandas array for some tasks like merging)
    • a typical dictionary has values length 3 million and about 70 keys or which about 30 values are string numpy arrays
    • to convert one of these numpy string arrays from string to bytestring or the reverse takes about 0.8s
    • because we use so many strings the memory difference in python3 to use strings only is a lot
  13. charris commented on Jan 18, 2020

    @charris
    Member

    @ri938

    When do you need to make the conversions?

  14. 18 remaining items

  15. eric-wieser commented on Jan 22, 2020

    @eric-wieser
    Member

    That wasn't clear from your comment above. In that case, you might find you need to implement __array_function__ for each function you need different behavior from. This isn't going to be easy, which is why subclasses are not a good solution for new data-types.

  16. charris commented on Jan 22, 2020

    @charris
    Member

    @eric-wieser Should we be changing some of those functions to use asanyarray?

    @ri938 Might be useful to have a list of functions you find problematic.

  17. rkern commented on Jan 22, 2020

    @rkern
    Member

    It's quite likely that we need to revisit the idea of one or more new encoded-string dtypes to solve this problem rather than an ndarray subtype. The long and contentious previous discussion on the subject. That effort stalled, but we did collect a number of concrete use cases to guide and constrain the design.

  18. ri938 commented on Jan 22, 2020

    @ri938
    Author

    array = EncodedStringArray(['test', 'check'])
    so far I have ran into problems with:

    1. np.array(array) : this will return a bytestring array when I really wanted it to convert to a string array
    2. np.in1d (uses asarray)
    3. np.array_equal (uses asarray)
      I can probably just solve this by replacing 2) and 3) with our own function which calls numpy except for strings which handles it differently
  19. seberg commented on Jan 22, 2020

    @seberg
    Member

    Having a string dtype with encoding seems good. The question is on which time frame we can add that though...

  20. ri938 commented on Jan 23, 2020

    @ri938
    Author

    I have managed to get something working with a custom class to replace all string numpy arrays we use in tables. Its hacky but I want to show you just so you can see what my use case looks like.

    import numpy as np
    
    HANDLED_FUNCTIONS = {}
    
    
    def encode_string_array(arr):
        try:
            arr = arr.astype(np.bytes_)
        except (UnicodeEncodeError, AttributeError):
            arr = np.vectorize(str.encode)(arr, encoding='utf8', errors='strict')
        return arr
    
    
    class EncodedStringArray(np.ndarray):
        """Numpy array for holding strings as bytestrings. This trades
        lower memory use for occasional slower processing times and is to work around
        that python3 numpy strings using 4x as much memory as python2.
    
        See "numpy strings use too much memory #15347"
        """
    
        def __new__(cls, arr):
            arr = np.asarray(arr)
            if np.issubdtype(arr.dtype, np.str_):
                arr = encode_string_array(arr)
            elif arr.dtype.type is not np.bytes_:
                raise TypeError('expected string values')
            self = arr.view(cls)
            return self
    
        def astype(self, *args, **kwargs):
            new = super(EncodedStringArray, self).astype(*args, **kwargs)
            if new.dtype.type is not np.bytes_:
                new = np.array(new)
            if new.dtype.type is np.object_:
                new = new.astype(str).astype(object)
            return new
    
        def argsort(self, *args, **kwargs):
            indexes = super(EncodedStringArray, self).argsort(*args, **kwargs)
            assert indexes.dtype.type is np.int64
            return np.array(indexes, dtype=np.int64)
    
        def __getitem__(self, item):
            ret = np.ndarray.__getitem__(self, item)
            if isinstance(ret, bytes):
                ret = ret.decode(encoding='utf8', errors='strict')
            return ret
    
        def __setitem__(self, key, value):
            if isinstance(value, str):
                value = value.encode(encoding='utf8', errors='strict')
            elif isinstance(value, int):
                value = np.bytes_(str(value))
            elif not isinstance(value, bytes):
                value = np.bytes_(value)
            return np.ndarray.__setitem__(self, key, value)
    
        def __array_finalize__(self, other):
            assert other.dtype.type is np.bytes_
    
        def _format_comparison_input(self, obj):
            if isinstance(obj, str):
                obj = obj.encode(encoding='utf8', errors='strict')
            elif isinstance(obj, np.ndarray) and obj.dtype.type in [np.str_, np.object_]:
                obj = encode_string_array(obj)
            elif isinstance(obj, list):
                obj = encode_string_array(obj)
            return obj
    
        def __eq__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__eq__(self, obj)
    
        def __ne__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__ne__(self, obj)
    
        def __gt__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__gt__(self, obj)
    
        def __lt__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__lt__(self, obj)
    
        def __ge__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__ge__(self, obj)
    
        def __le__(self, obj):
            obj = self._format_comparison_input(obj)
            return np.ndarray.__le__(self, obj)
    
        def __array_function__(self, func, types, args, kwargs):
            if func in HANDLED_FUNCTIONS:
                res = HANDLED_FUNCTIONS[func](*args, **kwargs)
            else:
                res = super(EncodedStringArray, self).__array_function__(func, types, args, kwargs)
            return res
    
    
    def implements(numpy_function):
        """Register an __array_function__ implementation for EncodedStringArray objects."""
        def decorator(func):
            HANDLED_FUNCTIONS[numpy_function] = func
            return func
        return decorator
    
    
    @implements(np.in1d)
    def in1d(ar1, ar2):
        ar2 = np.asarray(ar2, dtype=np.bytes_)
        return np.in1d(np.array(ar1, dtype=np.bytes_), ar2)
    
    
    @implements(np.array_equal)
    def array_equal(ar1, ar2):
        ar2 = np.asarray(ar2, dtype=np.bytes_)
        return np.array_equal(np.array(ar1, dtype=np.bytes_), ar2)```
  21. charris commented on Jan 29, 2020

    @charris
    Member

    Just curious how things are going.

  22. ri938 commented on Jan 29, 2020

    @ri938
    Author

    I consider this complete for us although of all the parts of upgrading to python3 this was the main source of pain and took maybe as long as updating everything else. What I did was:

    1. wrote a numpy array like the one I posted above which uses bytes but behaves as if it contains strings.
    2. I modified our table class which stores this arrays to always make sure strings are as encoded strings. This meant I didnt have to change any code except the table and everything in code base could benefit.
    3. fix a couple of issues in the codebase that I could not resolve: for example np.vectorise was acting on this array as if it was bytestrings and so I have to just avoid using that.
      So I do not require any further help and thanks for the help given.
  23. seberg commented on Nov 6, 2021

    @seberg
    Member

    While I would love to see encoded strings, we can't change NumPy Unicodes and at least right now encoded strings are even mentioned on the "roadmap". (Although, I would prefer if someone would try to start outside of NumPy for now, since the experimental support should be pretty close to useful now)

    In any case, going to close this, since I don't think it is a real TODO item.

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