Algorithmresearch
Recursive graph bisection for index reordering
Also called BP reordering, Dhulipala bisection ordering.
Orders documents by recursive balanced bisection of the term-document graph, moving documents to minimize a log-gap cost.
- Time
- O(I (m + n log n) log n) total
- Space
- O(n + m) extra
- Where
- I = the iteration limit of each bisection; m = the number of document-term pairs; n = the number of documents
- Model
- Word RAM
- Properties
- not comparison baseddeterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Recursive graph bisection orders the documents of a collection so that the gaps of the posting lists get small. It views the collection as a bipartite graph between terms and documents. It splits the documents into two halves of equal size, then improves the split in a few rounds. In each round it computes for each document the drop in an estimate of the log-gap cost if that document moved to the other half, sorts each half by this gain, and swaps the leading pairs while the sum of their gains is positive. Then it orders each half the same way, down to single documents. Dhulipala and others published it in 2016, and it is often called BP. The problem it attacks, and other ways to attack it, are on the page document identifier reassignment. The swap step is the idea of Kernighan-Lin, but with a different cost: Kernighan-Lin counts the edges cut, while this method counts the bits of the gaps. It is a heuristic with no approximation guarantee, and its gains are measured on real collections, not proved.
In plain words
An index stores, for each word, the numbers of the documents that contain it, as the gaps from one number to the next. Small gaps take few bits. So documents that share words should get numbers close to each other. This method finds such numbers by cutting. It cuts the documents into two equal piles, and then moves documents between the piles so that each word is, as much as possible, in only one pile. Then it cuts each pile in two and does the same again, and so on, until each pile has one document. The order of the piles gives the new numbers. Nothing promises that the result is good. It works well on real web pages, and it can lose on small or random sets.
The problem
The input is a collection of documents, each a set of terms. A document order is a permutation that gives each document a new id from 1 to . For a term whose documents get the ids , the gaps are . The log-gap cost of the order is the sum, over all terms and all their gaps , of the bit length . The goal is an order of small cost. Dhulipala and others show that finding an order of least cost is NP-hard for their objective, the sum of over the gaps, so the method aims for a good order, not the best one.
The algorithm
For one bisection of a list into halves and , let and be the numbers of documents in and in that contain term . The method estimates the cost of as if its documents were spread evenly in each half, so that the average gap in is :
The gain of a document is the drop of if that document alone moves to the other half. A large gain means the document fits the other half better.
BP(D, depth) ▷ D: a list of documents, each a set of terms- 1
if |D| ≤ leaf size or depth = depth limit then return D - 2
A ← the first ⌈|D|/2⌉ documents of D, B ← the rest - 3
repeat at most I times - 4
for each term t: a_t ← number of documents of A with t, b_t ← number of documents of B with t - 5
for each v in A: gain(v) ← sum over t in v of c(a_t, b_t) - c(a_t - 1, b_t + 1) - 6
for each v in B: gain(v) ← sum over t in v of c(a_t, b_t) - c(a_t + 1, b_t - 1) - 7
sort A and B by decreasing gain - 8
k ← the largest k such that gain(A[i]) + gain(B[i]) > 0 for every i < k - 9
if k = 0 then stop the loop - 10
exchange A[i] and B[i] for every i < k - 11
return BP(A, depth + 1) followed by BP(B, depth + 1)
Document at position of the result gets the new id . The original paper uses iterations, and the implementation uses the same default. Line L7 breaks ties by the original id, so the method is deterministic.
Example
Take 8 documents on two topics, in an order that mixes them:
| id | terms | id | terms |
|---|---|---|---|
| 1 | sort merge | 5 | sort merge array |
| 2 | sort array | 6 | hash table |
| 3 | merge array | 7 | key table |
| 4 | hash key | 8 | hash key table |
In the input order the log-gap cost is 32 bits. For example, the term hash is in documents 4, 6 and 8, with gaps 4, 2 and 2 of 3, 2 and 2 bits.
First level. and . In the degrees are 2 for sort, merge and array, and 1 for hash and key. In they are 1 for sort, merge and array, 2 for hash and key, and 3 for table. The gains are 0 for documents 1, 2 and 3, and 3.66 for document 4. In they are 5.49 for document 5 and for documents 6, 7 and 8. After the sort, the first pair is with sum 9.15, and the second pair has sum , so and documents 4 and 5 change sides. In the next round every gain is negative, and the loop stops. Now holds one topic and the other, and the cost of the order is 29 bits.
Second level. In the halves are and . The gains are 1.83 for documents 1, 2 and 5, and 0 for document 3, so both pairs have a positive sum and the two halves trade all their documents. That leaves the same split, and it happens again in each round. After 20 rounds is first, and the gain sort puts 5 before 3. The other half gives in the same way.
The final order is , with a cost of 27 bits. A search over all orders finds no order below 27, so here the method finds an optimal order, while the median order costs 32.
On the toy collection of the information retrieval pages the method does worse. The input order of its 8 documents costs 169 bits, the method gives 178, one round per level gives 164, and the best of all orders is 148. These are the measured results of this implementation, and they show that the cost can go up.
Correctness
The proof shows that each round keeps and a split of with the same sizes, that the recursion ends because both halves are strictly smaller, and so that the output is a permutation of the documents. There is no claim about the cost. The gain of line L5 or L6 is exact for one move alone, but line L10 makes many moves at once, each of which changes the degrees that the other gains used. The estimate also ignores the order inside each half. So a round can make the estimate worse, and the final order can be worse than the input. The tests check that the output is a permutation, that the cost function agrees with a separate walk over the positions, that the method lowers the cost on collections with planted topics, and that it raises the cost on some random collections.
Proof: Recursive graph bisection ends and returns a permutation of the documentsfull
Let be a list of distinct documents, each a set of terms, and let the parameters be an iteration limit , a leaf size and a depth limit. The claim is that ends and returns a list that holds each document of exactly once. The claim says nothing about the cost of the order. The method is a heuristic, and the last paragraph explains why no step of it gives a bound on the cost.
-
One iteration keeps and a balanced split of . Line L2 sets to the first documents of and to the rest, so and are disjoint and their union is . Lines L4 to L6 only read and . Line L7 reorders each list, which changes neither its set nor its size. Line L10 exchanges and for , with . Each such step moves one document from to and one from to . So after line L10, and are again disjoint, their union is still , and and as before. By induction on the number of iterations, this holds when the loop of line L3 ends.
-
The loop of line L3 ends. It runs at most times. Each run of lines L4 to L10 does a finite amount of work: one pass over the terms of each document, two sorts and at most exchanges. Line L9 may stop it sooner.
-
The recursion ends. If line L1 does not return, then , so . Then , and by step 1 both calls of line L11 get a list strictly shorter than . The length cannot drop below 0, so every chain of calls ends at line L1.
-
The output is a permutation of . By strong induction on . If line L1 returns, the output is itself. Otherwise, by step 3 and the hypothesis, is a permutation of and is a permutation of . Line L11 returns their concatenation. By step 1, and are disjoint with union , so each document of occurs in exactly one of the two parts, exactly once.
What the gains mean. For a term with documents in and in , the estimate is the bit cost of the gaps of if its documents were spread evenly in each half. Line L5 computes, for in , the drop in if alone moved to , and line L6 does the same for in . These are exact for one move against the current degrees. Line L10 then makes exchanges at once, and each exchange changes the degrees that the other gains assumed. So the total change of the estimate is not the sum of the gains, and the estimate can go up in an iteration. If all pairs are exchanged and , the two halves simply trade places, which leaves the split the same. Also, the estimate is not the true log-gap cost of the final order, which depends on the order inside each half and on the levels below. For these reasons the method has no approximation guarantee. The tests measure its effect: it lowers the cost on collections with planted topics, and it raises the cost on the toy collection and on some random inputs.
Complexity
One round at a list of documents with document-term pairs counts the degrees and the gains in time and sorts the two halves in time. The lists at one level of the recursion are disjoint, so a level costs in total. The recursion has levels, which gives time. The degree tables and the gains take space. The paper runs the method on collections of millions of documents, and the two halves at each level can be done in parallel.
Properties
- Deterministic. With ties broken by id, the same input gives the same order.
- Balanced. Every split has halves whose sizes differ by at most one, so the recursion depth is .
- Nested. Once a level puts a document in a half, the levels below keep it in that half.
- No guarantee. Nothing bounds the cost of the result in terms of the best cost.
Variants and improvements
- Depth limit. Stop the recursion at a fixed depth and keep the input order inside each leaf, which saves time when the leaves are small runs of similar documents.
- Other orders first. Start from a URL order or a MinHash order instead of the input order, so that the first split is already good.
- Graph compression. The paper applies the same method to the adjacency lists of social graphs, as in web graph compression, with the vertices on both sides of the bipartite graph.
- Other partitioners. General tools for graph partitioning, such as multilevel schemes, minimize the edges cut and do not model the gaps. Swaps of single vertices as in Fiduccia-Mattheyses are another option for the local step.
When to use it
Use it to renumber the documents of a static collection before the index is built, when the size of the index matters and an offline pass over the collection is affordable. It suits codes that gain from small gaps or dense clusters, such as partitioned Elias-Fano. For a collection that grows all the time, the ids must stay stable, and the method only applies to new segments. On a small or random collection it may not help, so measure the cost before and after.
Pitfalls
- It can make the order worse. On the toy collection the cost goes from 169 to 178 bits. Keep the input order if the measured cost does not drop.
- The halves can trade places. If the gains are all positive, line L10 exchanges every pair, which leaves the split the same and wastes the round. The result then depends on the number of rounds being odd or even.
- Keep the gains exact. If the sum of a gain depends on the order of a hash set, rounding can flip ties and the method stops being deterministic. Sum the terms in a fixed order, or use an exactly rounded sum.
- Do not count the gain of the whole round as the sum of the gains. The degrees change with each swap.
- The model is an estimate. It assumes that the documents of a term spread evenly in each half, which is not true for small halves.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.
Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""
DOCS = {
1: "binary search finds a key in a sorted array",
2: "merge sort merges two sorted runs into one sorted array",
3: "an inverted index maps each term to a posting list",
4: "a posting list is a sorted list of document ids",
5: "skip pointers speed up the merge of two posting lists",
6: "a hash table finds a key in constant expected time",
7: "search engines rank documents by a score for the query",
8: "the sorted array of ids is compressed with gap encoding",
}
N = len(DOCS)
QUERIES = {
"q1": "sorted array search",
"q2": "posting list merge",
"q3": "rank documents",
"q4": "quantum circuit",
}
# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
"q1": {1: 2, 2: 1, 8: 1},
"q2": {5: 2, 4: 1, 3: 1},
"q3": {7: 2},
"q4": {},
}
# A fixed run for the metric pages, as scores per query.
RUN = {
"q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}
def tokenize(text):
"""Lower-case words split on spaces."""
return text.lower().split()
_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}
def tf(term, doc_id):
"""Number of times term occurs in document doc_id."""
return _TOKENS[doc_id].count(term)
def df(term):
"""Number of documents that contain term."""
return sum(1 for toks in _TOKENS.values() if term in toks)
def cf(term):
"""Number of occurrences of term in the whole collection."""
return sum(toks.count(term) for toks in _TOKENS.values())
def doc_len(doc_id):
"""Number of tokens in document doc_id."""
return len(_TOKENS[doc_id])
def avgdl():
"""Average document length in tokens."""
return sum(len(toks) for toks in _TOKENS.values()) / N
recursive_graph_bisection_reordering.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-graph-bisection-reordering/. The authors are listed in prov/7XKMDW.jsonl.
import math
from collections.abc import Hashable, Iterable, Sequence
def move_cost(a: int, b: int, n_a: int, n_b: int) -> float:
"""The estimated log-gap bits of one term with a documents in a side of n_a and b in a side of n_b."""
cost = 0.0
if a:
cost += a * math.log2(n_a / (a + 1))
if b:
cost += b * math.log2(n_b / (b + 1))
return cost
def bisect_order(
docs: Sequence[Iterable[Hashable]],
iters: int = 20,
leaf_size: int = 1,
max_depth: int | None = None,
) -> list[int]:
"""Order documents 0..n-1 by recursive graph bisection. Returns order, with order[p] the document at position p.
docs[d] holds the terms of document d. This is a heuristic: the result has
no approximation guarantee, and it can be worse than the input order.
"""
terms = [frozenset(t) for t in docs]
if leaf_size < 1 or iters < 0:
raise ValueError("leaf_size must be at least 1 and iters at least 0")
limit = max_depth if max_depth is not None else math.inf
return _bp(list(range(len(terms))), terms, 0, iters, leaf_size, limit)
def _bp(d: list[int], terms: list[frozenset], depth: int, iters: int, leaf: int, limit: float) -> list[int]:
if len(d) <= leaf or depth >= limit: # @line L1
return d
half = (len(d) + 1) // 2
a, b = d[:half], d[half:] # @line L2
n_a, n_b = len(a), len(b)
for _ in range(iters): # @line L3
deg_a: dict = {}
deg_b: dict = {}
for v in a: # @line L4
for t in terms[v]:
deg_a[t] = deg_a.get(t, 0) + 1
for v in b:
for t in terms[v]:
deg_b[t] = deg_b.get(t, 0) + 1
def gain(v: int, to_b: bool) -> float:
parts = []
for t in terms[v]:
x, y = deg_a.get(t, 0), deg_b.get(t, 0)
nx, ny = (x - 1, y + 1) if to_b else (x + 1, y - 1)
parts.append(move_cost(x, y, n_a, n_b) - move_cost(nx, ny, n_a, n_b))
# fsum is exact up to one rounding, so the gain does not depend on the order of the set
return math.fsum(parts)
ga = {v: gain(v, True) for v in a} # @line L5
gb = {v: gain(v, False) for v in b} # @line L6
a.sort(key=lambda v: (-ga[v], v)) # @line L7
b.sort(key=lambda v: (-gb[v], v))
k = 0 # @line L8
while k < min(n_a, n_b) and ga[a[k]] + gb[b[k]] > 1e-12:
k += 1
if k == 0: # @line L9
break
a[:k], b[:k] = b[:k], a[:k] # @line L10
return _bp(a, terms, depth + 1, iters, leaf, limit) + _bp(b, terms, depth + 1, iters, leaf, limit) # @line L11
def log_gap_cost(docs: Sequence[Iterable[Hashable]], order: Sequence[int]) -> int:
"""Bits of the gaps of all posting lists when document order[p] gets id p + 1.
Each gap g, the first id included, costs its binary length floor(log2 g) + 1.
"""
new_id = {d: p + 1 for p, d in enumerate(order)}
postings: dict = {}
for d in sorted(new_id, key=new_id.get):
for t in set(docs[d]):
postings.setdefault(t, []).append(new_id[d])
total = 0
for ids in postings.values():
prev = 0
for i in ids:
total += (i - prev).bit_length()
prev = i
return total
test_recursive_graph_bisection_reordering.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-graph-bisection-reordering/. The authors are listed in prov/7XKMDW.jsonl.
import itertools
import random
from irtoy import DOCS, tokenize
from recursive_graph_bisection_reordering import bisect_order, log_gap_cost, move_cost
EXAMPLE = [s.split() for s in [
"sort merge", "sort array", "merge array", "hash key",
"sort merge array", "hash table", "key table", "hash key table",
]]
def direct_cost(docs: list, order: list[int]) -> int:
"""Walk the positions in order and charge each term the bit length of the gap since its last position."""
last: dict = {}
total = 0
for p, d in enumerate(order):
for t in set(docs[d]):
total += (p + 1 - last.get(t, 0)).bit_length()
last[t] = p + 1
return total
def best_cost(docs: list) -> int:
return min(log_gap_cost(docs, p) for p in itertools.permutations(range(len(docs))))
def planted(rng: random.Random, k: int, per: int) -> list[set]:
"""k topics of per documents each, 8 terms per document, 20% of the terms from a shared vocabulary, shuffled."""
docs = []
for c in range(k):
for _ in range(per):
ts: set = set()
while len(ts) < 8:
ts.add(("shared", rng.randrange(30)) if rng.random() < 0.2 else (c, rng.randrange(30)))
docs.append(ts)
rng.shuffle(docs)
return docs
def test_example() -> None:
n = len(EXAMPLE)
assert log_gap_cost(EXAMPLE, list(range(n))) == 32
assert bisect_order(EXAMPLE, max_depth=1) == [0, 1, 2, 4, 3, 5, 6, 7]
assert log_gap_cost(EXAMPLE, [0, 1, 2, 4, 3, 5, 6, 7]) == 29
order = bisect_order(EXAMPLE)
assert order == [0, 1, 4, 2, 3, 5, 7, 6]
assert log_gap_cost(EXAMPLE, order) == 27 == best_cost(EXAMPLE)
def test_move_cost() -> None:
assert move_cost(0, 0, 4, 4) == 0
assert abs(move_cost(1, 1, 4, 4) - 2.0) < 1e-12
assert abs(move_cost(2, 0, 4, 4) - 2 * 0.4150374992788438) < 1e-12
def test_toy_collection_is_a_case_where_it_loses() -> None:
docs = [tokenize(DOCS[d]) for d in sorted(DOCS)]
assert log_gap_cost(docs, list(range(8))) == 169
assert log_gap_cost(docs, bisect_order(docs)) == 178
assert log_gap_cost(docs, bisect_order(docs, iters=1)) == 164
assert best_cost(docs) == 148
def test_output_is_a_permutation_and_cost_matches() -> None:
rng = random.Random(20261122)
for _ in range(200):
n = rng.randint(0, 40)
docs = [set(rng.sample(range(25), rng.randint(0, 7))) for _ in range(n)]
before = [set(d) for d in docs]
iters = rng.choice([0, 1, 5, 20])
leaf = rng.choice([1, 2, 5])
order = bisect_order(docs, iters=iters, leaf_size=leaf)
assert sorted(order) == list(range(n))
assert docs == before
assert order == bisect_order(docs, iters=iters, leaf_size=leaf)
for o in (order, list(range(n)), rng.sample(range(n), n)):
assert log_gap_cost(docs, o) == direct_cost(docs, o)
if iters == 0:
assert order == list(range(n))
def test_depth_and_leaf_limits() -> None:
rng = random.Random(5)
for n in range(2, 30):
docs = [set(rng.sample(range(10), 3)) for _ in range(n)]
assert bisect_order(docs, max_depth=0) == list(range(n))
assert bisect_order(docs, leaf_size=n) == list(range(n))
half = (n + 1) // 2
one = bisect_order(docs, max_depth=1)
full = bisect_order(docs)
# deeper levels only reorder documents inside the halves of the first level
assert sorted(full[:half]) == sorted(one[:half]) and sorted(full[half:]) == sorted(one[half:])
def test_planted_topics_lower_the_cost() -> None:
for seed in range(8):
rng = random.Random(seed)
docs = planted(rng, rng.choice([2, 4, 8]), rng.choice([8, 16]))
n = len(docs)
assert log_gap_cost(docs, bisect_order(docs)) < log_gap_cost(docs, list(range(n)))
def test_no_guarantee_on_random_input() -> None:
rng = random.Random(1000)
worse = 0
for _ in range(100):
n = rng.randint(2, 30)
docs = [set(rng.sample(range(20), rng.randint(1, 6))) for _ in range(n)]
if log_gap_cost(docs, bisect_order(docs)) > log_gap_cost(docs, list(range(n))):
worse += 1
assert worse > 0
def test_edge_cases() -> None:
assert bisect_order([]) == [] and log_gap_cost([], []) == 0
assert bisect_order([["a"]]) == [0] and log_gap_cost([["a"]], [0]) == 1
assert sorted(bisect_order([[], [], []])) == [0, 1, 2]
for kw in ({"leaf_size": 0}, {"iters": -1}):
try:
bisect_order([["a"]], **kw)
except ValueError:
pass
else:
raise AssertionError("bad parameter was accepted")
History
The question of how document ids affect index size goes back to work on document reordering by Blandford and Blelloch in 2002 and by Shieh and others in 2003, who used clustering and traveling salesman tours. Silvestri showed in 2007 that the URL order of web pages is a strong and cheap baseline. Dhulipala, Kabiljo, Karrer, Ottaviano, Pupyrev and Shalita gave recursive graph bisection at KDD in 2016, with a swap step that follows the idea of Kernighan and Lin from 1970, and they reported smaller indexes than the earlier orders on the Gov2 and ClueWeb09 collections. Mackenzie and others reproduced the method in 2019.
References
- Laxman Dhulipala, Igor Kabiljo, Brian Karrer, Giuseppe Ottaviano, Sergey Pupyrev and Alon Shalita, Compressing graphs and indexes with recursive graph bisection, Proceedings of the 22nd ACM SIGKDD Conference (KDD 2016), arXiv 1602.08820, the log-gap cost model of the bipartite term-document graph, the recursive bisection with the swap of documents by gain, its running time, the NP-hardness of the ordering problem, and the experiments on Gov2 and ClueWeb09
- Compressing inverted indexes with recursive graph bisection, a reproducibility study, the independent implementation of the method and the measured index sizes against other document orders
- B. W. Kernighan and S. Lin, An efficient heuristic procedure for partitioning graphs, Bell System Technical Journal 49(2), 291 to 307, 1970, the balanced bisection improved by swapping pairs of vertices chosen by gain, which the swap step here follows
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7XKMDW Edit this page History Report an error Markdown