Fusion Trees: Sketching Keys
Van Emde Boas trees and y-fast tries answer predecessor queries in . That is excellent for short keys, but for very long words, say , it is and no better than a balanced BST. The fusion tree of Fredman and Willard (1990, journal version 1993) attacks the other end: it is a B-tree whose nodes have keys, and each node finds where a query falls among its keys in word operations. The height is , so a query costs
This lesson builds a fusion node, the part that does the magic, and explains the bounds; the full multiplication-based construction is only sketched.
The problem at one node
A node stores sorted -bit keys and must compute , the number of keys , in time. The parallel comparison trick does that for keys of bits when . Here each key has bits, so of them do not fit in a word. The fusion tree's idea is to compress each key to only the bits that matter.
Branching bits and sketches
Put the keys in a binary trie. The paths of the keys split at most times, at nodes whose depths correspond to bit positions with : the branching bits. (For adjacent keys in sorted order, the highest bit where they differ is a branching bit, and every branching bit arises this way.) The sketch of a key keeps only those bits:
Lemma. The sketches of the node's keys are in the same order as the keys. Two keys first differ (from the top) at a branching bit, and every higher branching bit is equal in both, so comparing sketches compares exactly that bit.
So the node stores sketches of bits each, bits in all, which fits in one word when , and one parallel comparison ranks a sketch among them. The catch: for a query , which is not one of the keys, can be wrong, because may leave the trie at a non-branching bit, where the sketch does not look.
Fixing the rank: the "desketch" step
- Compute $i = $ rank of among the sketches. One can show that the key sharing the longest common prefix with is or . Compare with both (an XOR and an msb each) and keep the longer common prefix; let be the first bit position, from the top, where differs from it. That is where leaves the trie.
- If bit of is 1, every key in the subtree that left is smaller than . Form = ('s bits above and at ) followed by all ones. Then is in the same position as relative to all keys, and 's sketch ranks correctly: rank = number of sketches .
- If bit of is 0, symmetrically form = prefix followed by all zeros, and rank = number of sketches .
Everything here is word operations, given an sketch and an msb. The program builds a node from 8 keys that agree except in three small groups of bits, prints the keys and their sketches, and checks the procedure against binary search on 20000 queries. The sketches are computed with a loop for clarity, and the rank among sketches with bisect, which one parallel comparison does in a real node.
import bisect, random
W = 64
def branching_bits(keys):
"""Bit positions (counted from the least significant bit) where the trie paths of the keys split."""
bits = set()
ks = sorted(keys)
for a, b in zip(ks, ks[1:]): # adjacent keys: their first differing bit is a branching bit
bits.add((a ^ b).bit_length() - 1)
return sorted(bits)
def sketch(x, bits):
s = 0
for i, b in enumerate(bits): # perfect sketch: the bits of x at the branching positions
s |= ((x >> b) & 1) << i
return s
class FusionNode:
def __init__(self, keys):
self.keys = sorted(keys)
self.bits = branching_bits(self.keys)
self.sk = [sketch(x, self.bits) for x in self.keys]
assert self.sk == sorted(self.sk), "sketches keep the order of the keys"
def _rank_sketch(self, s): # one parallel comparison in a real fusion node
return bisect.bisect_right(self.sk, s)
def rank(self, y):
"""Number of node keys <= y, using only sketches plus O(1) word operations."""
i = self._rank_sketch(sketch(y, self.bits))
# The key with the longest common prefix with y is keys[i-1] or keys[i]. Find that prefix length.
cands = [self.keys[j] for j in (i - 1, i) if 0 <= j < len(self.keys)]
x = max(cands, key=lambda c: W - (c ^ y).bit_length())
if x == y:
return self.keys.index(x) + 1
p = (x ^ y).bit_length() - 1 # first bit (from the top) where y leaves the trie
if (y >> p) & 1: # y goes right where the trie has only a left path:
e = (y >> p << p) | ((1 << p) - 1) # its prefix, then all ones; every key below is < e
return bisect.bisect_right(self.sk, sketch(e, self.bits))
e = y >> p << p # y goes left: prefix, then zeros; keys below are > e
return bisect.bisect_left(self.sk, sketch(e, self.bits))
rng = random.Random(1990)
base = rng.getrandbits(W)
keys = sorted({base ^ (rng.getrandbits(3) << 52) ^ (rng.getrandbits(2) << 30) ^ (rng.getrandbits(2) << 9) for _ in range(8)})
node = FusionNode(keys)
print("branching bits:", node.bits)
for x in sorted(keys):
print(f"{x:064b} sketch {sketch(x, node.bits):0{len(node.bits)}b}")
bad = 0
for _ in range(20000):
y = rng.getrandbits(W) if rng.random() < 0.9 else rng.choice(keys) ^ (1 << rng.randrange(8))
if node.rank(y) != bisect.bisect_right(node.keys, y): bad += 1
print("rank errors in 20000 queries:", bad)branching bits: [9, 30, 31, 52, 53, 54]
0101011100000110011000101001111100000011010010010111101110011000 sketch 000001
0101011100000110011000101001111111000011010010010111110110011000 sketch 000110
0101011100010110011000101001111110000011010010010111110110011000 sketch 001100
0101011100110110011000101001111100000011010010010111111110011000 sketch 011001
0101011101000110011000101001111100000011010010010111100110011000 sketch 100000
0101011101000110011000101001111101000011010010010111100110011000 sketch 100010
0101011101010110011000101001111100000011010010010111100110011000 sketch 101000
0101011101010110011000101001111100000011010010010111101110011000 sketch 101001
rank errors in 20000 queries: 0
Sixty-four-bit keys, six-bit sketches, and the rank comes out right for every query, including the ones built by flipping a single bit of a key, which leave the trie at non-branching bits.
Computing a sketch in : multiplication
Extracting scattered bits into consecutive positions is not a standard word operation (x86 has pext, but the model does not). Fredman and Willard's insight is that an approximate sketch is enough: the bits in the right order, at fixed positions spread over a window of bits with zeros in between. Mask to its branching bits, then multiply by :
If the sums are all distinct, no two terms collide and there are no carries, so bit of the product is exactly . If moreover , these "diagonal" bits keep their order, and masking them out gives the approximate sketch. Fredman and Willard show that shifts with all of these properties exist with the diagonal inside a window of bits. The program finds shifts greedily for the node above (placing the window just above the highest branching bit) and checks the result.
import random
def branching_bits(keys):
ks = sorted(keys)
return sorted({(a ^ b).bit_length() - 1 for a, b in zip(ks, ks[1:])})
def find_multiplier(bits):
"""Shifts m_j with all b_i + m_j distinct and b_0 + m_0 < b_1 + m_1 < ... (greedy)."""
ms, used, last = [], set(), bits[-1] - 1 # place every sketch bit above the highest b_i
for b in bits:
m = max(0, last - b + 1)
while any(bi + m in used for bi in bits):
m += 1
ms.append(m)
used |= {bi + m for bi in bits}
last = b + m
return ms
def approx_sketch(x, mask, M, pos_mask, shift):
return (((x & mask) * M) & pos_mask) >> shift # AND, multiply, AND, shift: O(1) word operations
def perfect_sketch(x, bits):
return sum(((x >> b) & 1) << i for i, b in enumerate(bits))
rng = random.Random(1990)
base = rng.getrandbits(64)
keys = sorted({base ^ (rng.getrandbits(3) << 52) ^ (rng.getrandbits(2) << 30) ^ (rng.getrandbits(2) << 9) for _ in range(8)})
bits = branching_bits(keys)
ms = find_multiplier(bits)
pos = [b + m for b, m in zip(bits, ms)]
mask = sum(1 << b for b in bits)
M = sum(1 << m for m in ms)
pos_mask = sum(1 << p for p in pos)
print("branching bits b_i:", bits)
print("shifts m_i: ", ms)
print("sketch bit lands at b_i + m_i:", pos, f"span {pos[-1] - pos[0] + 1} bits (r = {len(bits)}, r^4 = {len(bits) ** 4})")
ap = [approx_sketch(x, mask, M, pos_mask, pos[0]) for x in keys]
for x, a in zip(keys, ap):
print(f"perfect {perfect_sketch(x, bits):06b} approximate {a:0{pos[-1] - pos[0] + 1}b}")
print("approximate sketches sorted like the keys:", ap == sorted(ap))branching bits b_i: [9, 30, 31, 52, 53, 54]
shifts m_i: [45, 25, 28, 8, 11, 14]
sketch bit lands at b_i + m_i: [54, 55, 59, 60, 64, 68] span 15 bits (r = 6, r^4 = 1296)
perfect 000001 approximate 000000000000001
perfect 000110 approximate 000000000100010
perfect 001100 approximate 000000001100000
perfect 011001 approximate 000010001000001
perfect 100000 approximate 100000000000000
perfect 100010 approximate 100000000000010
perfect 101000 approximate 100000001000000
perfect 101001 approximate 100000001000001
approximate sketches sorted like the keys: True
The product here needs about bits, more than one 64-bit word; the real construction accounts for this (the product of two words is a double word, and the shifts are chosen so the window lands where it can be read). With keys and branching bits, the approximate sketches of bits take bits: one word. Then:
- sketch of a query: AND, multiply, AND, shift, ;
- rank among the node's sketches: one parallel comparison, ;
- the desketch step: XORs, msb (constant time with multiplication, The Word-RAM Model), one more sketch and comparison, .
In C++
A fusion node with perfect sketches, built on 200 random nodes of 8 clustered keys and checked against std::upper_bound on 100000 queries. On x86 with BMI2 the sketch loop is a single _pext_u64 instruction; the multiplication trick is what makes the same step on a machine without one.
#include <algorithm>
#include <bit>
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>
using u64 = std::uint64_t;
class FusionNode {
std::vector<u64> keys;
std::vector<int> bits; // branching bit positions, ascending
std::vector<u64> sk; // sketches, sorted like the keys
u64 sketch(u64 x) const { // perfect sketch (hardware: _pext_u64 with the mask of the bits)
u64 s = 0;
for (std::size_t i = 0; i < bits.size(); ++i) s |= ((x >> bits[i]) & 1) << i;
return s;
}
public:
explicit FusionNode(std::vector<u64> ks) : keys(std::move(ks)) {
std::sort(keys.begin(), keys.end());
for (std::size_t i = 0; i + 1 < keys.size(); ++i) bits.push_back(std::bit_width(keys[i] ^ keys[i + 1]) - 1);
std::sort(bits.begin(), bits.end());
bits.erase(std::unique(bits.begin(), bits.end()), bits.end());
for (u64 x : keys) sk.push_back(sketch(x));
}
std::size_t branching() const { return bits.size(); }
std::size_t rank(u64 y) const { // number of keys <= y
std::size_t i = std::upper_bound(sk.begin(), sk.end(), sketch(y)) - sk.begin();
u64 best = 0; int best_len = -1; // neighbour with the longest common prefix
for (std::size_t j : {i - 1, i}) {
if (j >= keys.size()) continue; // i - 1 wraps around when i == 0
int len = std::countl_zero(keys[j] ^ y);
if (len > best_len) { best_len = len; best = keys[j]; }
}
if (best == y) return std::upper_bound(keys.begin(), keys.end(), y) - keys.begin();
int p = 63 - best_len; // where y leaves the trie
if ((y >> p) & 1) {
u64 e = (y >> p << p) | ((u64{1} << p) - 1);
return std::upper_bound(sk.begin(), sk.end(), sketch(e)) - sk.begin();
}
u64 e = y >> p << p;
return std::lower_bound(sk.begin(), sk.end(), sketch(e)) - sk.begin();
}
};
int main() {
std::mt19937_64 rng(1990);
int nodes = 0, errors = 0, queries = 0;
for (int t = 0; t < 200; ++t, ++nodes) {
u64 base = rng();
std::vector<u64> ks;
for (int i = 0; i < 8; ++i) {
u64 flips = rng() & 0xFF; // one rng() call per statement:
int at = static_cast<int>(rng() % 56); // the order of evaluation is then fixed
ks.push_back(base ^ (flips << at));
}
std::sort(ks.begin(), ks.end());
ks.erase(std::unique(ks.begin(), ks.end()), ks.end());
FusionNode node(ks);
if (t == 0) std::printf("first node: %zu keys, %zu branching bits\n", ks.size(), node.branching());
for (int q = 0; q < 500; ++q, ++queries) {
u64 y = rng();
if (q % 2 == 0) { // half the queries: a key with one bit flipped
u64 k = ks[rng() % ks.size()];
y = k ^ (u64{1} << (rng() % 64));
}
std::size_t want = std::upper_bound(ks.begin(), ks.end(), y) - ks.begin();
errors += node.rank(y) != want;
}
}
std::printf("%d nodes, %d queries, %d rank errors\n", nodes, queries, errors);
}first node: 8 keys, 7 branching bits
200 nodes, 100000 queries, 0 rank errors
The fusion tree and its bounds
A fusion tree is a B-tree with fan-out whose nodes are fusion nodes. A query visits nodes and spends at each.
- Static fusion tree (Fredman and Willard): worst-case query time and space. Building a node takes time polynomial in , so preprocessing is in their construction; later constructions are faster.
- Dynamic sets: updates must rebuild the sketches of a node. Pătrașcu and Thorup (2014) gave dynamic fusion nodes with -time updates, which yields time per operation, deterministic, with linear space.
- The model uses multiplication. Andersson, Miltersen and Thorup (1999) showed that fusion trees can also be implemented with AC operations plus some non-standard ones.
Combining with van Emde Boas:
Use a y-fast trie when and a fusion tree otherwise. The query time is , and since the minimum of two positive numbers with product is at most ,
for every . So predecessor search on a word-RAM takes time with space, a bound independent of (randomized through the y-fast trie's hashing). The program tabulates the two terms.
import math
def depth(n, k):
return math.ceil(math.log(n) / math.log(k))
print(f"{'n':>8} {'w':>6} | {'lg n':>5} {'lg w':>5} {'log_w n':>8} {'min':>5} {'sqrt(lg n)':>10}")
for n in [2 ** 20, 2 ** 40, 2 ** 64]:
for w in [64, 2 ** 10, 2 ** 16]:
if w < math.log2(n): continue
lgn, lgw = math.log2(n), math.log2(w)
logwn = lgn / lgw
print(f"2^{int(lgn):<6} {w:>6} | {lgn:5.0f} {lgw:5.0f} {logwn:8.2f} {min(lgw, logwn):5.2f} {math.sqrt(lgn):10.2f}")
k = 64 ** 0.2
print(f"w = 64: fusion-node fan-out w^(1/5) = {k:.2f}, so a fusion tree on 2^20 keys has depth {depth(2 ** 20, 2)}") n w | lg n lg w log_w n min sqrt(lg n)
2^20 64 | 20 6 3.33 3.33 4.47
2^20 1024 | 20 10 2.00 2.00 4.47
2^20 65536 | 20 16 1.25 1.25 4.47
2^40 64 | 40 6 6.67 6.00 6.32
2^40 1024 | 40 10 4.00 4.00 6.32
2^40 65536 | 40 16 2.50 2.50 6.32
2^64 64 | 64 6 10.67 6.00 8.00
2^64 1024 | 64 10 6.40 6.40 8.00
2^64 65536 | 64 16 4.00 4.00 8.00
w = 64: fusion-node fan-out w^(1/5) = 2.30, so a fusion tree on 2^20 keys has depth 20
The last line is a reminder that fusion trees are a theoretical result: for the fan-out is about 2, so the constants make them slower than a plain B-tree. The idea, sketching keys to the bits that distinguish them, is used in practice in compressed tries and in SIMD search nodes.
Test yourself
Why do the sketches of a node's keys sort in the same order as the keys?
- Because the branching bits are the top bits
- Because two keys first differ at a branching bit, and all higher branching bits are equal in both
- Because sketches are computed by multiplication
- They do not; only approximately
Why is not always the rank of a query ?
- Sketches overflow the word
- may leave the trie at a bit that is not a branching bit, which the sketch ignores
- The parallel comparison is approximate
- Queries must be keys
For which word sizes is the predecessor time largest, as a function of ?
- , i.e. , where both terms equal
- always