Retrieval-Augmented Generation (RAG), from VectorDB to Reranker
Retrieval-augmented generation (RAG) gives a large language model (LLM) knowledge that is not in its weights, such as private or recent documents. The documents are split into chunks, and the chunks most relevant to a query are added to the prompt. This post builds the retrieval with short PyTorch and NumPy code. The following picture shows the pipeline:
The RAG pipeline with a retriever and a reranker. Ahead of time, the chunks of the documents are embedded and stored in a vector database. At query time, the query is embedded with the same model, and the database returns its top-\(n\) chunks. The reranker reads the query with each of them, and only its top-\(k\) chunks \(c_1\) to \(c_k\) reach the prompt of the LLM, between the system prompt (sys) and the query.
The retriever is fast but coarse: it narrows millions of chunks down to \(n\) candidates. The reranker is slow but accurate: it picks the \(k\) chunks that the LLM reads, with \(k\) much smaller than \(n\).
Embeddings and Encoder
An embedding is a vector of hundreds to thousands of numbers that a neural network computes from an input, such as a chunk of text or an image. The network is trained so that related inputs get close embeddings: a question and the passage that answers it are neighbors, and the search for relevant chunks becomes a search for the nearest vectors.
Similarity Measures
A vector database ranks the vectors by one of three measures:
- the dot product \(a^T b\), which grows with the norms of the vectors, e.g. in matrix factorization, which predicts a rating as the dot product of a movie vector and a user vector;
- the cosine similarity \(\cos(a, b) = a^T b / (\Vert a \Vert \, \Vert b \Vert)\), which only sees the angle between the vectors, and is the measure of most text embedding models;
- the Euclidean distance \(\Vert a - b \Vert\), the distance of k-means, and thus of the indexes below.
On unit vectors, the three measures give the same neighbors, as the dot product is then the cosine similarity, and \(\Vert a - b \Vert^2 = 2 - 2 \cos(a, b)\). So the embeddings are normalized to unit length when they are stored, and a search can use any of the three measures. Without the normalization, the measures disagree, and the right one is the one that the model was trained with.
Bi-Encoders and Cross-Encoders
The embedding model of the retriever is a bi-encoder: it encodes the query and each chunk on their own. Thus, the chunks are embedded once, ahead of time, and a query costs one pass of the encoder, followed by a cheap similarity search over the stored embeddings. A cross-encoder reads the query and a chunk together, so that their tokens attend to each other. It is more accurate, but nothing can be computed ahead of time: it runs one pass of the model per query-chunk pair, i.e. one per chunk for every query. This is why the cross-encoder only reranks the few candidates of the retriever.
The encoders of a bi-encoder, its towers, follow one of three designs:
- one shared tower, a Siamese network, is the most common for text. It has the fewest weights, and maps the queries and the chunks to one space by construction, but the same weights must encode both the short queries and the long chunks;
- one tower per input, e.g. one BERT for the questions and one for the passages in DPR, the retriever of the original RAG, lets each tower specialize, at the cost of twice the weights;
- one tower per modality, e.g. one encoder for the images and one for the text in CLIP, is needed when the inputs are of different kinds. However, it takes large datasets of paired inputs to align them, such as the 400 million image-text pairs of CLIP.
The code follows the last design, as its inputs have three modalities, with one small feed-forward tower per modality. For simplicity, the inputs of all modalities have the same size D_IN, and embed runs each input through the tower of its modality:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
D_IN, D_HIDDEN, D_EMB = 12, 32, 8
N_MODALITIES, N_NEG = 3, 10 # one tower per modality, negatives shared by the batch
def ffn(d_in=D_IN, d_out=D_EMB): # a small feed-forward network
return nn.Sequential(nn.Linear(d_in, D_HIDDEN), nn.ReLU(), nn.Linear(D_HIDDEN, d_out))
encoders = nn.ModuleList(ffn() for _ in range(N_MODALITIES))
def embed(inputs): # (modality, x) pairs, each x of shape [1, D_IN] -> [len(inputs), D_EMB]
return torch.cat([encoders[m](x) for m, x in inputs])
Training with InfoNCE
A bi-encoder learns from positive pairs, a query and a chunk that answers it, and from negatives, chunks that do not. Four losses are common:
- the contrastive loss takes one pair at a time, labeled as positive or negative, pulls a positive pair together, and pushes a negative pair at least a margin apart;
- the triplet loss takes a query, a positive and a negative, and makes the negative farther from the query than the positive, by a margin;
- the pairwise logistic loss of Bayesian Personalized Ranking (BPR), common in recommender systems, takes the same triplets and minimizes \(-\log \sigma(s^+ - s^-)\), where \(s^+\) and \(s^-\) are the scores of the positive and the negative. The positive then ranks first, with no margin;
- InfoNCE compares a query with its keys, one positive and many negatives, at once. The softmax of the cosine similarities of the query with all of them, each divided by a temperature \(\tau\), is a distribution over the chunks, and InfoNCE is its cross-entropy with the positive. The softmax, rather than a division of the similarities by their sum, makes this distribution, as the cosines can be negative.
The following picture shows the training with the contrastive loss and with InfoNCE, and the training of CLIP:
A Siamese network trained with the contrastive loss on one labeled pair (top) and with InfoNCE on \(B = 2\) queries (middle), and the two towers of CLIP trained on \(B = 3\) images and their captions (bottom). Each row of the cosine similarities compares one query \(q_i\) with all the keys: its positive \(k_i^+\) is green, and all the other keys are its negatives (red), the positive and the hard negatives \(k_{i,j}^-\) of the other query included.
Only InfoNCE is implemented, as it is the loss of most retrievers. The negatives of a query are the positives of the other queries of the batch (in-batch negatives), so it needs only positive pairs. Each query then gets many negatives from one matrix multiplication, while the other three losses see one negative at a time. It also trains the positive to rank first among all the keys, which is the task of a retriever. Extra negatives, such as the hard negatives of each query, which look relevant but do not answer it, add columns to the similarities, which then hold one row per query and one column per key. CLIP trains with a symmetric InfoNCE, on the \(B \times B\) similarities of \(B\) images and their captions: along each row, an image picks its caption, and along each column, a caption picks its image.
In info_nce, the keys hold the \(B\) positives first, on the diagonal of the similarities, and then N_NEG negatives shared by all the queries. Its last line is the mean of \(-\log\) of the softmax of each positive, i.e. F.cross_entropy(S, torch.arange(len(Q))). It uses logsumexp, which subtracts the largest similarity of each row before the exponentials, so that the loss stays finite for a small \(\tau\):
def info_nce(Q, K, tau=0.1): # Q: [B, E] queries, K: [B + N_NEG, E] keys, the positives first
Q = Q / Q.norm(dim=-1, keepdim=True) # unit vectors, so that Q @ K.T holds the cosines
K = K / K.norm(dim=-1, keepdim=True)
S = Q @ K.T / tau # [B, B + N_NEG], one row of similarities per query
return -(S.diagonal() - S.logsumexp(dim=1)).mean()
The training loop embeds the queries and the keys of each batch, and minimizes InfoNCE:
opt = torch.optim.SGD(encoders.parameters(), lr=0.01)
for queries, positives, negatives in batches: # B queries, their B positives, N_NEG negatives
Q = embed(queries) # [B, D_EMB]
K = embed(positives + negatives) # [B + N_NEG, D_EMB], the positives first
loss = info_nce(Q, K)
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
VectorDB and Retriever
Ahead of time, the trained towers embed all the chunks, and the vector database stores them as unit vectors, in the rows of a matrix:
with torch.no_grad(): # no gradients are needed to embed the chunks
X = embed(chunks).numpy() # [N, D_EMB], one row per chunk
X /= np.sqrt((X ** 2).sum(1, keepdims=True)) # unit vectors
The core of the database is the search of the nearest neighbors of a query, as in k-nearest neighbors, over millions to billions of vectors. Besides RAG, the same search serves a semantic cache: the database stores the embeddings of past queries with the answers of the LLM. A new query close enough to a past one, e.g. with a cosine similarity above a threshold, then gets the stored answer without a call to the LLM.
An exact search scores all the \(N\) vectors of the database, i.e. \(O(Nd)\) operations per query in \(d\) dimensions, which is too slow at this scale. The spatial indexes of databases, such as k-d trees, do not help either, due to the curse of dimensionality. Vector databases therefore use an approximate nearest neighbor (ANN) search, which returns most of the true nearest neighbors, i.e. a high recall, for a small fraction of the work. It works on embeddings, as they lie close to a manifold of much lower dimension than their number of coordinates, so the nearest neighbors of a query still stand out. The following indexes use the squared Euclidean distance on unit vectors.
Inverted File Index
An inverted file index (IVF) clusters the vectors with k-means, and keeps the list of the vectors of each cluster, i.e. of each Voronoi cell of the means. A query is compared with the means, and only the vectors of its few closest cells (the probes) are searched, as the following picture illustrates:
1. The vectors, clustered by k-means into cells, with their means (black dots). 2. A query (red) is compared with the means, and only the vectors of its 2 closest cells (colored) are searched; the other vectors (white) are skipped.
IVF clusters the vectors once, with W, cells = kmeans(X, 100) (the kmeans function of the clustering post), and a query scans only the vectors of its probes closest cells:
def ivf_search(X, W, cells, q, n, probes=5):
nearest = np.argsort(((W - q) ** 2).sum(1))[:probes] # the cells closest to q
ids = np.flatnonzero(np.isin(cells, nearest)) # the vectors of these cells
return ids[np.argsort(((X[ids] - q) ** 2).sum(1))[:n]] # the n nearest among them
A nearest neighbor in a cell that is not probed is missed: more probes find more of the true nearest neighbors, at a higher cost.
Product Quantization
Product quantization (PQ) compresses the vectors. Each vector is split into \(m\) sub-vectors, and each sub-vector is replaced by the index of its closest mean in a small k-means codebook of its part, e.g. one byte for 256 means. A vector of \(d\) FP32 values is then stored in \(m\) bytes instead of \(4d\). The distance from a query to a stored vector is the sum of the distances from the sub-vectors of the query to the means of its codes. These distances are read from one small table per part (parts is \(m\) in the code):
def pq_index(X, parts=8, centroids=256):
books, codes = [], []
for P in np.split(X, parts, axis=1): # the sub-vectors of all vectors, part by part
W, labels = kmeans(P, centroids) # the codebook of the part
books.append(W)
codes.append(labels)
return books, np.array(codes, dtype=np.uint8).T # one byte per sub-vector
def pq_search(books, codes, q, n):
tables = [((W - p) ** 2).sum(1) for W, p in zip(books, np.split(q, len(books)))]
dist = sum(table[codes[:, j]] for j, table in enumerate(tables)) # table lookups
return np.argsort(dist)[:n]
The distances of PQ are approximate, so its best candidates are usually ranked again with their exact distances. PQ is often combined with IVF (IVF-PQ), whose cells then hold the codes of their vectors, to search billions of vectors that do not fit in memory in full.
HNSW
Hierarchical Navigable Small World (HNSW) is a graph index: each vector is a node, linked to its nearest neighbors. The bottom layer of the graph holds all the nodes, and each layer above holds a random subset of the nodes of the layer below, with longer links. A query walks greedily from node to node in the top layer, always to the neighbor closest to the query, until no neighbor is closer. It then goes down one layer, from the node where it stopped, and repeats the walk until the bottom layer. Thus, the upper layers make long jumps across the data, and the lower layers refine the search, as the following picture illustrates:
The three layers of an HNSW graph of 2D points, from the top layer (left) to the bottom layer (right), which holds all the points. In each layer, the walk of the query (red) starts at the entry point (black), and moves to the neighbor closest to the query (red arrows) until no neighbor is closer. The node where it stops is the entry point of the layer below, and the walk ends at the nearest neighbor of the query in the bottom layer.
A new vector is inserted with the same search. It gets a random top layer, so that each layer holds about \(1/M\) of the nodes of the layer below, and it is linked to its \(M\) nearest nodes in its top layer and in each layer below it. Each node keeps at most \(M\) links (\(2M\) in the bottom layer). In the code, search_layer is a best-first search in one layer: it keeps the ef nearest nodes that it has found, and expands the nearest one that it has not expanded yet, until all of them are expanded. With ef = 1, it is the greedy walk of the picture:
def search_layer(X, graph, q, entries, ef): # the ef nearest nodes to q that it finds
found = sorted(zip(((X[entries] - q) ** 2).sum(1), entries)) # (distance, node)
seen, done = set(entries), set()
while todo := [i for _, i in found if i not in done]: # the nodes not expanded yet
done.add(todo[0]) # expand the nearest of them
new = [j for j in graph[todo[0]] if j not in seen]
seen.update(new)
found = sorted(found + list(zip(((X[new] - q) ** 2).sum(1), new)))[:ef]
return [i for _, i in found]
def nearest(X, i, nodes, M): # the M nodes closest to node i
return sorted(nodes, key=lambda j: ((X[i] - X[j]) ** 2).sum())[:M]
def hnsw_index(X, M=8, ef=32, seed=0):
rng = np.random.default_rng(seed)
graphs, entry = [], 0 # graphs[l][i]: the neighbors of node i in layer l
for i in range(len(X)):
top = int(rng.exponential() / np.log(M)) # the top layer of node i
ep = [entry]
for l in range(len(graphs) - 1, -1, -1): # from the top layer down
ep = search_layer(X, graphs[l], X[i], ep, ef if l <= top else 1)
if l <= top: # links to its M nearest nodes, and back
graphs[l][i] = ep[:M]
for j in ep[:M]:
graphs[l][j] = nearest(X, j, graphs[l][j] + [i], 2 * M if l == 0 else M)
if top >= len(graphs): # new layers, with node i as their entry point
graphs += [{i: []} for _ in range(top + 1 - len(graphs))]
entry = i
return graphs, entry
def hnsw_search(X, graphs, entry, q, n, ef=32):
ep = [entry]
for graph in graphs[:0:-1]: # a greedy walk in each upper layer, from the top
ep = search_layer(X, graph, q, ep, 1)
return search_layer(X, graphs[0], q, ep, max(ef, n))[:n]
Compared with IVF and PQ, HNSW reaches a higher recall for a given query time, but its index is slow to build and keeps the full vectors and their links in memory. Thus, HNSW is the usual choice when the vectors fit in memory, and IVF-PQ when they do not.
Retrieval
At query time, the retriever embeds the query with the same towers, normalizes it as the chunks, and asks the index for its \(n\) nearest chunks, e.g. with HNSW:
def retrieve(query, n=100): # the ids of the n chunks nearest to a query
with torch.no_grad():
q = embed([query]).numpy()[0]
return hnsw_search(X, graphs, entry, q / np.sqrt(q @ q), n)
The number of candidates \(n\) is a trade-off. A larger \(n\) raises the chance that the relevant chunks are among them, as the reranker can only reorder what it gets, but the reranker runs once per candidate. In practice, \(n\) is tens to a few hundred chunks, and \(k\) a handful. Also, embeddings may miss exact words, such as names, codes and numbers. Therefore, many systems merge the candidates of the embeddings with those of a lexical search, such as BM25, which scores the chunks by the words that they share with the query (hybrid search).
Faiss and Distributed Vector Databases
Faiss is the library of Meta that implements these indexes, on CPUs and GPUs. Its main indexes are:
- Flat (
IndexFlatL2,IndexFlatIP): the exact search, over all the vectors; - IVF (
IndexIVFFlat): the inverted file index above; - PQ (
IndexPQ): the product quantization above; - IVF-PQ (
IndexIVFPQ): IVF whose cells hold PQ codes, for billions of vectors; - HNSW (
IndexHNSWFlat): the graph above; - SQ (
IndexScalarQuantizer): scalar quantization, which quantizes each coordinate on its own, e.g. to 8 bits; - LSH (
IndexLSH): locality-sensitive hashing, which compares binary codes of the vectors by their Hamming distance; - CAGRA (
GpuIndexCagra): a graph index built for GPUs by NVIDIA (since Faiss 1.10).
When the vectors do not fit in the memory of one GPU or one node, the index is split into shards, each with a part of the vectors and its own index. A query is sent to all shards (a scatter), each shard returns its \(n\) nearest vectors, and these are merged into the global top-\(n\) (a gather). The latency of a query is thus the latency of the slowest shard, plus the merge:
def sharded_search(shards, q, n): # the ids and the vectors of each shard
D, I = [], []
for ids, X in shards: # in parallel, one shard per GPU or node
d = ((X - q) ** 2).sum(1) # or any of the indexes above
top = np.argsort(d)[:n] # the local top-n
D.append(d[top])
I.append(ids[top])
D, I = np.concatenate(D), np.concatenate(I) # gathered
return I[np.argsort(D)[:n]] # the global top-n
Reranker
The reranker is a cross-encoder: it reads the query and a candidate together, and returns a relevance score \(s\). In the code, it is a feed-forward network on the two inputs, each with a one-hot vector of its modality:
d_meta = 2 * N_MODALITIES # a one-hot of the modality of each input
reranker = ffn(2 * D_IN + d_meta, 1) # one score per (query, candidate) pair
def pair(q, c): # a query and a candidate, each a (modality, x) pair, as one input
(m1, x1), (m2, x2) = q, c
oh = F.one_hot(torch.tensor([m1, m2]), N_MODALITIES).float() # [2, N_MODALITIES]
return torch.cat([x1[0], oh[0], x2[0], oh[1]])
At query time, it scores the \(n\) candidates of the retriever, and only its top \(k\) reach the prompt. The whole retrieval of RAG is then rerank(query, retrieve(query)):
def rerank(query, ids, k=5): # the ids of the k best candidates
with torch.no_grad():
s = reranker(torch.stack([pair(query, chunks[i]) for i in ids]))[:, 0]
return [ids[i] for i in s.argsort(descending=True)[:k]]
Binary Cross-Entropy or ListNet
The reranker learns from lists of candidates with relevance labels, e.g. from human judgments of the results of the retriever. It is trained in one of two ways, as the following picture illustrates:
A reranker trained on one labeled pair with the binary cross-entropy (top), and on the list of \(n = 4\) candidates of a query with ListNet (bottom). The softmax turns the scores of the list into probabilities that compete with each other: here, two candidates are relevant (green), and two are not (red).
The pointwise training classifies each pair on its own, as relevant (\(y = 1\)) or not (\(y = 0\)). Its loss is the binary cross-entropy of the scores through the sigmoid \(\sigma\), given for the \(n\) candidates of a query by:
\[\mathcal{L}_\text{BCE} = -\frac{1}{n} \sum_{i=1}^{n} \Big( y_i \log \sigma(s_i) + (1 - y_i) \log \big( 1 - \sigma(s_i) \big) \Big)\]The listwise training of ListNet turns the scores of a list into a categorical distribution with a softmax, the probability that each candidate ranks first, and the labels into a second distribution in the same way. Its loss is the cross-entropy between the two (Eq. 2 in the paper):
\[\mathcal{L}_\text{ListNet} = - \sum_{i=1}^{n} P_y(i) \log P_s(i), \quad P_s(i) = \frac{\exp(s_i)}{\sum_{j=1}^{n} \exp(s_j)}\]where \(P_y\) is the softmax of the labels. With one relevant candidate per list, and its one-hot label as the target \(P_y\), ListNet is InfoNCE.
ListNet fits the task of the reranker, as only the order of the candidates of a query matters: its softmax makes them compete, so that raising one score lowers the probabilities of all the others. The binary cross-entropy fits each score to an absolute probability instead, so a list whose scores are all too high adds to the loss, even when its order is right. However, adding the same constant to all the scores of a list does not change its softmax. Thus, a reranker that must also drop the irrelevant candidates with a fixed threshold, e.g. \(\sigma(s) > 0.5\), is trained with the binary cross-entropy. Between the two, the pairwise RankNet applies the loss of BPR to two candidates at a time.
The code trains the reranker with the binary cross-entropy first, and then fine-tunes it with ListNet, by changing the line of the loss:
def list_net(S, Y): # S, Y: [B, n] scores and labels of B lists of n candidates
P = torch.softmax(Y, dim=-1) # the target distribution, from the labels
return F.cross_entropy(S, P) # the cross-entropy with the softmax of the scores
opt = torch.optim.SGD(reranker.parameters(), lr=0.01)
for X, Y in lists: # the n pairs of a query, [n, 2 * D_IN + d_meta], and their labels, [n, 1]
s = reranker(X) # [n, 1] scores
loss = F.binary_cross_entropy_with_logits(s, Y) # pointwise: each pair on its own
# loss = list_net(s.T, Y.T) # listwise: the n candidates as one list
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
Metrics
The retrieval is evaluated on a test set of queries whose relevant chunks are known. The label of a candidate, its relevance, is binary, or graded, e.g. from 0 for an irrelevant chunk to 3 for a chunk that answers the query. With \(r_i\) the relevance of the candidate at rank \(i\), the common metrics are:
- the recall at \(n\) (R@n), the fraction of the relevant chunks that are among the \(n\) candidates of the retriever. It is the metric of the retriever, as the reranker can only reorder its candidates;
- the precision at \(k\) (P@k), the fraction of the top \(k\) that is relevant, and the recall at \(k\) (R@k), the fraction of the relevant chunks that reach the prompt;
- the hit rate at \(k\), the fraction of the queries with at least one relevant chunk in their top \(k\), for questions that a single chunk answers;
- the mean reciprocal rank (MRR), the mean over the queries of \(1/i\), where \(i\) is the rank of the first relevant candidate, for questions with one right answer;
- the mean average precision (MAP), the mean over the queries of the average precision, the sum of the precisions at the ranks of the relevant candidates divided by the number of relevant chunks, for binary labels;
- the normalized discounted cumulative gain (NDCG) at \(k\), for graded labels, each discounted by its rank.
Only NDCG is implemented, as it is the most common metric of rerankers: it takes graded labels, and rewards the relevant chunks for coming first. The order matters, as LLMs use the start and the end of a long prompt better than its middle (Lost in the Middle). Finally, the answers of the LLM are compared with reference answers, or graded by another LLM, a judge: these metrics measure the whole pipeline, while the metrics above tell which stage to fix.
NDCG
The discounted cumulative gain (DCG) of the top \(k\) candidates adds their labels, each divided by the logarithm of its rank plus one, so that a relevant candidate counts less the lower it ranks:
\[\text{DCG@}k = \sum_{i=1}^{k} \frac{r_i}{\log_2(i + 1)}\]The DCG grows with the number of relevant candidates of a query, so it cannot be compared across queries. It is thus divided by the ideal DCG (IDCG@k), the DCG@k of the candidates sorted by their labels:
\[\text{NDCG@}k = \frac{\text{DCG@}k}{\text{IDCG@}k}\]The NDCG@k is then 1 for a perfect order, and the NDCG@k of a test set is its mean over the queries with at least one relevant candidate. A common variant uses the gain \(2^{r_i} - 1\) instead of the label \(r_i\), which rewards the highly relevant candidates more; for binary labels, both are the same. For the \(n\) candidates of a query, the NDCG@k is computed as:
def ndcg(scores, rel, k=5): # the scores and the labels of the n candidates of a query
r = rel[np.argsort(-scores)][:k] # the labels of the top k, in the predicted order
ideal = np.sort(rel)[::-1][:k] # the labels of the top k, in the ideal order
disc = np.log2(np.arange(2, len(r) + 2)) # log2(i + 1), for the ranks i = 1, 2, ...
return (r / disc).sum() / (ideal / disc).sum()