Algorithm Search⌘K

Algorithmresearch

Dense passage retrieval

Also called DPR.

Trains a question encoder and a passage encoder with in-batch negatives so that relevant passages are nearest neighbors by inner product.

Time
O(B m k) per_batchO(N k + N log N) per_query
Space
O(B m + N k) extra
Where
B = the number of questions in a batch; N = the number of passages in the collection; k = the vector dimension; m = the number of passages in a batch
Properties
deterministicexactofflineiterative
Origin
Vladimir Karpukhin, Barlas Oguz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen tau Yih, 2020

Dense passage retrieval (DPR) trains the two encoders of a dual encoder for open-domain question answering, so that the passage that answers a question has the largest inner product with it among millions of passages. The training loss is a softmax cross-entropy over one positive passage and many negatives, and its main trick is to reuse the positive passages of the other questions in a batch as negatives, which costs no extra encoding. The dual-encoder page describes the scoring model and its limits; this page gives the training objective, its gradient, the in-batch construction, and the exact top-kk step that the index approximates. Search over the vectors is the topic of maximum inner product search and HNSW. The two BERT encoders and the quality of the retrieval they learn are outside the code and the proofs here.

In plain words

We want a search system that turns every question and every passage into a list of numbers, so that a good answer passage lands close to its question. We train it on questions with known answer passages. A training batch holds many questions and their answer passages. For each question, its own passage is the right one, and the passages of all the other questions serve as wrong ones, for free. We also add one hard wrong passage per question, a passage that shares many words with the question but does not answer it. Training pushes each question toward its right passage and away from the wrong ones. Later, search is just finding the closest stored passages.

The problem

A batch has BB questions with vectors q1,…,qBq_1, \ldots, q_B and m≥Bm \ge B passages with vectors c1,…,cm∈Rkc_1, \ldots, c_m \in \mathbb R^k, produced by the question encoder EQE_Q and the passage encoder EPE_P. Passage cic_i is the positive of question ii for i≤Bi \le B; the other passages are negatives for it: the positives of the other questions and any extra hard negatives, such as the top BM25 passage that does not contain the answer. With Sij=qi⋅cjS_{ij} = q_i \cdot c_j, the loss is

L=1B∑i=1B−log⁡eSii∑j=1meSij.L = \frac{1}{B} \sum_{i=1}^{B} -\log \frac{e^{S_{ii}}}{\sum_{j=1}^{m} e^{S_{ij}}}.

This is Equation (2) of Karpukhin et al. (2020), averaged over the batch. After training, a question qq is answered by the KK passages of the collection with the largest q⋅cq \cdot c.

The algorithm

  1. DPR-BATCH(Q, C, B) -- Q: B × k question vectors, C: m × k passage vectors
  2. 1S ← Q Cᵀ
  3. 2p_i ← softmax(S_i) for each row i
  4. 3L ← (1/B) Σ_i -log p_ii
  5. 4G ← (P - [I | 0]) / B -- P has the rows p_i, [I | 0] marks the positives
  6. 5∇_Q ← G C, ∇_C ← Gᵀ Q
  7. 6return ∇_Q and ∇_C, to be back-propagated into E_Q and E_P
  8. 7SEARCH(q, K): return the K passages with the largest q · c, ties to the smaller id

Lines L1 to L6 are the code. The back-propagation into the encoders after line L6, and the update of their weights, are outside it. The paper trains with batch size 128 and one BM25 negative per question, so each question sees 255 negatives. Line L7 is exact search; the paper builds a FAISS HNSW index over the passage vectors to answer faster.

Example

Take B=2B = 2 questions q1=(1,0)q_1 = (1, 0) and q2=(0,1)q_2 = (0, 1), their positives c1=(2,0)c_1 = (2, 0) and c2=(1,1)c_2 = (1, 1), and one hard negative each: c3=(0,−1)c_3 = (0, -1) for q1q_1 and c4=(1,2)c_4 = (1, 2) for q2q_2. All four passages are shared negatives for both questions.

c1c_1 c2c_2 c3c_3 c4c_4
S1jS_{1j} 2 1 0 1
p1jp_{1j} 0.5344 0.1966 0.0723 0.1966
S2jS_{2j} 0 1 -1 2
p2jp_{2j} 0.0871 0.2369 0.0321 0.6439

The loss is 12(−ln⁡0.5344−ln⁡0.2369)=1.0334\frac{1}{2}(-\ln 0.5344 - \ln 0.2369) = 1.0334. Without the hard negatives, with only c1c_1 and c2c_2, it is 0.31330.3133: the hard negative c4c_4 outscores the positive of q2q_2 and dominates the loss. The gradients are

∇q1=(−0.2689,0.2588),∇q2=(0.0275,0.2463),\nabla_{q_1} = (-0.2689, 0.2588), \quad \nabla_{q_2} = (0.0275, 0.2463),
∇c1=(−0.2328,0.0436),∇c2=(0.0983,−0.3816),∇c3=(0.0362,0.0160),∇c4=(0.0983,0.3220).\nabla_{c_1} = (-0.2328, 0.0436), \quad \nabla_{c_2} = (0.0983, -0.3816), \quad \nabla_{c_3} = (0.0362, 0.0160), \quad \nabla_{c_4} = (0.0983, 0.3220).

A step against them moves q2q_2 and c2c_2 toward each other and c4c_4 away from q2q_2. At search time, q2q_2 would retrieve c4c_4 first with these vectors, which is what the loss penalizes.

Correctness

The proof in proofs/correctness.md shows:

  • Gradient. ∂L/∂qi=1B∑j(pij−[j=i])cj\partial L / \partial q_i = \frac{1}{B} \sum_j (p_{ij} - [j = i]) c_j and ∂L/∂cj=1B∑i(pij−[j=i])qi\partial L / \partial c_j = \frac{1}{B} \sum_i (p_{ij} - [j = i]) q_i, which is line L5. The tests check every coordinate against central finite differences on random batches.
  • Bounds. L>0L > 0, each row term is log⁡m\log m when its scores are equal, and it tends to 0 only when the positive's margin over every negative grows without bound. With m=Bm = B, each question has B−1B - 1 negatives; with one hard negative each, 2B−12B - 1.
  • Exact search. Line L7 returns the KK passages of largest inner product, ties to the smaller id. Approximate indexes are compared against this.

Nothing here shows that training makes the answer passage of a new question its nearest neighbor; that is measured. Karpukhin et al. (2020), Table 2, report a top-20 retrieval accuracy of 78.4 for DPR against 59.1 for BM25 on the Natural Questions test set, as a measurement.

Proof: The gradient of the in-batch negative loss, its bounds, and exact inner-product top-kfull

A batch has BB question vectors q1,…,qBq_1, \ldots, q_B and m≥Bm \ge B passage vectors c1,…,cmc_1, \ldots, c_m in Rd\mathbb R^d. For i≤Bi \le B, cic_i is the positive passage of question ii, and every other ckc_k is a negative for it: the positives of the other questions, and any extra negatives such as one BM25 hard negative per question. The vectors are the outputs of the two encoders, which this proof treats as given. Let Sik=qi⋅ckS_{ik} = q_i \cdot c_k and

pik=eSik∑l=1meSil,L=1B∑i=1B−log⁡pii.p_{ik} = \frac{e^{S_{ik}}}{\sum_{l=1}^{m} e^{S_{il}}}, \qquad L = \frac{1}{B} \sum_{i=1}^{B} -\log p_{ii}.

This is the negative log-likelihood of Karpukhin et al. (2020), Equation (2), with the in-batch negatives of their Section 3.2.

Lemma 1 (gradient).

∂L∂qi=1B∑k=1m(pik−[k=i]) ck,∂L∂ck=1B∑i=1B(pik−[k=i]) qi.\frac{\partial L}{\partial q_i} = \frac{1}{B} \sum_{k=1}^{m} (p_{ik} - [k = i])\, c_k, \qquad \frac{\partial L}{\partial c_k} = \frac{1}{B} \sum_{i=1}^{B} (p_{ik} - [k = i])\, q_i.

Proof. −log⁡pii=−Sii+log⁡∑leSil-\log p_{ii} = -S_{ii} + \log \sum_l e^{S_{il}}, so ∂(−log⁡pii)/∂Sik=pik−[k=i]\partial(-\log p_{ii}) / \partial S_{ik} = p_{ik} - [k = i], and SikS_{ik} does not enter any other row. Since ∂Sik/∂qi=ck\partial S_{ik} / \partial q_i = c_k and ∂Sik/∂ck=qi\partial S_{ik} / \partial c_k = q_i, the chain rule gives both sums. □\square

Lines L1 to L3 of the code compute SS, the rows of log-probabilities and LL, and lines L4 and L5 accumulate the coefficient (pik−[k=i])/B(p_{ik} - [k = i])/B times the other vector. One batch costs O(Bmd)O(B m d) time for SS and the same for the gradients. With a matrix library the two gradients are GCG C and G⊤QG^\top Q, where GG is the matrix of the coefficients.

A passage ckc_k that is not a positive (k>Bk > B) gets ∂L/∂ck=1B∑ipikqi\partial L / \partial c_k = \frac{1}{B} \sum_i p_{ik} q_i, a pull away from every question in proportion to how much probability it takes. The positive cic_i gets the push −1B(1−pii)qi-\frac{1}{B}(1 - p_{ii}) q_i toward its question, plus the pulls from the other questions that score it.

Lemma 2 (bounds). L>0L > 0. If all scores of row ii are equal, its term is log⁡m\log m. The term of row ii tends to 0 exactly when Sii−Sik→∞S_{ii} - S_{ik} \to \infty for every k≠ik \ne i.

Proof. pii<1p_{ii} < 1 because every eSik>0e^{S_{ik}} > 0, so −log⁡pii>0-\log p_{ii} > 0. Equal scores give pii=1/mp_{ii} = 1/m. The term is log⁡(1+∑k≠ieSik−Sii)\log(1 + \sum_{k \ne i} e^{S_{ik} - S_{ii}}), which tends to 0 exactly when each exponent tends to −∞-\infty. □\square

So each question of a batch with BB questions and no extra negatives is trained against B−1B - 1 negatives at no extra encoding cost, since the other positives are already encoded. With one hard negative per question, m=2Bm = 2B and each question has 2B−12B - 1 negatives.

Lemma 3 (exact top-k). Line L7 returns the kk passages with the largest q⋅cq \cdot c, and among equal scores the smaller ids, in that order.

Proof. Sorting by the key (−q⋅cp,p)(-q \cdot c_p, p) orders the passages by score, highest first, and then by id. The keys are distinct, because the ids are, so the first kk entries are the kk smallest keys. □\square

Exact search is the reference that approximate indexes such as HNSW approximate. It costs O(Nd)O(N d) per query for NN passages, plus the sort.

What is outside the proof. Nothing here says that training makes relevant passages nearest neighbors on new questions. The encoders, their training data and their retrieval accuracy are outside the code, and the accuracy figures of the paper are measurements.

The tests in impl/python/test_dense_passage_retrieval.py check Lemma 1 by central finite differences in every coordinate of qq and cc on random batches, the loss against a direct sum, Lemma 2, that a small step against the gradient lowers the loss, Lemma 3 with ties against a brute force, and the worked example of the page.

Complexity

One batch costs O(Bmk)O(B m k) for SS and the same for the two gradients, plus the encoder passes for B+mB + m inputs, which dominate in practice. The in-batch negatives add B−1B - 1 negatives per question for no extra encoder pass, since their vectors are already computed. The extra space is O(Bm)O(B m) for the scores. Search by exact scan costs O(Nk)O(N k) per query, plus O(Nlog⁡K)O(N \log K) to keep the top KK with a heap, and the index stores NkN k numbers; for 21 million passages of dimension 768 that is about 16 billion numbers, which is why the index uses compression or graph search.

Properties

  • Shift invariant per row. Adding a constant to all scores of one question does not change the loss.
  • Hard negatives matter. In the example, one hard negative raises the loss from 0.3133 to 1.0334, because it is the strongest competitor of the positive. The paper's main training setting adds one BM25 negative per question to the in-batch negatives.
  • Batch size is the number of negatives. Larger batches give more negatives per question at the same encoding cost per question, which ties the quality of training to the memory of the hardware.
  • Same similarity at training and search. The loss uses the inner product, so the search must use the inner product, not the cosine.
  • Passages are fixed once encoded. A change of EPE_P requires re-encoding the whole collection.

Variants and improvements

  • Mined hard negatives. Use negatives retrieved by the current model, refreshed during training.
  • Distillation from a reranker. Train the dual encoder to match the scores of a cross-encoder instead of hard labels.
  • Multi-vector scoring. ColBERT keeps one vector per token and scores by late interaction.
  • Joint training with a reader or generator. Retrieval-augmented generation fine-tunes the question encoder of DPR through the generator's likelihood, with the passage encoder frozen.
  • Hybrid with BM25. Combine dense and lexical scores, for example by a linear combination or reciprocal rank fusion.

When to use it

Use DPR as the first stage when queries are questions in natural language and the answers are in passages that may not share the question's words. It needs training pairs of questions and positive passages, and a GPU to encode the collection. When the queries are keyword-like or the domain has no training data, BM25 is a strong baseline that the paper itself uses for hard negatives. For the final order of a short list, a cross-encoder is more accurate, at a cost per pair.

Pitfalls

  • Positives counted as negatives. If two questions in a batch share a positive passage, line L4 treats it as a negative for one of them. Remove such duplicates when building batches.
  • Softmax over the wrong axis. Line L2 normalizes each question's row over the passages. Normalizing over questions gives a different loss and, in line L5, different gradients.
  • Overflow. Line L2 must subtract the row maximum before exponentiating.
  • Approximate search mistaken for the model. Recall measured with an approximate index in place of line L7 mixes the errors of the index with those of the encoders. Report the exact-search result when comparing models.
  • False hard negatives. A BM25 passage that does not contain the answer string may still answer the question. Such negatives push the model away from correct passages.

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.

dense_passage_retrieval.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dense-passage-retrieval/. The authors are listed in prov/GDMYGR.jsonl.

"""The in-batch negative loss of DPR and exact inner-product retrieval.

The encoders are outside this file. The inputs are the vectors that they
would produce: q_1..q_B for the questions of a batch, and c_1..c_m for the
passages of the batch, where c_i (i < B) is the positive passage of
question i and the other rows are negatives (for example one BM25 hard
negative per question). With S = Q C^T,

    L = (1 / B) sum_i -log( exp(S_ii) / sum_k exp(S_ik) ).

With p_ik the softmax of row i of S,

    dL/dq_i = (1 / B) sum_k (p_ik - [k = i]) c_k,
    dL/dc_k = (1 / B) sum_i (p_ik - [k = i]) q_i.

Retrieval returns the k passages of largest q . c, with ties broken by the
smaller passage id.
"""

import math


def dot(a, b):
    return sum(p * q for p, q in zip(a, b))


def similarity(qs, cs):
    return [[dot(q, c) for c in cs] for q in qs]                       # @line L1


def softmax(v):
    m = max(v)
    e = [math.exp(x - m) for x in v]
    z = sum(e)
    return [x / z for x in e]


def log_softmax(v):
    m = max(v)
    lz = m + math.log(sum(math.exp(x - m) for x in v))
    return [x - lz for x in v]


def in_batch_loss(qs, cs):
    """The mean negative log-likelihood of the positive passage c_i for question i."""
    s = similarity(qs, cs)
    rows = [log_softmax(row) for row in s]                             # @line L2
    return -sum(row[i] for i, row in enumerate(rows)) / len(qs)        # @line L3


def in_batch_gradients(qs, cs):
    """(dL/dq, dL/dc) as lists of vectors."""
    b = len(qs)
    s = similarity(qs, cs)
    gq = [[0.0] * len(qs[0]) for _ in qs]
    gc = [[0.0] * len(cs[0]) for _ in cs]
    for i, row in enumerate(s):
        p = softmax(row)
        for k, pk in enumerate(p):
            coef = (pk - (1.0 if k == i else 0.0)) / b                  # @line L4
            for c in range(len(qs[0])):
                gq[i][c] += coef * cs[k][c]                             # @line L5
                gc[k][c] += coef * qs[i][c]
    return gq, gc                                                      # @line L6


def top_k(q, passages, k):
    """The ids of the k passages with the largest inner product, ties by id."""
    order = sorted(range(len(passages)), key=lambda p: (-dot(q, passages[p]), p))
    return order[:k]                                                   # @line L7
test_dense_passage_retrieval.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dense-passage-retrieval/. The authors are listed in prov/GDMYGR.jsonl.

import math
import random

from dense_passage_retrieval import (
    dot,
    in_batch_gradients,
    in_batch_loss,
    similarity,
    softmax,
    top_k,
)

Q = [[1.0, 0.0], [0.0, 1.0]]
C = [[2.0, 0.0], [1.0, 1.0], [0.0, -1.0], [1.0, 2.0]]


def test_page_example():
    assert similarity(Q, C) == [[2.0, 1.0, 0.0, 1.0], [0.0, 1.0, -1.0, 2.0]]
    assert [round(v, 4) for v in softmax([2.0, 1.0, 0.0, 1.0])] == [0.5344, 0.1966, 0.0723, 0.1966]
    assert [round(v, 4) for v in softmax([0.0, 1.0, -1.0, 2.0])] == [0.0871, 0.2369, 0.0321, 0.6439]
    assert round(in_batch_loss(Q, C), 4) == 1.0334
    # Without the two hard negatives, only the other positive is a negative.
    assert round(in_batch_loss(Q, C[:2]), 4) == 0.3133
    gq, gc = in_batch_gradients(Q, C)
    assert [round(v, 4) for v in gq[0]] == [-0.2689, 0.2588]
    assert [round(v, 4) for v in gc[3]] == [0.0983, 0.3220]


def test_gradients_by_finite_differences():
    rng = random.Random(1)
    h = 1e-6
    for _ in range(20):
        b = rng.randint(1, 4)
        m = b + rng.randint(0, b)
        d = rng.randint(1, 4)
        qs = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(b)]
        cs = [[rng.uniform(-1, 1) for _ in range(d)] for _ in range(m)]
        gq, gc = in_batch_gradients(qs, cs)
        for mat, grad in ((qs, gq), (cs, gc)):
            for r in range(len(mat)):
                for c in range(d):
                    old = mat[r][c]
                    mat[r][c] = old + h
                    up = in_batch_loss(qs, cs)
                    mat[r][c] = old - h
                    down = in_batch_loss(qs, cs)
                    mat[r][c] = old
                    assert abs((up - down) / (2 * h) - grad[r][c]) < 1e-6


def test_loss_with_one_passage_per_question_is_cross_entropy_of_the_rows():
    rng = random.Random(2)
    qs = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
    cs = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
    s = similarity(qs, cs)
    direct = 0.0
    for i in range(3):
        direct += -s[i][i] + math.log(sum(math.exp(v) for v in s[i]))
    assert abs(in_batch_loss(qs, cs) - direct / 3) < 1e-12


def test_small_step_lowers_loss():
    rng = random.Random(3)
    qs = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(4)]
    cs = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(8)]
    before = in_batch_loss(qs, cs)
    gq, gc = in_batch_gradients(qs, cs)
    eta = 1e-3
    qs2 = [[a - eta * g for a, g in zip(q, gr)] for q, gr in zip(qs, gq)]
    cs2 = [[a - eta * g for a, g in zip(c, gr)] for c, gr in zip(cs, gc)]
    assert in_batch_loss(qs2, cs2) < before


def test_loss_bounds():
    # The loss is positive and is at most log m when every score is equal.
    qs = [[0.0, 0.0], [0.0, 0.0]]
    cs = [[1.0, 1.0], [2.0, 0.0], [0.5, 0.5]]
    assert abs(in_batch_loss(qs, cs) - math.log(3)) < 1e-12
    assert in_batch_loss(Q, C) > 0


def test_top_k_exact_with_ties():
    passages = [[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.5, 0.5], [2.0, -1.0]]
    assert top_k([1.0, 0.0], passages, 3) == [4, 0, 2]
    rng = random.Random(4)
    for _ in range(50):
        ps = [[rng.randint(-2, 2) for _ in range(3)] for _ in range(10)]
        q = [rng.randint(-2, 2) for _ in range(3)]
        got = top_k(q, ps, 4)
        brute = sorted(range(10), key=lambda p: (-dot(q, ps[p]), p))[:4]
        assert got == brute
        kth = dot(q, ps[got[-1]])
        assert all(dot(q, ps[p]) <= kth for p in range(10) if p not in got)

History

Neural dual encoders for retrieval go back at least to DSSM by Huang et al. (2013), trained on click data. Karpukhin et al. (2020) showed that two BERT encoders, fine-tuned only on question and passage pairs with in-batch negatives and one BM25 negative, beat BM25 on several open-domain question answering benchmarks in their measurements. DPR became the standard dense retriever of the following years and the retriever of the original retrieval-augmented generation model.

References

  1. Vladimir Karpukhin, Barlas Oguz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen and Wen-tau Yih, Dense passage retrieval for open-domain question answering, Proceedings of EMNLP 2020, pp. 6769-6781; Section 3.1 and Equation (1) (the similarity of the [CLS] vectors of two BERT encoders, dimension 768), Section 3.2 and Equation (2) (the negative log-likelihood of the positive passage, with in-batch negatives and BM25 hard negatives), Section 5.4 (indexing with FAISS HNSW), Table 2 (retrieval accuracy)

Where this leads

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.per_batch
  • a full proof of time.per_query
  • 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