Repository navigation
Conversation
|
That's awesome! |
Oops, disregard this, must've pressed something by accident. |
|
@amosbird I'm seeing a ubsan failure on functional tests, could you look into it? If you fix it, it's better to rebase to current master, because test reports were broken at that time so we only see '[' in error report. |
|
I see some formatting changes in the lines that are not otherwise touched by this pull request. This leads to some problems:
I'd prefer not to change the formatting of the old code at all, or, if it blatantly violates our style guide, to do it as a separate pull request. |
|
Thanks for reviewing this! The formating and style adjustments are to settle down the changes introduced from my previous FixedHashMap PR. I agree those should be separate commits, however this feature is a long over due and has been refactored multiple times. The original commits aren't reviewable at all thus I've squashed them. |
akuzm
left a comment
There was a problem hiding this comment.
Thanks for the fixes, I will continue with the review. Among other things, I'd like to try adding a performance test for aggregation to our CI.
There was a problem hiding this comment.
It's worth to have a comment about why we use internal iteration, like you described in the pull request, and also mention what arguments the Func should take.
The names of the functions are somewhat unclear. Maybe something like mergeToEmplace -> merge and mergeToFind -> findInBoth?
There was a problem hiding this comment.
Indeed, comments are needed among other places as well. Naming things is hard (https://martinfowler.com/bliki/TwoHardThings.html) . I'm open to suggestions.
There was a problem hiding this comment.
We can probably remove this one as well, I tried and there's no warning.
There was a problem hiding this comment.
Removing that leads to
/home/amos/git/chorigin/dbms/src/Common/ColumnsHashingImpl.h:40:54: error: 'state' may be used uninitialized in this function [-Werror=maybe-uninitialized]
bool check(const Value & value_) { return !empty && value == value_; }
~~~~~~~^~~~~~~~~~~~~~~~~~
There was a problem hiding this comment.
StringHashTableHash doesn't provide a StringRef hash, so the Ts type looks wrong. I don't understand why it compiles. First I thought that it works because the actual hashing is done by dispatch(). To check that, I tried removing the hash function for UInt16, but then it doesn't compile because getHash() is required somewhere. I'm confused now.
There was a problem hiding this comment.
Yeah, that code somehow gets lost when doing refactoring. It compiles because Ts uses SavedHash scheme and dispatch always provides a hash value upon insertion, so getHash() never gets called. I'll add the hash function back.
|
As an aside, I found an interesting benchmark of some hashing algorithms: https://github.com/vnmakarov/mum-hash#intel-i7-9700k MUM looks promising for small strings, and Meow -- for long ones. Both are relatively new, maybe we should test them in the future. |
|
I doubt any of those would beat CRC32 due to hardware acceleration. But it might be useful for |
There was a problem hiding this comment.
So in the end the HashTable decides whether to put the key to arena or not, looking at its type? This looks convoluted. Can we decide this in the caller and just call the proper method? Or even better, just work with Arena in the caller, and not make HashTable know about it at all.
There was a problem hiding this comment.
It's not trivial since StringHashMap has different submaps and only the string submap does allocation. Adding a new method will require multiple if constexpr hanging around
There was a problem hiding this comment.
You mean, because of multiplexing in dispatch(), the callers like HashMethodBase::emplaceKeyImpl() can't know whether they should put the key to Arena or not? This is a problem indeed. Still, I think HashTable is supposed to be a generic container, and so it shouldn't contain any logic specific to the particular use case with StringHashTable and Arena. Maybe we could make this decision in StringHashTable itself?
Or maybe we could move the Arena-related stuff even higher in the call graph. I'll try to find a solution next week, but this will take some time. The hashing-related code in CH seems rather convoluted and I'm having a hard time understanding it.
|
Now that sso is enabled by default, it's strange that we don't see improvement in performance test. There are also some regressions on queries like |
For compound hash tables such as the future StringHashMap, implementing an iterator-based API might be inefficient, because: 1) the information about the component to which the value belongs is lost, and has to be recalculated if the value is reinserted; 2) the key has to be converted to a general format from a from a component-specific format, which may differ between the components. These inefficiencies are especially apparent when merging two hash tables. In contrast, an efficient algorithm would merge a compound table component-wise, avoiding unnecessary conversions and recalculations. Therefore, switch Aggregator to use internal iteration (map-like functions) when traversing and merging the hash tables. This commit prepares for the StringHashMap PR #5417 and contains some of its code.
|
Some benchmark results.
This is median of 38 runs, the spread of results is 5 to 20%. The CPU is Intel(R) Xeon(R) CPU E5-2660 v4 @ 2.00GHz. I'm not sure what the results mean. There is a regression of StringHashMap compared to the HashMapWithSavedHash on long keys. I didn't see this regression on the original version before, but that was on a different machine. It's good to see that the refactoring didn't worsen performance, but I'm also not sure why would it improve performance, especially when we are benchmarking emplace() of the old hash map. Maybe it's the effect of not having to construct a resulting iterator and returning a pointer to mapped value instead (that is change 2.2 from my above big comment). |
It might related to the load factor being too small which triggers edge resize. https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/HashTable/HashTable.h#L159 tweaking it to 80%-95% probably gives more reliable results. |
Some aggregation methods initially emplace a temporary StringRef key into a hash table. Then, if the key was not seen before, they make a persistent copy of the key and update the hash table with it. This approach is not suitable for compound hash tables, because the logic of when the persistent key is needed is more complex, and is contained within the hash table itself. In this commit, we switch to managing key memory with callbacks passed to the hash table, that allow it to request a persistent copy of the key if it is needed. This should be more appropriate for compound hash tables. This commit prepares for StringHashMap PR #5417.
For compound hash tables such as the future StringHashMap, implementing an iterator-based API might be inefficient, because: 1) the information about the component to which the value belongs is lost, and has to be recalculated if the value is reinserted; 2) the key has to be converted to a general format from a from a component-specific format, which may differ between the components. These inefficiencies are especially apparent when merging two hash tables. In contrast, an efficient algorithm would merge a compound table component-wise, avoiding unnecessary conversions and recalculations. Therefore, switch Aggregator to use internal iteration (map-like functions) when traversing and merging the hash tables. This commit prepares for the StringHashMap PR #5417 and contains some of its code.
Some aggregation methods initially emplace a temporary StringRef key into a hash table. Then, if the key was not seen before, they make a persistent copy of the key and update the hash table with it. This approach is not suitable for compound hash tables, because the logic of when the persistent key is needed is more complex, and is contained within the hash table itself. In this commit, we switch to managing key memory with callbacks passed to the hash table, that allow it to request a persistent copy of the key if it is needed. This should be more appropriate for compound hash tables. This commit prepares for StringHashMap PR #5417.
For compound hash tables such as the future StringHashMap, an iterator-based API might be inefficient for iterating over a table or for merging two tables, because: 1) the key has to be converted to a general format from a from a component-specific format, which may differ between the components; 2) the information about the component of the compound hash table to which the value belongs is lost, and has to be recalculated if the value is reinserted. A more efficient approach is to use internal iteration, that is, map-like functions, which avoids unnecessary conversions when iterating, and allows to use an efficient component-wise approach when merging. This commit is a part of the StringHashMap PR #5417.
|
Remember the mysterious ubsan failure? The old ubsan stack was like that, the new msan one is the same. |
|
In master now? You mean it's introduced by the iterator inside out pr ? |
I thought so, but after reverting this PR, it still reproduces. Will investigate further. |
It doesn't reproduce if I revert the key holder patch. The test that fails under MemorySanitizer is 00376_shard_group_uniq_array_of_int_array. I've been looking at this for several hours now, and don't have a slightest idea what is happening. Interestingly, the test doesn't fail if I create the table and wait for the background merges to complete. |
Intriguing. I'll investigate too. What's the cmake command line you use to generate memory sanitizer build? |
|
Hmm, I cannot reproduce with memory sanitizer |
I'm using these flags: Some easy frequent failures are fixed here: #6925 |
|
@akuzm found the cause. It's actually a bug lurking before and gets unveiled by hashtable refactoring. When getting data from Theoretically we'd like to get the same pointer value in https://github.com/yandex/ClickHouse/blob/master/dbms/src/Columns/ColumnArray.cpp#L151 . However, since we have a dedicated ZeroValueStorage in hash table. The pointer of zero lengthed arrays becomes nil after placing into the agg states hash table, which leads to UBSan and MemSan failure. |
|
Some news about what I'm working on now: before, I changed emplace() to return a pointer to Mapped type, not an iterator. I realized that this makes it impossible to support a consecutive keys cache, because the cache must store the persistent key, and there is no way to get it from the table. The code that is now in #6243 is incorrect, it has a use-after-free in HashMethodBase::emplaceImpl, where it stores the key into cache. I'm trying to fix this by returning a different type from emplace() based on the kind of the table. For normal tables, it will return a reference to Cell, and for FixedHashTable or StringHashTable -- pointer to Mapped type. The caller will then get the key and "mapped" value using overloaded functions. There will be no overloads for string or fixed table, but they are not needed, because these tables don't use cache. So hopefully it will work this way. |
|
Yeah, that was a difficulty when I built this hash map, which leads me to disable consecutive caches for certain maps. |
|
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
|
This PR was fully merged as a series of patches ending with #6243. |
I hereby agree to the terms of the CLA available at: https://yandex.ru/legal/cla/?lang=en
For changelog.
Add short_string_optimization settings to optimize short string aggregations.
Category (leave one):
Motivations
There are a lot of string data that acts as an aggregation key all over the place, such as url domains, nick names, key words, rdf attributes, IDs, to name a few. Most of them share a common property: the length is small. A few of them have low cardinalities and are well handled by ClickHouse now, while others generally don't. Since a major portion of time consuming operations related to short strings are based on hash tables, a better hash table is needed for speeding them up for short string keys. No only will it give better aggregation performance, but also help improve Join, Dict and other analytical functions.
Observations and Current Limitations
Currently strings are represented as StringRefs and a linear probing hash table with saved hash values is used to support all string key related operations. The obvious drawback of this approach is its huge memory overhead. Each short string might results in a StringRef structure that is larger than itself. An naive appproach would be adopting the SSO techniques in major standard libraries that encodes short strings in place of their StringRef structures. However it might lead to even worse memory overhead, and suffer from tons of branch misses due to several branch conditions it introduces.
There are other aspects that can be optimized:
It doesn't make sense to save short keys' hash values
The loaded piece of memory in the hash computation process can be reused.
CRC32 hash works well for both numeric and string values.
We can assume strings don't contain zero bytes in middle. (this might not be true, but can be served as an optimization hint)
Side node: ClickHouse's HashMapWithSavedHash is already very efficient in aggregation workloads. I've tested 10+ hashmaps that are all self-claimed to be the fastest one, none of them runs even closed to HashMapWithSavedHash (+20% - 100%). Oh, there are also maps built via Trie, which are generally slower than hashmaps in aggregation workloads.
Main Ideas and Promising Results
The main idea of this patch is to use string length dispatching so that small string keys will end up in hash tables that are built for integers. It's both CPU and memory efficient than using StringRef for short keys. The outcome is a hashtable that is up to 100% faster than the original one.
Unit Testing
In order to get reliable test results, I did the following steps as a prelude:
add "isolcpus=5,11 rcu_nocbs=5,11" to boot cmdline to isolate a real cpu (hyperthreaded) for testing
sudo python3 -m perf system tuneto set stable cpu frequencynumactl and taskset to make sure local memory access and using the isolated cores
The following tests are all single-threaded.
Map
StringHashMap is up to 100% faster than both HashMap and HashMapWithSavedHash in small string workloads when tested directly (See string_hash_map.cpp). Here are some results: (termN means the key length is subject to binomial distribution with expectation N)
I've also tested StringHashMap with long string dataset (expectation = 48 bytes). It's about 1% slower. I decided to use up to 24 bytes for small strings, same as gcc and clang for their SSO strings. It makes code smaller and properly does faster dispatching.
Aggregation
StringHashMap is consistently more effcient in the aggregation tests (See string_hash_map_aggregation.cpp bench_agg). The improvement is a bit lower (up to 70%) since the actual time spending on hashmap operations are around 70%. (perf shows the two other major operations are: 1. getKey; and 2. agg function). To complete the comparision, I've also tested the merging process (See string_hash_map_aggregation.cpp bench_merge). As we now have more sequencial memory access during map iterations, the merge process runs faster too. Here are some results:
End to End Testing (Parallel 40 Threads)
To validate the efficiency of StringHashMap, I've carried on some e2e tests via the SQL interface. The query I used looks like this:
insert into blackhole select term8, count() from terms group by term8. Here are some results:Memory Consumption Testing
StringHashMap is very memory efficient compared to HashMap. It doesn't use Arena when keys are shorter than 24 bytes. To achieve this, I changed the emplace API to accept an additional Arena argument that is only used when Key is of type StringRef, wihch replaces the onNewKey method. Here are some results:
To further validate the efficiency, I tried grouping 1 billion small string records with high cardinality. StringHashMap consumes 60GB memory while HashMap 100GB. In addition, https://greg7mdp.github.io/parallel-hashmap/ suggests that two level hash tables use memory in a smooth manner. As we already adopted TwoLevelHashMap, StringHashMap makes it even smoother. Note: the table grower used in StringHashMap (or its two level variant) has its glowing rate set to 1, or else we could end up having too many submaps with a very low fill factor. It also helps make testing stable to different dataset, since some dataset might trigger the grow too early, resulting in unfair comparisions.
Additional Testing
I've also tested with some real dataset (100M weibo posting dataset with nickname and number of comments). The name cardinality is around 20M and the length distribution is
Testing SQL:
insert into blackhole select name, count(comments_num) from weibo group by name;. StringHashMap is 25% faster.In addition to the StringHashMap work, I've also built a RobinHoodMap because of its recent fame (https://news.ycombinator.com/item?id=12399989 and rust's default hashmap). It turns out that the performance of a hashmap is heavily related to the workloads it's dealing with. For aggregations, ClickHouse's linear probing hashmap outperforms robinhood map by 20%. In fact, it outperforms all hashmaps I could find, which gives me a really hard time when building the map, since there is really nothing to optimize: the code is dead simple. However, there is indeed an opportunity for string keys to use RobinHoodMap due to its variant length property. This might make StringHashMap more efficient. I'll try to enhance it in near future. Also, for long string keys, there are some chances we can do better too.
Some Implementation Details
Key Dispatching
The key dispatching process is critical for efficiency. It has to do proper inlining, fast memcpying and hash computation, etc. (See comments in StringHashMap.h for detail)
Serialization and Merge
After aggregation, there is a workload for extracting key-values from hashmap into actual blocks. This might be a heavy workload when the grouping key has a high cardinality. Since StringHashMap requires converting different cells into a StringRef representation, it consumes addtional cpu resources. In order to avoid unnecessary data conversion, I've turned the iterator inside out (http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/), and make key disassembling as late as possible, hoping compilers eliminate additional data movements for me. This works well and is even faster due to that strings are stored continuously in the cells, compared to a bunch of randomly allocated StringRef pointers.
LastElemCache
Building the LastElemCache requires the original StringRef key stored, which drags StringHashMap down as we have to convert the numeric representation to a StringRef. To tackle this, I tried reusing the input key and making sure that onExistingKey wouldn't rollback the cache. (There is also a bug discovered in the Serialized method https://github.com/yandex/ClickHouse/blob/master/dbms/src/Common/ColumnsHashingImpl.h#L243) However, enabling LastElemCache still slows down the aggregation by 20% due to code bloating. Luckily, emplacing keys in the numeric hash table has comparable performance to StringRef comparisons, so we can disable the use_cache without possibly introducing regression. To validate this observation, I've generated three datasets, each of them has 100 million same strings with length <= 8, <= 16, and <=24. Hence, all except one operation will end up hitting the LastElemCache if it's enabled. The test result shows that using StringHashMap without cache is as efficient as using HashMap with cache. That's why I have cached disabled for StringHashMap.
TODO
StringHashMap in Join, Dict and others
Apply to serialized method. Need to resolve zeroes in middle
In distributed env the two level hash computation is redundant
Make compatible to non SSE4.2 build and Big Endianness?
Better hash maps for short keys and long keys