Algorithmcore
Reciprocal rank fusion
Also called RRF.
Scores each document by the sum over input rankings of 1/(k + rank), a simple fusion that needs no score calibration.
- Solves
- Rank aggregation
- Time
- O(N + n log n) worst
- Space
- O(n) extra
- Where
- N = the total length of the input rankings; n = the number of distinct documents in them
- Model
- Word RAM
- Properties
- not comparison baseddeterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gordon V. Cormack, Charles L. A. Clarke, Stefan Büttcher, 2009
Reciprocal rank fusion (RRF) merges several ranked lists of documents into one by giving each document the sum, over the lists, of , where is its rank in the list and is a constant, usually 60. Documents that are not in a list get nothing from it. RRF uses only the ranks, so it can merge the outputs of systems whose scores have different scales, such as BM25 and a dense retriever, with no training and no score normalization. Gordon Cormack, Charles Clarke and Stefan Büttcher proposed it in 2009 as a simple baseline for rank aggregation, and it is now a common default for hybrid search.
In plain words
Several search systems each return a ranked list for the same query. We want one list. Each system gives each of its documents a small vote: the top document gets the largest vote, the second a slightly smaller one, and so on, and the votes get smaller slowly, not fast. A document's final score is the sum of its votes from all systems. A document that two systems both return gets two votes, so it usually beats a document that only one system returns, even near the top. A document that one system puts first still gets a strong vote, so one confident system can lift it. The method never looks at the systems' own scores, which often cannot be compared.
The problem
The input is ranked lists for one query. Each list holds distinct documents, best first, and may be partial, as the top results of a search system are. For a list that holds , is the rank of , from 1. The output is one ranking of the union of the lists. Scores may exist, but the method does not use them. The constant is a parameter.
The algorithm
RRF(L1, ..., Lm, k)- 1
s ← an empty map from documents to scores - 2
for each list L: - 3
for i ← 1 to |L|: - 4
s(L[i]) ← s(L[i]) + 1 / (k + i) ▷ a missing entry counts as 0 - 5
return the documents of s sorted by s, highest first, ties to the smaller id
So . The constant controls how flat the votes are. With the vote of rank 1 is twice the vote of rank 2. With the votes of ranks 1 and 2 are and , which differ by less than 2 percent, and the vote of rank 61 is still half the vote of rank 1. The paper says that "was fixed during a pilot investigation and not altered during subsequent validation", and that "mitigates the impact of high rankings by outlier systems". The value 60 is a tuned constant, not the result of a theorem.
Example
Take the two runs of the toy collection for the query "sorted array search": the BM25 list and a second list . With , the table shows the scores after each pass of line L2, to 6 places.
| document | 1 | 2 | 8 | 4 | 6 | 7 |
|---|---|---|---|---|---|---|
| rank in | 1 | 2 | 3 | 5 | none | 4 |
| score after | 0.016393 | 0.016129 | 0.015873 | 0.015385 | 0 | 0.015625 |
| rank in | 1 | 4 | 3 | 5 | 2 | none |
| score after | 0.032787 | 0.031754 | 0.031746 | 0.030769 | 0.016129 | 0.015625 |
Line L5 returns . The exact scores of documents 2 and 8 are and , which differ by about . Document 4 is fifth in both lists, and its two votes, , beat the single vote of document 6, which ranks second. With and two lists, any document that both lists hold in their top 61 beats any document that only one list holds, wherever that list ranks it. The Borda count on the same lists gives , so the two methods differ exactly on documents 4 and 6.
If each list is first cut to its top 2, the scores are for document 1 and for documents 2 and 6, and the result is : the tie goes to the smaller id.
A second example shows that RRF is not an order by average rank. With two lists, let be at ranks 1 and 41 and at ranks 20 and 20. The total rank of is 40, smaller than the 42 of , but beats .
Correctness
The file proofs/correctness.md proves that lines L1 to L4 compute exactly: the loop invariant is that after lists, each document seen so far holds the sum of its votes from those lists. It also proves that one list comes back unchanged, and that if every list that holds ranks above , then . For full rankings of documents and , the RRF order is the order by total rank, which is the Borda order; the proof writes and bounds the second part. For the usual no such statement holds, as the second example shows.
What RRF does not have is a proof of quality. Cormack, Clarke and Büttcher measured it. On their pilot, with 30 system configurations on TREC topics 351 to 400, the mean average precision went from 0.2072 at to 0.2145 at and 0.2147 at , so the choice of mattered little. On submitted runs for TREC 3, TREC 5, TREC 9 and the TREC 2004 Robust track, RRF beat Condorcet fusion on all four and CombMNZ on three. On LETOR 3, fusing the published learning to rank baselines beat each of them, while CombMNZ scored slightly higher than RRF there. These are measurements on those collections.
Proof: RRF computes its formula, keeps the order of one list, and becomes the total-rank order for large kfull
Let be the input rankings. Each holds distinct documents, best first, and may be partial. For a ranking that holds , is its rank, from 1. Let be the constant. The RRF score is
Lemma 1 (the code computes ). After lines L1 to L4, the map holds exactly the documents that appear in at least one ranking, each with the value , and line L5 returns them by decreasing , with ties broken by the document id.
Proof. Line L1 starts with an empty map. Invariant of the loop of line L2: after the first rankings, the map holds the documents of , each with the sum of over the with . It holds for . Lines L3 and L4 visit each document of once, with its rank, and add to its entry, creating it with value 0 if needed. So the invariant holds for , and for it is the claim. The scores are exact fractions in the code, so the comparison in line L5 has no rounding error.
Lemma 2 (one ranking). With , line L5 returns unchanged.
Proof. is strictly decreasing in , so the scores strictly decrease down the list and no tie occurs.
Lemma 3 (agreement). If every ranking that holds also holds and ranks above , and some ranking holds , then .
Proof. For each ranking that holds , its term for is strictly larger than its term for . The rankings that hold but not add a positive amount to only. If no ranking holds , .
So RRF never puts a document below another document that every relevant ranking places it above: it is unanimous in the sense of the Pareto rule.
Theorem 1 (large ). Let all rankings be full rankings of the same documents, and let be the total rank of . If , then implies . So for such , line L5 orders the documents by increasing total rank, which is the Borda order, with ties in left to the tie rule.
Proof. Write . Then with . Since , each term satisfies , so
Let ; the ranks are integers, so . Then and . Now is equivalent to , that is, to . Since , this holds when . So and .
Remark (small is not the total-rank order). For finite the two orders can differ. With and two rankings, a document at ranks 1 and 41 has total rank 42 and score , while a document at ranks 20 and 20 has total rank 40 and score . So is above , although has the smaller total rank. This is the intended effect: a top rank in one list counts for more than a uniform middle rank.
Remark (depth). Cutting each ranking to its first documents before line L2 removes every term with . The cut scores are therefore the full scores minus a nonnegative amount, and the order can change. On the toy runs of the page, the full fusion is and the fusion at depth 2 is .
The tests in impl/python/test_reciprocal_rank_fusion.py check Lemma 1 against a direct computation of the sum, Theorem 1 with on random full rankings, the two remarks, and the toy runs.
Complexity
Line L4 runs once for each entry of each list, so lines L2 to L4 take expected time with a hash map, where . Line L5 sorts documents in ; if only the top are needed, a heap gives . The extra space is for the map. The lists can be read one at a time, as the paper notes, so they need not all be in memory at once. With exact fractions, as in the code, the arithmetic costs more, but the counts of operations are the same.
Properties
- Rank only. Any change to a system's scores that keeps its order leaves the result the same. This is the main reason to use RRF.
- Unanimity. If every list that holds ranks above , and some list holds , RRF ranks above .
- Presence counts. Each list that holds a document adds a positive amount, so being in more lists helps. With this effect is strong, as the toy example shows.
- Separable. The score is a sum over lists, so lists can be added one at a time, and a weight per list is a simple change.
- Not a Kemeny method. RRF has no approximation guarantee for the Kemeny objective. It is a positional rule, like Borda, with points in place of .
Variants and improvements
- Weighted RRF. Multiply the vote of list by a weight , for example to trust a lexical retriever more than a dense one. The weights are tuned on training queries.
- Other . Small gives more weight to the very top of each list, and large moves RRF toward Borda on the total rank, by the theorem above. Systems tune per collection when they have judged queries.
- Depth cut. Fuse only the top of each list. This bounds the work and matches what search systems return, but it changes the scores, as the depth-2 example shows.
- Score fusion. When the scores are comparable, or can be normalized, CombSUM and CombMNZ use them. In the paper, CombMNZ was close to RRF and sometimes better.
- Pairwise and stationary methods. Condorcet fusion and Markov chain rank aggregation use pairwise majorities in place of positions.
When to use it
Use RRF as the default way to merge ranked lists from different retrievers, for example a lexical and a dense retriever in hybrid search or a retrieval-augmented generation pipeline, when you have no training data or no time to calibrate scores. It is a few lines of code, it is hard to get badly wrong, and it is a strong baseline in the published experiments. If you have judged queries, try weighted RRF or a learned fusion, and compare them to plain RRF on held-out queries.
Pitfalls
- Ranks from 0. Writing with from 0 in line L3 shifts every vote and gives a different method from the paper's. Count ranks from 1, as in line L3, or say that you use .
- Floating point ties. The scores of documents 2 and 8 differ by ; with many lists and long lists, true ties and near ties are common. Sorting floats in line L5 can then order equal scores by rounding noise. Keep exact fractions, or sum the votes in a fixed order and break ties by a stated rule.
- Duplicate entries. If a list holds the same document twice, line L4 counts both votes. Remove duplicates from each list first.
- Treating k = 60 as proved. The constant came from one pilot on TREC data. On other data a different , or weights per list, can be better. Tune it if you can, and report it.
- Lists of very different length. A list of 1,000 documents gives votes of about to its tail, which can add up across many lists and lift documents that every system ranks low. Cut all lists to the same depth.
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
reciprocal_rank_fusion.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reciprocal-rank-fusion/. The authors are listed in prov/552S8S.jsonl.
from fractions import Fraction
from typing import Any, Hashable, Mapping, Sequence
Ranking = Sequence[Hashable]
def to_ranking(scores: Mapping[Hashable, float]) -> list[Any]:
"""Turn a run of scores into a ranking: score descending, then id ascending."""
return sorted(scores, key=lambda d: (-scores[d], d))
def rrf_scores(rankings: Sequence[Ranking], k: int = 60, exact: bool = False) -> dict[Any, Any]:
"""Return the RRF score of each document: the sum over the rankings that hold it of 1/(k + rank).
Ranks start at 1. A ranking that does not hold a document adds 0 for it. With
exact=True the scores are Fractions.
"""
one = Fraction(1) if exact else 1.0
score: dict[Any, Any] = {} # @line L1
for r in rankings: # @line L2
for i, d in enumerate(r, start=1): # @line L3
score[d] = score.get(d, 0 * one) + one / (k + i) # @line L4
return score
def rrf(rankings: Sequence[Ranking], k: int = 60, depth: int | None = None) -> list[Any]:
"""Fuse the rankings, each cut to its first depth documents when depth is given."""
cut = [list(r)[:depth] if depth is not None else list(r) for r in rankings]
score = rrf_scores(cut, k, exact=True)
return sorted(score, key=lambda d: (-score[d], d)) # @line L5
test_reciprocal_rank_fusion.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reciprocal-rank-fusion/. The authors are listed in prov/552S8S.jsonl.
import random
from fractions import Fraction
import irtoy
from reciprocal_rank_fusion import rrf, rrf_scores, to_ranking
def random_profile(rng, n, m, partial):
items = list(range(1, n + 1))
out = []
for _ in range(m):
r = items[:]
rng.shuffle(r)
if partial:
r = r[: rng.randint(0, n)]
out.append(r)
return out
def bm25_q1():
"""BM25 with k1 = 1.2, b = 0.75 and the Lucene idf on q1 of the toy collection."""
q = irtoy.tokenize(irtoy.QUERIES["q1"])
import math
out = {}
for d in irtoy.DOCS:
s = 0.0
for t in q:
f = irtoy.tf(t, d)
if f:
idf = math.log(1 + (irtoy.N - irtoy.df(t) + 0.5) / (irtoy.df(t) + 0.5))
bd = 1 - 0.75 + 0.75 * irtoy.doc_len(d) / irtoy.avgdl()
s += idf * f * 2.2 / (f + 1.2 * bd)
if s:
out[d] = s
return out
def test_scores_match_the_formula():
rng = random.Random(1)
for _ in range(300):
prof = random_profile(rng, rng.randint(1, 8), rng.randint(1, 5), partial=True)
k = rng.choice([0, 1, 5, 60, 1000])
if k == 0 and any(len(r) == 0 for r in prof):
continue
s = rrf_scores(prof, k, exact=True)
union = {d for r in prof for d in r}
assert set(s) == union
for d in union:
want = sum((Fraction(1, k + r.index(d) + 1) for r in prof if d in r), Fraction(0))
assert s[d] == want
got = rrf(prof, k)
assert got == sorted(union, key=lambda d: (-s[d], d))
f = rrf_scores(prof, k)
for d in union:
assert abs(f[d] - float(s[d])) < 1e-12
def test_large_k_gives_the_order_of_the_total_rank():
rng = random.Random(2)
for _ in range(300):
n, m = rng.randint(1, 7), rng.randint(1, 5)
prof = random_profile(rng, n, m, partial=False)
k = m * n * n + 1
s = rrf_scores(prof, k, exact=True)
total = {d: sum(r.index(d) + 1 for r in prof) for d in range(1, n + 1)}
for x in total:
for y in total:
if total[x] < total[y]:
assert s[x] > s[y]
def test_one_top_rank_beats_a_better_total_at_k_60():
# x has ranks 1 and 41 (total 42), y has ranks 20 and 20 (total 40).
a = ["x"] + [f"a{i}" for i in range(18)] + ["y"] + [f"b{i}" for i in range(21)]
b = [f"c{i}" for i in range(19)] + ["y"] + [f"d{i}" for i in range(20)] + ["x"]
assert a.index("x") + 1 == 1 and b.index("x") + 1 == 41
assert a.index("y") + 1 == 20 and b.index("y") + 1 == 20
s = rrf_scores([a, b], 60, exact=True)
assert s["x"] == Fraction(1, 61) + Fraction(1, 101)
assert s["y"] == Fraction(2, 80)
assert s["x"] > s["y"]
def test_toy_runs():
run_a = to_ranking(bm25_q1())
run_b = to_ranking(irtoy.RUN["q1"])
assert run_a == [1, 2, 8, 7, 4]
assert run_b == [1, 6, 8, 2, 4]
s = rrf_scores([run_a, run_b], 60, exact=True)
assert s == {
1: Fraction(2, 61),
2: Fraction(1, 62) + Fraction(1, 64),
8: Fraction(2, 63),
6: Fraction(1, 62),
7: Fraction(1, 64),
4: Fraction(2, 65),
}
assert rrf([run_a, run_b]) == [1, 2, 8, 4, 6, 7]
# Cut to depth 2: only documents 1, 2 and 6 are left, and 2 ties with 6.
assert rrf([run_a, run_b], depth=2) == [1, 2, 6]
def test_edge_cases():
assert rrf([]) == []
assert rrf([[], []]) == []
assert rrf([[3, 1, 2]]) == [3, 1, 2]
History
Cormack, Clarke and Büttcher presented RRF in a two-page poster at SIGIR 2009. They came up with it as an unsupervised baseline while they studied learning to rank, and they reported that it almost always beat the best of the lists it combined. They chose the reciprocal form because highly ranked documents should count more, but the weight of lower ranks should not vanish as it would with an exponential decay. The method builds on earlier rank-based fusion such as Aslam and Montague's Borda-fuse of 2001 and Montague and Aslam's Condorcet fusion of 2002. Its later spread came from hybrid search, where lexical and neural retrievers return scores that cannot be compared, and several search engines now offer it with as the default.
References
- Gordon V. Cormack, Charles L. A. Clarke and Stefan Büttcher, Reciprocal rank fusion outperforms Condorcet and individual rank learning methods, Proceedings of the 32nd Annual International ACM SIGIR Conference (SIGIR 2009), 758-759, Section 1 (the formula, "k = 60 was fixed during a pilot investigation", the pilot results of Table 1, the TREC results of Table 2 and the LETOR 3 results of Table 3) and Section 2 (discussion)
- Javed A. Aslam and Mark H. Montague, Models for metasearch, Proceedings of the 24th Annual International ACM SIGIR Conference (SIGIR 2001), 276-284, Borda-fuse, the rank-based fusion with linear points that RRF replaces by reciprocal points
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 552S8S Edit this page History Report an error Markdown