You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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').
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?
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
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
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.
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.
Reacted by Eric Wieser, Robert Irvine and Zongyi LIU
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
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.
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.
array = EncodedStringArray(['test', 'check'])
so far I have ran into problems with:
np.array(array) : this will return a bytestring array when I really wanted it to convert to a string array
np.in1d (uses asarray)
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
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.
importnumpyasnpHANDLED_FUNCTIONS= {}
defencode_string_array(arr):
try:
arr=arr.astype(np.bytes_)
except (UnicodeEncodeError, AttributeError):
arr=np.vectorize(str.encode)(arr, encoding='utf8', errors='strict')
returnarrclassEncodedStringArray(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)
ifnp.issubdtype(arr.dtype, np.str_):
arr=encode_string_array(arr)
elifarr.dtype.typeisnotnp.bytes_:
raiseTypeError('expected string values')
self=arr.view(cls)
returnselfdefastype(self, *args, **kwargs):
new=super(EncodedStringArray, self).astype(*args, **kwargs)
ifnew.dtype.typeisnotnp.bytes_:
new=np.array(new)
ifnew.dtype.typeisnp.object_:
new=new.astype(str).astype(object)
returnnewdefargsort(self, *args, **kwargs):
indexes=super(EncodedStringArray, self).argsort(*args, **kwargs)
assertindexes.dtype.typeisnp.int64returnnp.array(indexes, dtype=np.int64)
def__getitem__(self, item):
ret=np.ndarray.__getitem__(self, item)
ifisinstance(ret, bytes):
ret=ret.decode(encoding='utf8', errors='strict')
returnretdef__setitem__(self, key, value):
ifisinstance(value, str):
value=value.encode(encoding='utf8', errors='strict')
elifisinstance(value, int):
value=np.bytes_(str(value))
elifnotisinstance(value, bytes):
value=np.bytes_(value)
returnnp.ndarray.__setitem__(self, key, value)
def__array_finalize__(self, other):
assertother.dtype.typeisnp.bytes_def_format_comparison_input(self, obj):
ifisinstance(obj, str):
obj=obj.encode(encoding='utf8', errors='strict')
elifisinstance(obj, np.ndarray) andobj.dtype.typein [np.str_, np.object_]:
obj=encode_string_array(obj)
elifisinstance(obj, list):
obj=encode_string_array(obj)
returnobjdef__eq__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__eq__(self, obj)
def__ne__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__ne__(self, obj)
def__gt__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__gt__(self, obj)
def__lt__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__lt__(self, obj)
def__ge__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__ge__(self, obj)
def__le__(self, obj):
obj=self._format_comparison_input(obj)
returnnp.ndarray.__le__(self, obj)
def__array_function__(self, func, types, args, kwargs):
iffuncinHANDLED_FUNCTIONS:
res=HANDLED_FUNCTIONS[func](*args, **kwargs)
else:
res=super(EncodedStringArray, self).__array_function__(func, types, args, kwargs)
returnresdefimplements(numpy_function):
"""Register an __array_function__ implementation for EncodedStringArray objects."""defdecorator(func):
HANDLED_FUNCTIONS[numpy_function] =funcreturnfuncreturndecorator@implements(np.in1d)defin1d(ar1, ar2):
ar2=np.asarray(ar2, dtype=np.bytes_)
returnnp.in1d(np.array(ar1, dtype=np.bytes_), ar2)
@implements(np.array_equal)defarray_equal(ar1, ar2):
ar2=np.asarray(ar2, dtype=np.bytes_)
returnnp.array_equal(np.array(ar1, dtype=np.bytes_), ar2)```
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:
wrote a numpy array like the one I posted above which uses bytes but behaves as if it contains strings.
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.
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.
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.
Activity
eric-wieser commentedon Jan 18, 2020
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.
In this case, you can use
my_bytes_arr == my_str_scalar.encode('utf8').eric-wieser commentedon Jan 18, 2020
It is exactly equivalent to what python2 called a string.
ri938 commentedon Jan 18, 2020
I know there is way to perform actions on bytestrings but
charris commentedon Jan 18, 2020
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.
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?
ri938 commentedon Jan 18, 2020
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
charris commentedon Jan 18, 2020
So is the problem that pandas cannot use byte strings?
ri938 commentedon Jan 18, 2020
well now bytestrings and strings cannot be merged without converting one to the other
ri938 commentedon Jan 18, 2020
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
eric-wieser commentedon Jan 18, 2020
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.
ri938 commentedon Jan 18, 2020
I would have to look into this -- I will see how much of a rewrite this requires. Thanks for the help.
charris commentedon Jan 18, 2020
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.
ri938 commentedon Jan 18, 2020
Here is roughly our use case for future reference:
charris commentedon Jan 18, 2020
@ri938
When do you need to make the conversions?
18 remaining items
eric-wieser commentedon Jan 22, 2020
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.charris commentedon Jan 22, 2020
@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.
rkern commentedon Jan 22, 2020
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
ndarraysubtype. 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.ri938 commentedon Jan 22, 2020
array = EncodedStringArray(['test', 'check'])
so far I have ran into problems with:
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
seberg commentedon Jan 22, 2020
Having a string dtype with encoding seems good. The question is on which time frame we can add that though...
ri938 commentedon Jan 23, 2020
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.
charris commentedon Jan 29, 2020
Just curious how things are going.
ri938 commentedon Jan 29, 2020
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:
So I do not require any further help and thanks for the help given.
seberg commentedon Nov 6, 2021
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.
Add npz_save() overloaded functions to save directly std::string data.
Add npz_save() overloaded functions to save directly std::string data.
Add npz_save() overloaded functions to save directly std::string data.