Algorithm Search⌘K

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.

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
Properties
not comparison baseddeterministiciterative
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 1/(k+r)1/(k + r), where rr is its rank in the list and kk 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 mm ranked lists L1,…,LmL_1, \ldots, L_m for one query. Each list holds distinct documents, best first, and may be partial, as the top cc results of a search system are. For a list LL that holds dd, L(d)L(d) is the rank of dd, 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 k>0k > 0 is a parameter.

The algorithm

  1. RRF(L1, ..., Lm, k)
  2. 1s ← an empty map from documents to scores
  3. 2for each list L:
  4. 3for i ← 1 to |L|:
  5. 4s(L[i]) ← s(L[i]) + 1 / (k + i) ▷ a missing entry counts as 0
  6. 5return the documents of s sorted by s, highest first, ties to the smaller id

So s(d)=∑l:d∈Ll1/(k+Ll(d))s(d) = \sum_{l : d \in L_l} 1/(k + L_l(d)). The constant kk controls how flat the votes are. With k=0k = 0 the vote of rank 1 is twice the vote of rank 2. With k=60k = 60 the votes of ranks 1 and 2 are 1/611/61 and 1/621/62, 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 k=60k = 60 "was fixed during a pilot investigation and not altered during subsequent validation", and that kk "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 A=1,2,8,7,4A = 1, 2, 8, 7, 4 and a second list B=1,6,8,2,4B = 1, 6, 8, 2, 4. With k=60k = 60, the table shows the scores after each pass of line L2, to 6 places.

document 1 2 8 4 6 7
rank in AA 1 2 3 5 none 4
score after AA 0.016393 0.016129 0.015873 0.015385 0 0.015625
rank in BB 1 4 3 5 2 none
score after BB 0.032787 0.031754 0.031746 0.030769 0.016129 0.015625

Line L5 returns 1,2,8,4,6,71, 2, 8, 4, 6, 7. The exact scores of documents 2 and 8 are 1/62+1/64=63/19841/62 + 1/64 = 63/1984 and 2/632/63, which differ by about 8⋅10−68 \cdot 10^{-6}. Document 4 is fifth in both lists, and its two votes, 2/652/65, beat the single vote of document 6, which BB ranks second. With k=60k = 60 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 1,2,8,6,4,71, 2, 8, 6, 4, 7, so the two methods differ exactly on documents 4 and 6.

If each list is first cut to its top 2, the scores are 2/612/61 for document 1 and 1/621/62 for documents 2 and 6, and the result is 1,2,61, 2, 6: the tie goes to the smaller id.

A second example shows that RRF is not an order by average rank. With two lists, let xx be at ranks 1 and 41 and yy at ranks 20 and 20. The total rank of yy is 40, smaller than the 42 of xx, but s(x)=1/61+1/101≈0.026294s(x) = 1/61 + 1/101 \approx 0.026294 beats s(y)=2/80=0.025s(y) = 2/80 = 0.025.

Correctness

The file proofs/correctness.md proves that lines L1 to L4 compute ss exactly: the loop invariant is that after jj lists, each document seen so far holds the sum of its votes from those jj lists. It also proves that one list comes back unchanged, and that if every list that holds yy ranks xx above yy, then s(x)>s(y)s(x) > s(y). For full rankings of nn documents and k>mn2k > m n^2, the RRF order is the order by total rank, which is the Borda order; the proof writes 1/(k+r)=(1/k)(1−r/(k+r))1/(k + r) = (1/k)(1 - r/(k + r)) and bounds the second part. For the usual k=60k = 60 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 k=0k = 0 to 0.2145 at k=60k = 60 and 0.2147 at k=80k = 80, so the choice of kk 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 L1,…,LmL_1, \ldots, L_m be the input rankings. Each holds distinct documents, best first, and may be partial. For a ranking LL that holds dd, L(d)L(d) is its rank, from 1. Let k>0k > 0 be the constant. The RRF score is

s(d)=∑l : d∈Ll1k+Ll(d).s(d) = \sum_{l \,:\, d \in L_l} \frac{1}{k + L_l(d)}.

Lemma 1 (the code computes ss). After lines L1 to L4, the map holds exactly the documents that appear in at least one ranking, each with the value s(d)s(d), and line L5 returns them by decreasing ss, 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 jj rankings, the map holds the documents of L1,…,LjL_1, \ldots, L_j, each with the sum of 1/(k+Ll(d))1/(k + L_l(d)) over the l≤jl \le j with d∈Lld \in L_l. It holds for j=0j = 0. Lines L3 and L4 visit each document of Lj+1L_{j+1} once, with its rank, and add 1/(k+Lj+1(d))1/(k + L_{j+1}(d)) to its entry, creating it with value 0 if needed. So the invariant holds for j+1j + 1, and for j=mj = m it is the claim. The scores are exact fractions in the code, so the comparison in line L5 has no rounding error. □\square

Lemma 2 (one ranking). With m=1m = 1, line L5 returns L1L_1 unchanged.

Proof. 1/(k+i)1/(k + i) is strictly decreasing in ii, so the scores strictly decrease down the list and no tie occurs. □\square

Lemma 3 (agreement). If every ranking that holds yy also holds xx and ranks xx above yy, and some ranking holds xx, then s(x)>s(y)s(x) > s(y).

Proof. For each ranking that holds yy, its term for xx is strictly larger than its term for yy. The rankings that hold xx but not yy add a positive amount to s(x)s(x) only. If no ranking holds yy, s(y)=0<s(x)s(y) = 0 < s(x). □\square

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 kk). Let all mm rankings be full rankings of the same nn documents, and let R(d)=∑lLl(d)R(d) = \sum_l L_l(d) be the total rank of dd. If k>mn2k > m n^2, then R(x)<R(y)R(x) < R(y) implies s(x)>s(y)s(x) > s(y). So for such kk, line L5 orders the documents by increasing total rank, which is the Borda order, with ties in RR left to the tie rule.

Proof. Write 1k+r=1k(1−rk+r)\frac{1}{k + r} = \frac{1}{k} \left( 1 - \frac{r}{k + r} \right). Then s(d)=1k(m−g(d))s(d) = \frac{1}{k} (m - g(d)) with g(d)=∑lLl(d)k+Ll(d)g(d) = \sum_l \frac{L_l(d)}{k + L_l(d)}. Since 1≤Ll(d)≤n1 \le L_l(d) \le n, each term satisfies Ll(d)k+n≤Ll(d)k+Ll(d)≤Ll(d)k\frac{L_l(d)}{k + n} \le \frac{L_l(d)}{k + L_l(d)} \le \frac{L_l(d)}{k}, so

R(d)k+n≤g(d)≤R(d)k.\frac{R(d)}{k + n} \le g(d) \le \frac{R(d)}{k}.

Let R(x)<R(y)R(x) < R(y); the ranks are integers, so R(y)≥R(x)+1R(y) \ge R(x) + 1. Then g(x)≤R(x)/kg(x) \le R(x)/k and g(y)≥(R(x)+1)/(k+n)g(y) \ge (R(x) + 1)/(k + n). Now R(x)/k<(R(x)+1)/(k+n)R(x)/k < (R(x) + 1)/(k + n) is equivalent to R(x)(k+n)<(R(x)+1)kR(x)(k + n) < (R(x) + 1) k, that is, to nR(x)<kn R(x) < k. Since R(x)≤mnR(x) \le m n, this holds when k>mn2k > m n^2. So g(x)<g(y)g(x) < g(y) and s(x)>s(y)s(x) > s(y). □\square

Remark (small kk is not the total-rank order). For finite kk the two orders can differ. With k=60k = 60 and two rankings, a document xx at ranks 1 and 41 has total rank 42 and score 1/61+1/101≈0.0262941/61 + 1/101 \approx 0.026294, while a document yy at ranks 20 and 20 has total rank 40 and score 2/80=0.0252/80 = 0.025. So xx is above yy, although yy 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 cc documents before line L2 removes every term with Ll(d)>cL_l(d) > c. 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 1,2,8,4,6,71, 2, 8, 4, 6, 7 and the fusion at depth 2 is 1,2,61, 2, 6.

The tests in impl/python/test_reciprocal_rank_fusion.py check Lemma 1 against a direct computation of the sum, Theorem 1 with k=mn2+1k = m n^2 + 1 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 Θ(N)\Theta(N) expected time with a hash map, where N=∑l∣Ll∣N = \sum_l |L_l|. Line L5 sorts nn documents in O(nlog⁡n)O(n \log n); if only the top tt are needed, a heap gives O(nlog⁡t)O(n \log t). The extra space is O(n)O(n) 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 yy ranks xx above yy, and some list holds xx, RRF ranks xx above yy.
  • Presence counts. Each list that holds a document adds a positive amount, so being in more lists helps. With k=60k = 60 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 1/(k+i)1/(k + i) in place of n−i+1n - i + 1.

Variants and improvements

  • Weighted RRF. Multiply the vote of list ll by a weight wlw_l, for example to trust a lexical retriever more than a dense one. The weights are tuned on training queries.
  • Other kk. Small kk gives more weight to the very top of each list, and large kk moves RRF toward Borda on the total rank, by the theorem above. Systems tune kk per collection when they have judged queries.
  • Depth cut. Fuse only the top cc 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 1/(k+i)1/(k + i) with ii 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 k+1k + 1.
  • Floating point ties. The scores of documents 2 and 8 differ by 8⋅10−68 \cdot 10^{-6}; 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 kk, 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 1/10601/1060 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.

irtoy.pyI0RawGitHub
# 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 k=60k = 60 as the default.

References

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example