204 points · by djoldman · 3y ago · 63 comments
I think LibreOffice might do this. It always picks blue and orange for the first 2 series in a chart. But you can keep picking and it always has more colors that are just slightly different than all the previous ones.
The idea is roughly:
Say you have a hashtable of size 1024. You then create x uint arrays of size size 256. These arrays you fill up with random numbers 0-1023.
To get your hash value, you take your input and for i=0..x-1 determine byte k=input[i] you lookup the value in array[i][k]. These lookup values are then XORed giving a final random value between 0-1023 ready for inserting into the hash array.
No modulos. No multiplications. You only have to redo the random tables when the size changes from say 1024 to 2048. Easy peacy. Superfast.
Even in the L1 cache, it's hard to beat the mul: A multiplication (which can hash multiple bytes in the case of Fibonacci hashing) has 3 cycles latency on modern x86. A single load, even from L1, is 5, I believe.
Multiplications we're bad 40 years ago, but the year 2020 called and FMAC is incredibly optimized today.
You should still avoid integer division (floating point division is commonly optimized as reciprocal and then multiply). But multiplications are really really fast at least as far back as 2008 or so.
-------
I'm pretty sure multiplication's latency is only 5 clocks, but with all the out of order processing that occurs on modern cores, latency of just 5 ticks is rarely is the bottleneck. (A DDR4 memory load is like 200+ cycles of latency. You shouldn't even worry about 5 cycles like multiplication, especially because those out of order cores will find some work to parallelize in that time).
-----
> you lookup the value in array[i][k]
You know a L1 cache lookup these days is like 4 cycles of latency right? And I'm pretty sure you have fewer load/store units than multiplication units. So a load/store, even to L1 cache, might use more resources than the multiply.
Might, I'd have to benchmark to be sure.
" Zobrist hashing is the first known instance of the generally useful underlying technique called tabulation hashing. "
so to https://en.wikipedia.org/wiki/Tabulation_hashing
"
In computer science, tabulation hashing is a method for constructing universal families of hash functions by combining table lookup with exclusive or operations. It was first studied in the form of Zobrist hashing for computer games; [...]
Despite its simplicity, tabulation hashing has strong theoretical properties that distinguish it from some other hash functions. In particular, it is 3-independent: [...]
Because of its high degree of independence, tabulation hashing is usable with hashing methods that require a high-quality hash function, including hopscotch hashing, cuckoo hashing, and the MinHash technique for estimating the size of set intersections.
"
further
" Method: The basic idea is as follows:
First, divide the key to be hashed into smaller "blocks" of a chosen length. Then, create a set of lookup tables, one for each block, and fill them with random values. Finally, use the tables to compute a hash value for each block, and combine all of these hashes into a final hash value using the bitwise exclusive or operation.[1]
"
edit: Memory access (along with div) is pretty much the only slow operation in modern CPUs -- extra pressure on L1 just to have random number is not smart at any rate, heck Marsaglia's xor (random) is likely cheaper than accessing L1, very likely all the latency to be hidden behind the memory access.
Even without getting into SIMD algorithms you could load 8 bytes at a time and pretty easily go faster than that, possibly while using the multiplication instruction for mixing.
This of course ignores that we are not looking up values from a hash table in a vacuum. Other code will also be competing for the cache, and that generally means that everything runs slower because of more cache misses.
But, you don't have to be a bigger expert than Knuth to dismiss an optimization done for hardware say 40 years ago (the circumstances around this particular case I don't know).
Even in that case though it might still be relevant for embedded CPUs.
If it is all so clear and all the armchair experts here have ample experience in the field like they pretend, why is it so hard to run a few benchmarks?
Fibonacci Hashing: The Optimization That the World Forgot - https://news.ycombinator.com/item?id=17328756 - June 2018 (75 comments)
This is just fixing up the hash function, which should have a good enough distribution from the start. And if it did this remapping wouldn't be necessary.
The proper place to add this is in your hash function, to "fix up" the distribution. But then, if your hash function doesn't generate a good enough distribution without this trick you should probably redesign it.
1) A lot of hash tables uses modulo to map a large range to a small range, and this is slow.
2) Fibonacci hashing is according to the author both faster and as a side effect happens to improve on bad inputs.
Yes, you should improve your hash function, but assuming the author is right you should still prefer this over integer modulo to reduce the size of the input hash value to the size of the hash table if you can as a default because it's faster, and the extra mixing is just a bonus.
Also, for library implementations where the implementer has no control over which hash function the user provides, being resistant to pathological inputs is good. Especially if you get it as a free side effect of a performance improvement.
What we're comparing here are these two:
// We're only dealing with sizes of num_slots = 2^b
int key_to_slot1(key) {
return hash(key) & (num_slots - 1);
}
int key_to_slot2(key) {
return (hash(key) * k) >> (64 - b);
}
The only difference is: (1) we're doing an extra multiplication, and (2) we're using the high bits instead of the low bits.This should _only_ help if you use a terrible hash function. I'm also not sure why they claim that integer modulo is slow when the* show how to make it fast by using bitwise AND.
> Also, for library implementations where the implementer has no control over which hash function the user provides, being resistant to pathological inputs is good. Especially if you get it as a free side effect of a performance improvement.
But we're designing the hash table! There's no reason for us to make it possible for the user to provide a custom hash function. We've learnt this before: Instead of letting the user provide `int hashCode(Key key)` (as in Java), we use `void hash(Hash state, Key key)` (as in Rust). The user will tell us which sources of data needs to be hashed, but we can provide the hash function and mixing functionality.
So in other words it helps. The point being that when you're writing a library where you have no control over what people will pass you, you can either punt on doing the best you can and leave it to be the users problem, or when - like in this case - there is a trivially simple option that makes things better you can make it better.
> I'm also not sure why they claim that integer modulo is slow when the* show how to make it fast by using bitwise AND.
They show that integer modulo is slow because a lot of code uses the actual modulo rather than bitwise and (granted often because they assume they need a prime sized hash table to do well).
EDIT: Note that the article specifically also addresses the bitwise and by pointing out that Dinkumware in using that 1) had to compensate by using a more expensive hash for integers, 2) created a situation where implementers providing a custom hash had to be aware that this specific implementation would just throw away the high bits, and pointed out they'd been bitten by that issue several times. It also mentions how Google's google::dense_hash_map did the same thing but without even providing it's own integer hash replacement to compensate.
> But we're designing the hash table! There's no reason for us to make it possible for the user to provide a custom hash function.
He's comparing it to the C++ stdlib. An implementation that is intended to be a drop-in replacement for that needs to abide by similar guarantees, so it is possible to provide a custom hash function for the set of contracts in the libraries he compares with, and it's fairly common to do so.
The logical conclusion is that there is a reason for him to make it possible for the user to provide a custom hash function, because it's what the clients he wants to support expects.
Sure when you have control over the API and you are free to refuse to let users of the API set custom hash functions, just provide a better hash function.
But that is explicitly not the case this article is addressing, so you're arguing against a strawman.
The argument that another solution to this issue is to just refuse to let users provide the hash function would be entirely reasonable, and maybe it'd have been nice if the article started by addressing that.
Technically Rust users are also welcome to provide a custom hash function, it's just that it's defined in terms of an API called by all the stuff which wants to be hashed via the trait named Hasher. You can get a drop-in FNV1a hash for example: https://crates.io/crates/fnv
The mechanics to make all this work in Rust involve a proc macro, so people who want to be able to put a Foozle in a HashMap (or an FNV HashMap, or their own custom hashtable) just write #[derive(Hash,Eq,PartialEq)] above the definition of Foozle telling Rust yeah, just look at the constituent parts of this type and use them to derive functions for equality and hashing the whole type. C++ macros aren't powerful enough to do that, so you'd need a more powerful reflection mechanism and templates to do it I think.
Using a better hash function with a better distribution is orthogonal to mapping hash values to buckets in the table.
https://www.tumblr.com/accidentallyquadratic/153545455987/ru...
Each bucket in the smaller table maps to precisely two buckets in the larger table. The differences are in the lowest bit in the larger table's indices.
If you'd store the product in each entry then you wouldn't need to redo the multiplication when resizing. I suppose that the product would work just as well as the hash value when looking up an entry in a bucket, so you could just store that instead.
* https://en.wikipedia.org/wiki/Smoothsort#cite_note-EWD-796a-...
See for example multiply shift hashing in https://arxiv.org/abs/1504.06804
But that is also not the only issue: If you use powers of two and resort to bitwise and to pick the bucket, you're even more dependent on a good hash function, which may be impossible to guarantee if implementinf APIs that let the user choose hash function as in the article.
Unless you follow the suggestion in this article and uses this method to pick buckets.
[1] https://github.com/Tessil/robin-map/blob/master/include/tsl/...