Skip to content

Language models, retrieval, prompting, and language adaptation · Long-context and retrieval-augmented language · LNG054 · Model

Dense Passage Retrieval (DPR)

Uses separate neural encoders for questions and passages to retrieve relevant evidence through vector similarity. Passage vectors can be indexed ahead of time, making it practical to search large document collections.

Runs in CodeSplash Component demo, not a trained model CodeSplash's own run

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Component demo, not a trained model
Who ran it
CodeSplash's own run
CodeSplash's run
The reference's example ran in Python and R here, and they agree.
The reference's record
Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Uses separate neural encoders for questions and passages to retrieve relevant evidence through vector similarity. Passage vectors can be indexed ahead of time, making it practical to search large document collections.

Question / objective

Can separate query and passage encoders retrieve answer-bearing text efficiently?

Architecture / computational structure

Two encoders output fixed-size vectors scored by inner product; passage embeddings populate an external index. Learned encoder weights are parameters; embedding dimension, negative selection, index parameters, and top-k are hyperparameters.

Assumptions

Unlabeled passages may actually be relevant, producing false negatives.

Formula / computational definition

s(q,p)=EQ(q)⊤EP(p),L=−log⁡es(q,p+)es(q,p+)+∑jes(q,pj−).s(q,p)=E_Q(q)^\top E_P(p),\qquad \mathcal L=-\log\frac{e^{s(q,p^+)}}{e^{s(q,p^+)}+\sum_je^{s(q,p_j^-)}}.

s(q,p)=E_Q(q)^T E_P(p); minimize -log exp(s(q,p+))/[exp(s(q,p+))+sum_j exp(s(q,p_j-))]. In-batch and mined negatives teach the query encoder to distinguish relevant passages.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Encoder initialization, embedding size, negatives, hard-negative mining, passage length, index approximation, and retrieval depth.

Fitting, fine-tuning, and adaptation

Fit relevance pairs with contrastive loss and hard negatives. Freeze one encoder for controlled adaptation, or update both and rebuild the index; supported LoRA is possible only with correct encoder targets. Validate false negatives, domain transfer, recall, and downstream reader quality.

How to use and calibrate

Use recall-at-k, ranking metrics, downstream answer accuracy, latency, index memory, and domain-transfer splits. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.

Example application

Retrieve likely answer passages before an expensive reading or generation stage.

Interpretation / pitfalls

Watch out

Training-domain relevance may not transfer to new domains; indexing with outdated passage encoders breaks score consistency. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.

Python and R code examples

Full implementation route: Transformers exposes DPR encoders; vector indexing uses a separately documented search library. R can bridge encoders through reticulate and calculate dot products/ranking metrics natively. The native example explicitly computes the contrastive retrieval loss for one positive and two negatives.

Example scope: DPR contrastive retrieval loss for one query, one positive, and two negatives.

Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.

Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Component demo, not a trained model — DPR contrastive retrieval loss for one query, one positive, and two negatives.

Shared setup for this chapter
import math

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

def dot(a, b):
    return sum(x*y for x, y in zip(a, b))

def matvec(matrix, vector):
    return [dot(row, vector) for row in matrix]

def meanvec(rows):
    return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]

def sigmoid(x):
    return 1/(1+math.exp(-x))

def nll(probabilities):
    return -sum(math.log(p) for p in probabilities)
q = [0.8,0.6]; passages = [[0.7,0.7],[1,0],[-0.5,0.1]]
scores = [dot(q,p) for p in passages]
print(scores,-math.log(softmax(scores)[0]))
R

Component demo, not a trained model — DPR contrastive retrieval loss for one query, one positive, and two negatives.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
q <- c(0.8,0.6); passages <- rbind(c(0.7,0.7),c(1,0),c(-0.5,0.1))
scores <- drop(passages %*% q)
print(list(scores=scores,loss=-log(softmax(scores)[1])))

Sources

From the CodeSplash reference, entry LNG054.