TExcelTAD
Home › Advanced & Succinct Data Structures › Fusion Trees: Sketching Keys

Fusion Trees: Sketching Keys

Van Emde Boas trees and y-fast tries answer predecessor queries in O(lg⁡w)O(\lg w). That is excellent for short keys, but for very long words, say w=n0.1w = n^{0.1}, it is Θ(lg⁡n)\Theta(\lg n) 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 k=Θ(w1/5)k = \Theta(w^{1/5}) keys, and each node finds where a query falls among its kk keys in O(1)O(1) word operations. The height is log⁡kn=O(log⁡wn)\log_k n = O(\log_w n), so a query costs

O(log⁡wn)=O ⁣(lg⁡nlg⁡w)O(\log_w n) = O\!\left(\frac{\lg n}{\lg w}\right)

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 kk sorted ww-bit keys x0<⋯<xk−1x_0 < \cdots < x_{k-1} and must compute rank⁡(y)\operatorname{rank}(y), the number of keys ≤y\le y, in O(1)O(1) time. The parallel comparison trick does that for keys of bb bits when k(b+1)≤wk(b + 1) \le w. Here each key has ww bits, so kk 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 kk keys in a binary trie. The paths of the keys split at most k−1k - 1 times, at nodes whose depths correspond to bit positions b0<b1<⋯<br−1b_0 < b_1 < \cdots < b_{r-1} with r≤k−1r \le k - 1: 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:

sketch⁡(x)=x[br−1] x[br−2]⋯x[b0](r bits)\operatorname{sketch}(x) = x_{[b_{r-1}]} \, x_{[b_{r-2}]} \cdots x_{[b_0]} \quad (r \text{ 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 kk sketches of r<kr < k bits each, k2k^2 bits in all, which fits in one word when k≤wk \le \sqrt{w}, and one parallel comparison ranks a sketch among them. The catch: for a query yy, which is not one of the keys, rank⁡(sketch⁡(y))\operatorname{rank}(\operatorname{sketch}(y)) can be wrong, because yy may leave the trie at a non-branching bit, where the sketch does not look.

Fixing the rank: the "desketch" step

  1. Compute $i = $ rank of sketch⁡(y)\operatorname{sketch}(y) among the sketches. One can show that the key sharing the longest common prefix with yy is xi−1x_{i-1} or xix_i. Compare yy with both (an XOR and an msb each) and keep the longer common prefix; let pp be the first bit position, from the top, where yy differs from it. That is where yy leaves the trie.
  2. If bit pp of yy is 1, every key in the subtree that yy left is smaller than yy. Form ee = (yy's bits above and at pp) followed by all ones. Then ee is in the same position as yy relative to all keys, and ee's sketch ranks correctly: rank(y)(y) = number of sketches ≤sketch⁡(e)\le \operatorname{sketch}(e).
  3. If bit pp of yy is 0, symmetrically form ee = prefix followed by all zeros, and rank(y)(y) = number of sketches <sketch⁡(e)< \operatorname{sketch}(e).

Everything here is O(1)O(1) word operations, given an O(1)O(1) sketch and an O(1)O(1) 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.

python · try it yourself
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 O(1)O(1): multiplication

Extracting rr 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 rr bits in the right order, at fixed positions spread over a window of O(r4)O(r^4) bits with zeros in between. Mask xx to its branching bits, then multiply by m=∑j2mjm = \sum_j 2^{m_j}:

(x&mask)⋅m=∑i∑jx[bi] 2bi+mj(x \mathbin{\&} \text{mask}) \cdot m = \sum_{i} \sum_{j} x_{[b_i]} \, 2^{b_i + m_j}

If the r2r^2 sums bi+mjb_i + m_j are all distinct, no two terms collide and there are no carries, so bit bi+mib_i + m_i of the product is exactly x[bi]x_{[b_i]}. If moreover b0+m0<b1+m1<⋯b_0 + m_0 < b_1 + m_1 < \cdots, 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 O(r4)O(r^4) bits. The program finds shifts greedily for the node above (placing the window just above the highest branching bit) and checks the result.

python · try it yourself
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 7070 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 k=w1/5k = w^{1/5} keys and r<kr < k branching bits, the kk approximate sketches of O(r4)O(r^4) bits take O(k5)=O(w)O(k^5) = O(w) bits: one word. Then:

  • sketch of a query: AND, multiply, AND, shift, O(1)O(1);
  • rank among the node's sketches: one parallel comparison, O(1)O(1);
  • the desketch step: XORs, msb (constant time with multiplication, The Word-RAM Model), one more sketch and comparison, O(1)O(1).

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 O(1)O(1) on a machine without one.

cpp · try it yourself
#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 k=Θ(w1/5)k = \Theta(w^{1/5}) whose nodes are fusion nodes. A query visits O(log⁡kn)=O(log⁡wn)O(\log_k n) = O(\log_w n) nodes and spends O(1)O(1) at each.

  • Static fusion tree (Fredman and Willard): O(log⁡wn)O(\log_w n) worst-case query time and O(n)O(n) space. Building a node takes time polynomial in kk, so preprocessing is O(n⋅poly(k))O(n \cdot \text{poly}(k)) 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 O(1)O(1)-time updates, which yields O(log⁡wn)O(\log_w n) 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 AC0^0 operations plus some non-standard ones.

Combining with van Emde Boas: O(lg⁡n)O(\sqrt{\lg n})

Use a y-fast trie when lg⁡w≤log⁡wn\lg w \le \log_w n and a fusion tree otherwise. The query time is O(min⁡(lg⁡w,lg⁡n/lg⁡w))O(\min(\lg w, \lg n / \lg w)), and since the minimum of two positive numbers with product lg⁡n\lg n is at most lg⁡n\sqrt{\lg n},

min⁡(lg⁡w,lg⁡nlg⁡w)≤lg⁡n\min\left(\lg w, \frac{\lg n}{\lg w}\right) \le \sqrt{\lg n}

for every ww. So predecessor search on a word-RAM takes O(lg⁡n)O(\sqrt{\lg n}) time with O(n)O(n) space, a bound independent of ww (randomized through the y-fast trie's hashing). The program tabulates the two terms.

python · try it yourself
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 w=64w = 64 the fan-out w1/5w^{1/5} 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?

  1. Because the branching bits are the top bits
  2. Because two keys first differ at a branching bit, and all higher branching bits are equal in both
  3. Because sketches are computed by multiplication
  4. They do not; only approximately

Why is rank⁡(sketch⁡(y))\operatorname{rank}(\operatorname{sketch}(y)) not always the rank of a query yy?

  1. Sketches overflow the word
  2. yy may leave the trie at a bit that is not a branching bit, which the sketch ignores
  3. The parallel comparison is approximate
  4. Queries must be keys

For which word sizes is the predecessor time O(min⁡(lg⁡w,log⁡wn))O(\min(\lg w, \log_w n)) largest, as a function of nn?

  1. w=lg⁡nw = \lg n
  2. lg⁡w≈lg⁡n\lg w \approx \sqrt{\lg n}, i.e. w=2lg⁡nw = 2^{\sqrt{\lg n}}, where both terms equal lg⁡n\sqrt{\lg n}
  3. w=nw = n
  4. w=64w = 64 always