Skip to content

Use succinct tries for vocabulary storage #2639

Closed as not planned
Closed as not planned

Description

@kmike

Hey,

Python dictionary is quite wasteful for string data, so CountVectorizer, TfidfVectorizer and DictVectorizer all could take much less memory with an another data structure for vocabulary_.

Here is a quick prototype that persists vocabulary_ of CountVectorizer and TfidfVectorizer in MARISA-Trie via Python wrapper: https://gist.github.com/kmike/7814472.

I used this script to measure memory and speed of fit and dump, and this script to measure parameters of load and transform.

The results are quite cool: for '20 newsgroups' data (fit on training subset, transform on test subset) memory consumption of different vectorizers after loading is the following:

  • CountVectorizer(): 94MB;
  • CountVectorizer(ngram_range=(1,2): 666MB;
  • MarisaCountVectorizer(): 1.2MB;
  • MarisaCountVectorizer(ngram_range=(1,2)): 13.3MB;

So using a good succinct Trie implementation gives us 50x-80x reduction of memory usage; it also makes serializing and deserializing almost instant. And such vectorizers don't have HashingVectorizer limitations.

The downside is that fit method is 2x-3x slower and requires slightly more memory (but I think it could be changed to require less memory than CountVectorizer.fit), and transform is about 2x slower. Full output: https://gist.github.com/kmike/7815156

What do you think about adding something similar to scikit-learn?

Activity

  1. kmike commented on Dec 7, 2013

    @kmike
    ContributorAuthor

    to make it clear, memory improvements came because of 3 reasons:

    1. there is no need to store all strings as Python objects - they are generated on fly;
    2. there is no need to store token indices as Python objects - they are also generated on fly; I don't fully understand how does MARISA-Trie work, but I suspect these indices are not stored explicitly and their binary values are just tree paths;
    3. MARISA-Trie itself is more memory efficient than hash table for string storage.
  2. larsmans commented on Dec 7, 2013

    @larsmans
    Member

    I've been thinking about tries to store feature names, but I think it would be hard to maintain them inside the codebase. You don't understand how MARISA-Trie works, I don't, and I don't think anyone does. Is there a non-intrusive way to be able to use these, without introducing dependencies? E.g. a parameter that tells CountVectorizer to use a constructor other than dict for its vocabulary?

    Ping @ogrisel.

  3. jnothman commented on Dec 7, 2013

    @jnothman
    Member

    I don't fully understand how does MARISA-Trie work, but I suspect these indices are not stored explicitly and their binary values are just tree paths

    So are these indices still a complete range from 0 to len(vocabulary)? Can you reorder the vocabulary manually?

    One use-case that needs to be considered for these feature extractors is parallelised extraction where you then need to merge multiple partial vocabularies and partial sparse outputs... I'm not sure how that affects this.

    Like Larsmans, I'm not convinced a dependency on MARISA is worthwhile, but we should consider ways to support alternative Mapping implementations; the way your gist uses MARISA suggests it might not fully implement Mapping in a way that can be dropped in here...

  4. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    @jnothman Yes, these indices are a complete range from 0 to len(vocabulary)-1. You can't reorder them manually, and you can't change MARISA-Trie after building.

    MARISA can implement Mapping interface with a couple of extra methods in a wrapper, I don't think it is an issue. I just haven't done that as a part of this particular proof-of-concept. What you can't do is to build MARISA-based vocabulary as you're building a dict-based vocabulary - it doesn't support adding/deletion of the keys or changing the values (like many other data structures tailored for memory efficiency). This means that simple version of @larsmans's suggestion (pass either dict or Vocabulary to CountVectorizer) won't work.

    "Fit" hack is works this way: first, vocabulary_ dict is learned using standard CountVectorizer.fit - this way we can use standard CountVectorizer preprocessors, things like min_df, etc. Then we create a MARISA-Trie from this dict, and use it like as it was passed as a fixed vocabulary to the constructor.

    By passing fixed vocabulary to constructor I'd had to implement full Mapping interface for Vocabulary class (not important) + duplicate code for vocabulary creation (important). Just replacing vocabulary doesn't work because there is no way to make indices the same as before (without creating an another array for them) - that's why we have to call fit again. fit is 2x-3x slower partially because of that hackish implementation detail.

    @larsmans Non-intrusive way would be to release these custom classes as a separate python package, and maybe change some CountVectorizer internals to make it easier to adapt it for such use cases. But the package most likely won't use these improvements in order to support older sklearn versions. I don't want to go this non-intrusive route before discussing if you sckit-learn folks like it inside the scikit-learn itself / if there is a way to get this into scikit-learn or if it is a bad idea.

    Memory improvements looks quite significant, they can enable e.g. tf*idf on larger training sets. In my recent project I used CountVectorizer and TfIdfVectorizer for development and switched to MARISA-based variants before deploying in order to reduce server-side memory requirements; as far as I know you can't do that with HashingVectorizer.

  5. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    I've re-read the ticket, and it was unclear: I don't propose to replace vocabulary storage for CountVectorizer/etc by default, I propose to add some way to "freeze" the vocabulary to a more efficient readonly data structure when model development is done. Using classes like MarisaTfidfVectorizer is one of the ways; it works OK with Pipeline and FeatureUnion, but better ideas are welcome.

  6. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    Using a regular Trie is quite different: the implementation would be simpler (and faster), it would allow a drop-in dict replacement (and thus it can be used by default), and it could allow saving memory on fit, but memory savings won't be so large (I expect them to be at most 5x-10x, with most of savings coming from removing a need for Python unicode and int objects), and most likely it won't help with serialization/deserialization speed.

  7. larsmans commented on Dec 8, 2013

    @larsmans
    Member

    But if we add a freeze option, that would be rather specific to libmarisa, wouldn't it? Doesn't DAtrie allow incremental construction?

  8. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    I'm not aware of succinct Trie that allows updates. As for Double Array Tries, incremental construction of DAtrie (as implemented in libdatrie) is more like a hack, and it could be very slow, esp. when trie size increases and insertions are random because it could require moving large blocks of memory. Ordered insertion is faster, but it also degrades significantly when data size increases and when keys are long. Most other Double Array Trie implementations are static: darts, darts-clone, DASTrie. From the docs it seems that cedar implementation allows fast updates, but I haven't tried it. It is interesting to check how is it done because fast updates to DATries are not straightforward.

    By the way, cedar docs looks interesting because there is a comparison between some succinct, DA Trie and DAFSA implementations: succinct implementations take 5x-10x less memory than best Double Array Trie implementations on their datasets. It seems that DATries perform better than I expected (maybe my datasets had another properties), but the gap is still quite large.

  9. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    If you need fast insertions/deletions then most likely you use some pointer-based implementation, and this mean extra memory requirements and slower serialization. If you don't need them, you store all data in a contignous block of memory and can use some tricks to reduce the size further.

  10. larsmans commented on Dec 8, 2013

    @larsmans
    Member

    Carrasco and Forcada present an insertion algorithm for DAFSAs. I must admit I've never seen it live.

    Also, any pointer-based FSA or trie can be transformed into a dynamic array-based one by replacing the pointers by indices into the array and resizing it when a new node has to allocated.

  11. kmike commented on Dec 8, 2013

    @kmike
    ContributorAuthor

    Interesting, I didn't know efficient insertions are possible for DAFSAs.

    Right, pointer is an index and RAM is an array, and if we want faster serialization we can do it ourselves, a good point. But it doesn't seem to help with memory usage much, unless we reduce pointer size. Usually Trie implementations are a bit more tricky: in Double Array Tries indices can point to different locations based on their sign; also, they encode "list"-based Tries, but in a such way search is not necessary. Succinct Tries layout is based on other ideas - I don't think it can be seen as an encoding of a "general" DAFSA (as far as I know, it is unknown how to encode DAFSA succinctly).

    What I was trying to prove is that freeze option is not specific to libmarisa, and frozen data structures have some properties that are hard to get from "dynamic" data structures, and it can be good to be able to "freeze" the vocabulary even if some dynamic Trie is used during vocabulary building; these options are not mutually exclusive.

  12. larsmans commented on Dec 8, 2013

    @larsmans
    Member

    The other niceties of indices instead of pointers is that you get to pick how large they need to be, and that serialization means dumping the array to disk :)

    The operations are not mutually exclusive, but the question is how many more options we want to add to TfidfVectorizer. Its API is one of the most heavily overloaded ones in the library.

  13. ogrisel commented on Dec 10, 2013

    @ogrisel
    Member

    Interesting discussion. To wrap up:

    1- what changes to the current vectorizer API are required to make it possible to leverage an external trie-based vocabulary implementation such as the MARISA-Trie implementation you wrapped?

    2- do you think it would be possible to have a builtin, cython based implementation of a trie datastructure in sklearn to be used by default to replace the current dict-based implementation?

  14. kmike commented on Mar 25, 2014

    @kmike
    ContributorAuthor

    Some parts of my #2639 (comment) are incorrect: of course, HashingVectorizer works fine with TfidfTransformer. But you can't do min_df or max_df with HashingVectorizer, and having feature names is nice.

    Rewritten MarisaCountVectorizer which requires updated marisa-trie wrapper (that supports necessary features directly) and doesn't use "call fit_transform twice" hack is available here: https://gist.github.com/kmike/9750796. The speed gap is reduced in this new implementation: for unigrams+bigrams example fit takes 19.4s vs 15.2s, transform takes 6.9s vs 5s (it was about 2x slower previously); memory savings are the same (<15MB vs 600MB+).

    Wrapping up:

    1. If builtin marisa-trie support is not desired (it seems nobody wants it) then [MRG + 2] ENH enable setting pipeline components as parameters #1769 or a simpler solution like Add meta-estimator for switching between estimators #2994 will make it easier to work with classes like MarisaCountVectorizer.

    Another option is to add optional "freeze" step to CountVectorizer. This would remove a need for externally maintained vectorizers. Implementation-wise it could be the similar to https://gist.github.com/kmike/9750796, but instead of hardcoding marisa_trie.Trie the mapping class could be passed to constructor. Mapping class could be set to None by default - it'll mean "no freezing step". We may have to handle fixed vocabulary differently (passing vocabulary to constructor doesn't work in the current implementation), but I'm not sure.

    Semantics of "freezing" is the following: after the fitting replace self.vocabulary_ with a different vocabulary, preserving keys but not preserving indices. User code ("frozen vocabulary constructor") receives feature names and returns new vocabulary; scikit-learn fixes indices in all learned matrices.

    In my implementation I'm also deleting self.stop_words_ after freezing, but this can be optional.

    It looks like a similar freezing step can be implemented for TfidfVectorizer, but reordering of learned arrays will be a bit harder.

    There may be other usages for "freeze" step, e.g. we can make alphabetical feature names sorting optional.

    DictVectorizer is different because it caches feature_names in an attribute. This is not desirable when MARISA-Trie is used: keys can be retreived from MARISA Trie by their ids using restore_key method without materializing all strings as Python objects at the same time. "Freezing" of DictVectorizer is useless if all strings are still in memory. One way to fix it is to make feature_names_ a "property" alias to get_feature_names() function, and make get_feature_names() function compute result on demand from vocabulary (like CountVectorizer is doing). This can also make pickling and unpickling of DictVectorizer faster if I'm not mistaken.

    MARISA Trie also supports memory mapping, but I haven't came up with a good way to integrate this feature with the rest of vectorizers, and I didn't have a need for that - the memory usage is quite low already.

    Does "freezing" sound good, or is it too much for sklearn internals to support?

    1. I think that for CountVectorizer and other sklearn classes it is better to use some kind of radix (patricia) trie when learning vocabulary, or at least a trie that stores "tails" separately. "Standard" trie could be wasteful for n-grams, and n-grams data needs compression most. This makes implementation less straightforward. A good Trie (e.g. a HAT-Trie) implementation can be used by default - it should work roughly as fast as a Python dict and require e.g. 4x less memory during training. But I could be wrong - I haven't tried this with sklearn vectorizers.

    There is often a plenty of memory on desktops, and you can rent a spot amazon instance for a short period of time if memory is not enough, but RAM can be costly for ever-running virtual servers doing predictions - that's why I've been focusing on "freezing" part so far.

  15. GaelVaroquaux commented on Mar 27, 2014

    @GaelVaroquaux
    Member

    I am wondering if it would be to sort the problem of large memory footprint of python dicts by replacing them with a cython wrapper on the c++ map, mapping from strings to ints. I did something similar in sklearn.utils.fast_dict.pyx.

  16. 13 remaining items

  17. kmike commented on Mar 27, 2014

    @kmike
    ContributorAuthor

    Yes, you can't avoid the encoding step - encoding is how you convert your strings to bytes, and IMHO it is better to do that at Cython level because it is compiled to PyUnicode_AsUTF8String in this case.

    There is no branch for these prototypes, just some local files; most of them uploaded to gists. They all reside outside sklearn code. I'll try to come up with a complete set of gists.

    Regarding unordered_map availability - my C++ is rusty, and I can't get Google to show me a nice table for that, sorry.

    While it is nice to have 2x-3x more memory efficient CountVectorizer during training, this is not what this ticket was about initially. It was more about memory reduction at prediction time, not at train time. For example, let's go crazy and use ngram_range=(1,4):

    ./memuse_fit.py count4
    fit time: 52.3s
    fit memory usage: 2312.6MB
    dump time: 361.2s
    dump memory usage: 3498.1MB
    
    ./memuse_transform.py count4
    transform features: 5553070
    load time: 93.8s
    load memory usage: 2691.9MB
    transform time: 10.7s
    transform memory leak: 84.6MB
    
    ./memuse_fit.py marisa_count4
    fit time: 73.3s
    fit memory usage: 2325.2MB
    dump time: 0.1s
    dump memory usage: 1328.9MB
    
    ./memuse_transform.py marisa_count4
    transform features: 5553070
    load time: 0.1s
    load memory usage: 69.1MB
    transform time: 16.5s
    transform memory leak: 63.7MB
    

    For this data MARISA-Trie makes load instant (no 6min dump time and no 1.5min startup time), uses 70MB instead of 2.7GB for prediction and reduces max memory needed for data serialization (it seems my script showed OSX-compressed memory for "dump memory usage: 3498.1MB", it was actually > 4GB for "stock" CountVectorizer). I doubt people use ngram_range=(1,4) in practice much, but there could be other valid memory-intensive applications.

    unordered_map or hat_trie will most likely make memory usage at prediction time the same as at training time, so instead of 40x gain we'd get 2x or 3x or maybe 5x (which is still good).

    What about the following:

    1. add "freezing" support (as described in Use succinct tries for vocabulary storage #2639 (comment));
    2. add support for non-dict vocabularies used in training, but don't provide anything other than dict by default?

    I can work on (1) and (2) if you want, but implementing default vocabulary based on unordered_map or something similar will be too much for me in the near future :)

  18. kmike commented on Mar 27, 2014

    @kmike
    ContributorAuthor
  19. GaelVaroquaux commented on Mar 27, 2014

    @GaelVaroquaux
    Member

    I am OK with the freeze support bit not excited about it.  Because it requires manual operation I get that very few people will use it. I would have preferred something they just works even if it is less good. But it seems that it is not happening. 

  20. ogrisel commented on Mar 28, 2014

    @ogrisel
    Member

    +1 for the freeze support in scikit-learn. And +1 for publishing your MarisaCountVectorizer as a sister project on github referenced from:

    https://github.com/scikit-learn/scikit-learn/wiki/Third-party-projects-and-code-snippets

  21. arjoly commented on Mar 28, 2014

    @arjoly
    Member

    What do you mean for freeze support?

  22. kmike commented on Mar 28, 2014

    @kmike
    ContributorAuthor

    @arjoly by freeze support I mean the following: after fit is done, replace self.vocabulary_ with a different vocabulary, preserving keys but not preserving indices. User code (a callable passed to CountVectorizer.__init__) receives feature names and returns new vocabulary; scikit-learn fixes indices in all learned matrices.

    marisa_trie.Trie class could be used as such callable because its constructor accepts a list of keys and returns a key->index mapping. So if we add this constructor argument then it seems there is no need for a sister project with MarisaCountVectorizer.

  23. larsmans commented on Mar 28, 2014

    @larsmans
    Member

    Yes, unordered_map is C++11. cppreference.com is the best online C++ reference manual.

  24. larsmans commented on Mar 28, 2014

    @larsmans
    Member

    Also +1 for freeze support in general, but I think we need a better name for it. Vocabulary compression? Finalizing?

  25. amueller commented on Oct 5, 2016

    @amueller
    Member

    Should we summarize and close and make a new issue? This one got pretty carried away lol

  26. adrinjalali commented on Apr 17, 2024

    @adrinjalali
    Member

    So it seems the conclusion has been here that we won't be adding this enhancement.

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