$\newcommand{\argmin}{\textrm{argmin}} \newcommand{\argmax}{\textrm{argmax}} \newcommand{\v}[2]{{#1}_{\mathrm{#2}}} \newcommand{\Exp}{\mathbb{E}} \newcommand{\Var}{V} \newcommand{\Obs}{\mathcal{O}} \newcommand{\RR}{\mathbb{R}} \newcommand{\matA}{\mathbf{A}} \newcommand{\matB}{\mathbf{B}} \newcommand{\matW}{\mathbf{W}} \newcommand{\matX}{\mathbf{X}} \newcommand{\matY}{\mathbf{Y}} \newcommand{\vx}{\mathbf{x}} \newcommand{\vy}{\mathbf{y}} \newcommand{\card}[1]{\left|#1\right|} \newcommand{\mat}[1]{\mathbf{#1}} \newcommand{\RV}{\mathbf{#1}} \newcommand{\RVX}{\mathbf{X}} \newcommand{\RVY}{\mathbf{X}} \newcommand{\RVY}{\mathbf{X}} \newcommand{\dpartial}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\seq}[2]{#1: #2} \newcommand{\softmax}{\textrm{softmax}} \newcommand{\Length}{L} \newcommand{\Tokens}{\mathcal{T}} \newcommand{\token}{t} \newcommand{\tokens}{\mathbf{t}} \newcommand{\prefix}{\mathbf{s}} \newcommand{\rep}[2]{\mathbf{r}_{#1}\left(#2\right)} \newcommand{\trep}[2]{\mathbf{x}^{(#1)}_{#2}} \newcommand{\tyrep}[2]{\mathbf{y}^{(#1)}_{#2}} \newcommand{\tXrep}[3]{\mathbf{#1}^{(#2)}_{#3}} % After SA \newcommand{\sarep}[2]{\mathbf{x}^{(#1{\scriptsize \angle SA})}_{#2}} \newcommand{\carep}[2]{\mathbf{x}^{(#1{\scriptsize \angle CA})}_{#2}} \newcommand{\arep}[2]{\mathbf{x}^{(#1{\scriptsize \angle A})}_{#2}}$
LLMs - RAG & Deep IR
Benjamin Piwowarski
Lecture 5
Press ? for help on keyboard shortcuts
Slides in PDF
► Overview

Today's Lecture

  1. Retrieval-Augmented Generation (RAG)
    • Motivation: addressing hallucinations
    • Architecture and components
  2. Information Retrieval Foundations
    • Traditional IR: BM25, TF-IDF
    • Evaluation metrics: Precision, Recall, nDCG
  3. Neural Information Retrieval
    • Dense models (bi-encoders) and vector indexing
    • Interaction models (cross-encoders, ColBERT)
    • Learned sparse models (SPLADE) and inverted indices
  4. Learning to Rank
    • Loss functions and training strategies

RAG: Retrieval-Augmented Generation

► With a Search Engine
► LLM: Information Access via Dialogue
Specialized responses based on retrieved context
Many applications beyond simple Q&A...
► Document Analysis
Question Answering architecture
Document analysis / summarization
Meeting transcripts and reports
► The Hallucination Problem
LLMs Make Things Up
  • Generate plausible but incorrect information
  • Confidently state outdated facts
  • Cannot access real-time information
  • Knowledge cutoff limits usefulness
Solution
Augment generation with retrieved information!

RAG Framework

► Retrieval-Augmented Generation (RAG)
Web search + document retrieval + LLM generation
RAG: Retrieval Augmented Generation
► RAG Pipeline
RAG Architecture
  1. Query - User question or prompt
  2. Retrieve - Find relevant documents from corpus
  3. Augment - Add retrieved context to prompt
  4. Generate - LLM produces answer grounded in context
Key Benefit
Grounds generation in retrieved facts, reducing hallucinations
► RAG Prompt Example
Augmented Prompt
Use the following context to answer the question. Context: [1] The Eiffel Tower is 330 meters tall and was completed in 1889 for the World's Fair. [2] It receives about 7 million visitors annually. Question: How tall is the Eiffel Tower? Answer based only on the provided context.
Without RAG
LLM might hallucinate: "The Eiffel Tower is 324 meters tall"
With RAG
LLM answers: "The Eiffel Tower is 330 meters tall [1"]
► RAG Components

Core Components

Retriever
Finds relevant documents (sparse, dense, or hybrid)
Document Store
Index of documents (vector DB, search engine)
Generator
LLM that produces the final response
Prompt Template
Combines query and retrieved context
► Does Better Retrieval Mean Better Answers?
The Assumption
Improving retrieval quality should improve answer quality... right?
RAG has a strong impact on answer quality
Rau, D. et al.
2024. BERGEN: A Benchmarking Library for Retrieval-Augmented Generation. Findings of the Association for Computational Linguistics: EMNLP 2024.
Most tasks are impacted positively, but... not always!
All LLMs can be positively impacted
Rau, D. et al.
2024. BERGEN: A Benchmarking Library for Retrieval-Augmented Generation. Findings of the Association for Computational Linguistics: EMNLP 2024.
All LLMs benefit from RAG, even strong ones (LLama 2-70B).
Strong correlation between retrieval and answer quality
Rau, D. et al.
2024. BERGEN: A Benchmarking Library for Retrieval-Augmented Generation. Findings of the Association for Computational Linguistics: EMNLP 2024.
There is a clear correlation between retrieval quality (Recall@5) and RAG performance
► When to Use RAG?

Use RAG When

  • Need up-to-date information
  • Domain-specific knowledge required
  • Factual accuracy is critical
  • Auditability needed (cite sources)

Consider Alternatives When

  • General knowledge is sufficient
  • Latency is critical
  • No relevant corpus available
  • Creative generation needed

Traditional Information Retrieval

IR Fundamentals

► What is Information Retrieval?
Definition
"Information retrieval (IR) is finding material (usually documents) of an unstructured nature (usually text) that satisfies an information need from within large collections (usually stored on computers)."
— C. Manning
Also in enterprises, digital libraries, personal computers...
Specialized domains: medicine, law, scientific literature
Most common application: search engines
► Information is Everywhere
Information is available
BUT: the problem lies in selection
Finding the right information for the right user at the right time
► The U-shaped Process
Indexing: Extract document content into an index; same process for queries to enable matching
Matching: Relate the indexed document collection with the processed query to identify relevant documents
Query Reformulation: Refine the user's information need throughout the search session
► Document Matching
Hypotheses Behind Document Matching

The more words query and document share, the more relevant the document

The more similar the term distributions, the more relevant the document

Classical Models

► Vector Space Model (Salton et al., 1975)
  • Feature space: terms $t_i$, $i = 1...n$ (preprocessed)
  • Documents and queries represented as weight vectors:
    • Document: $d = (x_0, ..., x_{n-1})$
    • Query: $q = (y_0, ..., y_{n-1})$
  • $x_k$ = weight of term $k$ in document $d$:
    • Presence/absence (binary)
    • Term frequency (TF)
    • TF-IDF (most common)

Similarity Measures

Inner Product

$$s(q,d) = q \cdot d = \sum_i x_i \cdot y_i$$

Cosine Similarity

$$s(q,d) = \frac{q \cdot d}{||q|| \cdot ||d||}$$
► Okapi-BM25 (Robertson et al., 1994)

Key Ideas

  • Extends the Binary Independence Model (BIM)
  • Eliteness: a term is "elite" if it represents the document
    • Elite terms follow Poisson distribution with parameter $\lambda_t$
    • Non-elite terms follow Poisson with $\mu_t < \lambda_t$
  • The more frequent a term, the more likely it is elite

BM25 Formula

$$s(q,d) = \sum_{t \in q \cap d} \underbrace{\log \frac{N - n_t + 0.5}{n_t + 0.5}}_{IDF} \times \underbrace{\frac{tf_t}{tf_t + k_1 \cdot B}}_{TF\ saturation}$$
where $B = (1-b) + b \cdot \frac{|d|}{avgdl}$ (document length normalization)

Parameters

  • $k_1 \approx 1.2$: saturation parameter
  • $b \approx 0.75$: length normalization

Intuition for $b$

  • $b=1$: verbose text (term repeats because doc is long)
  • $b=0$: multi-topic text (term repeats because important)

Evaluation Metrics

► Relevance and Evaluation
Relevance
A document is relevant if it satisfies the user's information need.

Contingency Table

RetrievedNot Retrieved
RelevantTP (true positive)FN (false negative)
Not RelevantFP (false positive)TN (true negative)
  • $R$ = set of relevant documents
  • $A$ = set of retrieved documents (answer)

Binary Relevance Metrics

Precision

Fraction of retrieved that are relevant: $P = \frac{|R \cap A|}{|A|} = \frac{TP}{TP + FP}$

Recall

Fraction of relevant that are retrieved: $R = \frac{|R \cap A|}{|R|} = \frac{TP}{TP + FN}$

F1 Score

Harmonic mean: $F_1 = \frac{2PR}{P + R} = \frac{2 \cdot TP}{2 \cdot TP + FP + FN}$
► Ranked Retrieval Metrics

Average Precision (AP)

Average of precision at each relevant document position
$$AP = \frac{1}{|R|} \sum_{k=1}^{n} P@k \cdot \text{rel}(k)$$
where $\text{rel}(k) = 1$ if document at rank $k$ is relevant, 0 otherwise

Mean Average Precision (MAP)

Mean of AP across queries
$$MAP = \frac{1}{|Q|} \sum_{q \in Q} AP(q)$$

Normalized Discounted Cumulative Gain (nDCG)

Accounts for graded relevance and position discount
$$nDCG@k = \frac{DCG@k}{IDCG@k} = \frac{\sum_{i=1}^{k} \frac{2^{rel_i} - 1}{\log_2(i+1)}}{IDCG@k}$$

Neural Information Retrieval

► Information Retrieval: Introduction
Information Retrieval (IR)
Finding documents relevant to an information need expressed as a query

The IR Task

Input

  • A collection of documents $\mathcal{D} = \{d_1, ..., d_n\}$
  • A query $q$ (user's information need)

Output

  • A ranked list of documents
  • Ordered by decreasing relevance to $q$

Key Challenges

  • Scale: Collections with millions/billions of documents
  • Speed: Sub-second response time required
  • Relevance: Understanding semantic meaning, not just keywords
► From Classical to Neural IR

Classical IR (1960s-2010s)

  • Bag-of-words: TF-IDF, BM25
  • Exact term matching
  • Fast and scalable (inverted index)
  • Vocabulary mismatch problem ("car" vs "automobile")

Neural IR (2013-now)

  • Semantic matching beyond exact keywords
  • Better relevance (understands meaning)
  • Computationally expensive

Key Question

How to combine the efficiency of classical IR with the effectiveness of neural models?
How to learn neural models that generalize well to other collections that the one used for training?
► Neural IR: Overview

Representation based

A score is computed from fixed document and query embeddings

Late-Interaction

A score is computed for each pair of query and document token embeddings. Those pairwise scores are aggregated into a final query-document score.

Early-Interaction

Uses the full interaction between query and document tokens to compute a relevance score.
► Multi-Stage Retrieval

Pipeline Architecture

  1. First Stage: Fast retrieval (BM25, dense bi-encoder)
    Retrieve top-K candidates (K = 100-1000)
    Rely on efficient indices (inverted index, ANN index)
  2. Second Stage: Re-ranking (cross-encoder)
    Score all K candidates with expensive model
  3. Optional Third Stage: Diversification, filtering
    Remove duplicates, apply business rules
Why Multi-Stage?
Cross-encoders are accurate but expensive
First stage reduces candidates to manageable size

Dense Text Representations

► Text Embeddings
Semantic Space
Every text $t$ is represented by $f_\theta(t) \in \mathbb{R}^n$
  • Symmetric model: $s(t_1, t_2) = g(f_\theta(t_1), f_\theta(t_2))$
  • Asymmetric model: $s(t_1, t_2) = g(f^{(q)}_\theta(t_1), f^{(d)}_\theta(t_2))$
Challenge
  • Text is a sequence (words, characters)
  • Neural networks expect fixed-size inputs
  • How to get fixed-size representations?
► DSSM (2013)

One of the first neural IR models

Huang, P. et al.
2013. Learning Deep Structured Semantic Models for Web Search Using Clickthrough Data.
There were quite a few works (skipped here) before modern dense architectures based on Transformers (next slide)
► Modern Dense Models
All based on the same pattern
A vector space model using transformer representations:
$$\hat q = \text{BERT}_{\text{[CLS]}}(\text{[CLS]}\ q_1 \ldots q_n\ \text{[SEP]})$$
and
$$\hat d = \text{BERT}_{\text{[CLS]}}(\text{[CLS]}\ d_1 \ldots d_m\ \text{[SEP]})$$
The score is given by $s(q,d) = \hat q \cdot \hat d$
Alternative: use mean pooling instead of [CLS] token
And... that's it!

Dense Indexing

► Efficient Dense Retrieval
Searching in Dense Space
Computing dot products with all documents is expensive ($O(n)$)
How can we speed up retrieval?

Two complementary approaches

  • Graph-based methods (HNSW): reduce number of comparisons
  • Quantization (PQ): make each comparison faster
► HNSW: Hierarchical Navigable Small World
Malkov, Y.A. and Yashunin, D.A.
2018. Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs.
From Pinecone.io

Properties

  • Search complexity: $O(\log n)$ instead of $O(n)$
  • Approximate: may miss some relevant documents
  • Trade-off: more layers/neighbors → better recall, slower search
► Product Quantization (PQ)
Jegou, H. et al.
2011. Product Quantization for Nearest Neighbor Search.

Idea

  • Split $d$-dimensional vector into $m$ subvectors of dimension $d/m$
  • Quantize each subvector independently using a codebook of $k$ centroids
  • Store only the centroid indices (e.g., $m \times 8$ bits instead of $d \times 32$ bits)

Example ($d=128$, $m=8$, $k=256$)

Original vector

128 floats = 512 bytes

PQ encoding

8 subvectors × 1 byte = 8 bytes

Compression

64× smaller!

Distance computation

  • Precompute distances from query subvectors to all centroids
  • Approximate distance = sum of table lookups
  • $$d(q, x) \approx \sum_{i=1}^{m} d(q^{(i)}, c_{\hat x_i}^{(i)})$$
► FAISS Library
FAISS
Facebook AI Similarity Search - library for efficient similarity search

Index Types

Flat
Exact search, no compression
IVF (Inverted File)
Cluster-based, probe nearest clusters
HNSW
Hierarchical Navigable Small World graphs
PQ (Product Quantization)
Compress vectors into codes

Learned Sparse Retrieval

► Motivation
Inverted indices are efficient!
Why not use sparse representations?
We can then rank all documents efficiently
Idea #1: learn term weights
► DeepCT, HDCT
Idea: Predict term weights using contextualized representations
Based on BERT contextual embeddings + linear model
Dai, Z. and Callan, J.
2019. Context-Aware Sentence/Passage Term Importance Estimation For First Stage Retrieval.
► DeepCT Details
Term weight estimated by linear transformation of BERT contextual representation $x^{(t)}$
$$y_{t,d} = x^{(t)} \cdot w_1 + b_1$$
$$y_{t,q} = x^{(t)} \cdot w_2 + b_2$$
Score: $rsv(q,d) = \sum_{t \in q} y_{t,q} \cdot y_{t,d}$
Target values $y$ from relevance estimates on training data
Absent words are not added (no expansion)
Idea #2: Expand documents with generative models
► Doc2Query and DocT5TTT
Generate questions that the document answers
Nogueira, R. et al.
2019. Document Expansion by Query Prediction.
(DocT5TTT is the same approach using T5 instead of BERT)
► DeepImpact
Combine vocabulary expansion and term weighting
DocT5 (vocabulary expansion) + DeepCT (term weights)
Mallia, A. et al.
2021. Learning Passage Impacts for Inverted Indexes.
Idea #3: Learn sparse representations directly
► SparTerm and SPLADE
Predict vocabulary weights for each token
Pooling mechanism (= 1 weight per word at the end)
Bai, Y. et al.
2020. SparTerm: Learning Term-based Sparse Representation for Fast Text Retrieval.
► Sparse Representations: Intuition
MLM task naturally induces vocabulary expansion
► SPLADE Details
Formal, T. et al.
2021. SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking. Proceedings of the 44th International ACM SIGIR Conference on Research and Development in Information Retrieval.
Estimate weight $w_{td}$ of term $t$ in document $d$:
$$w_{td}= \log\left(1 + \max_{i \in d} \text{ReLU}(y_{i}^{(t)})\right)$$
with
$$y_{i}^{(t)} = \text{BERT}_i(d) \cdot \theta_t + b_t$$
where $\text{BERT}_i(d)$ is the contextualized embedding of token $i$ in document $d$

Training Objective

  • IR Loss: infoNCE or distillation
  • Sparsity Loss: FLOPS regularization to limit number of active terms
    $$\mathcal{L}_{\text{FLOPS}} = \lambda_d \sum_{t \in V} \bar{w}_{t,d}^2 + \lambda_q \sum_{t \in V} \bar{w}_{t,q}^2$$
    where $\bar{w}_{t,q}$ and $\bar{w}_{t,d}$ are mean weights of term $t$ over queries / documents (batch)
► Sparse Models: Conclusion
Excellent results (much better than BM25)
Easy to train (SparTerm, SPLADE) or use (DocT5TTT)
To reach state-of-the-art, still need re-ranking (e.g., with monoBERT)

Sparse Indexing

► Inverted Index

Classic Approach

  • Map each term to list of documents containing it
  • Store term frequencies and positions
  • Efficient for exact term matching
  • Well-understood compression techniques

For Learned Sparse (SPLADE, etc.)

  • Same structure, but with learned term weights
  • May have expanded vocabulary
  • Can use standard search engines (Lucene, Elasticsearch)
► WAND Algorithm
Broder, A.Z. et al.
2003. Efficient Query Evaluation Using a Two-Level Retrieval Process. Proceedings of the Twelfth International Conference on Information and Knowledge Management.

Basic Idea

  • Weighted AND - efficient top-k retrieval
  • Each posting list has a max weight (upper bound for any doc in the list)
  • Find pivot: smallest doc_id where cumulative max weights ≥ threshold

How it works

  1. Accumulate max weights until sum ≥ θ → this term's doc_id is the pivot
  2. If all cursors point to pivot → evaluate document, update θ
  3. Otherwise → skip: advance cursors with doc_id < pivot to pivot
Key: we can jump directly to pivot, skipping many documents
► WAND: Example

Setup

  • Query: "cat food", top-1
  • θ = 0 initially

Posting Lists

TermMaxPostings (doc: weight)
cat3.0d1: 2.5, d2: 3.0, d3, d4, d5: 3.0
food4.0d2: 3.0, d5: 2.0
Evaluated / Skipped

WAND Execution

  1. cat→d1, food→d2
    Accumulate: cat(3.0) ≥ θ=0 → pivot=d1
    Only cat at d1 → evaluate: score=2.5, θ=2.5
    Advance cat→d2
  2. cat→d2, food→d2
    Accumulate: cat(3.0) ≥ θ → pivot=d2
    Both at d2 → evaluate: score=6.0, θ=6.0
    Advance cat→d3, food→d5
  3. cat→d3, food→d5
    Accumulate: cat(3.0) < θ, cat+food(7.0) ≥ θ → pivot=d5
    cat(d3) < pivot → skip cat to d5, both at d5
    evaluate: score=5.0 < θ, done
d3, d4 skipped: cat cursor jumped directly to d5
► Quantization for Learned Weights

The Problem

  • Learned weights are floating-point values
  • Standard inverted indices use integer term frequencies
  • Use quantization to convert learned weights to integers

In practice

Simple solution: repeat tokens according to quantized weight

SPLADE output

{"cat": 3.7, "food": 2.1, "pet": 1.8}

Quantization (10 steps, max=5)

cat:  round(3.7/5 × 10) = 7
food: round(2.1/5 × 10) = 4
pet:  round(1.8/5 × 10) = 4

PyTerrier input

"cat cat cat cat cat cat cat
 food food food food
 pet pet pet pet"

Interaction Models

► Motivation
Build attention maps from both texts
Benefit: Identify common terms (exact match) and similar terms (semantic match)
Use 2D aggregation techniques (convolution and/or pooling)
► MatchPyramid
Use object detection techniques
Hu, B. et al.
2014. Convolutional Neural Network Architectures for Matching Natural Language Sentences. Advances in Neural Information Processing Systems 27.
  • Interaction matrix
  • 2D convolution model
► DRMM: Deep Relevance Matching Model
Guo, J. et al.
2016. A Deep Relevance Matching Model for Ad-hoc Retrieval.
► KNRM: Kernel Neural Relevance Model
One of the best interaction models (before BERT...)
Generalization of DRMM
$$K_k(\underbrace{q_i \cdot d_j}_{I_{ij}}) = \exp\left( \frac{(I_{ij} - \mu_k)^2}{2\sigma_k^2} \right)$$
with $q_i$ the representation of query term $i$ and $d_j$ of document term $j$
Xiong, C. et al.
2017. End-to-End Neural Ad-hoc Ranking with Kernel Pooling.
► ColBERT
Even simpler: Interaction model with max aggregation
Key advantage: Can build an index!
Khattab, O. and Zaharia, M.
2020. ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT.
$$score(q,d) = \sum_{i=1}^{|q|} \max_{j=1}^{|d|} \underbrace{\cssId{colbert-sim}{\mathop{sim}}}(q_i, d_j)$$
cosine or inner product
► ColBERT: Pros and Cons

Advantages

  • Better effectiveness than bi-encoders
    Fine-grained token-level matching
  • Can build an ANN index
    Pre-compute document token embeddings offline
  • Faster than cross-encoders
    No query-document attention at query time

Disadvantages

  • Storage: store all token embeddings
    ~128 dims × ~180 tokens × 4 bytes ≈ 90 KB/doc
    MS MARCO (8.8M docs) ≈ 800 GB
  • Speed: ANN search per query token
    $|q|$ ANN lookups instead of 1
► ColBERTv2 and PLAID
Compression technique
$$\hat x_{di} = \underbrace{z_{j(x_{di})}}_{\text{cluster}} + \underbrace{\tilde x_{di}}_{\text{residual}}$$
Santhanam, K. et al.
2021. ColBERTv2: Effective and Efficient Retrieval via Lightweight Late Interaction.
PLAID: 3 increasingly precise filtering stages, then full computation
Santhanam, K. et al.
2022. PLAID: An Efficient Engine for Late Interaction Retrieval.
► Interaction Models: Conclusion
Interaction models achieve the best performance
Computationally expensive - though recent work shows significant simplification is possible while maintaining quality
(Generally, except ColBERT) Two-stage mechanism: select ~1000 documents then re-rank

Cross-Encoders

► Cross-Encoder with BERT (2019)
Concatenate query and target document, feed to BERT
Nogueira, R. and Cho, K.
2019. Passage Re-ranking with BERT.
Score $rsv(q,d)$ is computed from the [CLS] token representation (2-layer MLP)
And... that's it!
► Cross-Encoder Results
Excellent results...
But very expensive: recent work focuses on reducing processing time substantially
► Late Interaction: PreTTR
MacAvaney, S. et al.
2020. Efficient Document Re-Ranking for Transformers by Precomputing Term Representations. Proceedings of the 43rd International ACM SIGIR Conference on Research and Development in Information Retrieval.
► PreTTR Performance
Performance and latency on TREC WebTrack 2012 (re-ranking 100 documents)
MacAvaney, S. et al.
2020. Efficient Document Re-Ranking for Transformers by Precomputing Term Representations. Proceedings of the 43rd International ACM SIGIR Conference on Research and Development in Information Retrieval.

Learning to Rank

Problem Formulation

► The Learning to Rank Problem
Over time, many relevance indicators have been defined...
How to combine them
Each model (BM25, PageRank) measures a form of relevance
How to combine them optimally?
► Learning to Rank: Ingredients
A scoring function $\varphi(q,d)$
First article
Fuhr, N. and Buckley, C.
1991. A Probabilistic Learning Approach for Document Indexing.
$$\varphi(q,d) = \log P(R | q, d) = 1 - \exp(\Phi(q, d) \cdot { \color{red} \mathbf{\theta} } )$$
An IR dataset
  • Queries $q$
  • Document collection $D$
  • Relevant documents $D_q^+ \subseteq D$
  • Non-relevant documents $D_q^- \subseteq D$
We assume documents $D \setminus D_q^+$ are non-relevant
This is not always true!

Two-Stage Ranking

► Ranking and Learning
$\varphi$ is expensive to compute
$\varphi$ has been learned... but it's slow!
How can we make it faster?
Two-Stage Ranking
  1. Find top-K (e.g., $K=1000$) with BM25 or another fast model
  2. Re-rank the $K$ documents with $\varphi$
► Two-Stage Ranking: Consequences

(1) Re-ranking

Use examples after BM25 (or other first-stage retriever)

(2) Full Ranking

Sample from the entire document collection $D$
In both cases, always sample positive examples for training, but:
Full Ranking
Sample negatives using... other IR models
Hofstätter, S. et al.
2021. Improving Efficient Neural Ranking Models with Cross-Architecture Knowledge Distillation.
Re-ranking
Sample documents to re-rank using BM25

Loss Functions

► Fundamental Question
How to learn a model that maximizes an IR metric
Not possible in general (metrics are non-differentiable)
Use relaxations of the problem
Three approaches:
Pointwise
Predict relevance score for each (query, document) pair independently
Mostly classification (relevant/not relevant)
Pairwise
Learn to order pairs: given $(q, d^+, d^-)$, predict $s(q, d^+) > s(q, d^-)$
Binary classification on document pairs
Listwise
Optimize directly over the full ranked list
Approximate non-differentiable IR metrics (e.g., softmax over scores)
► Loss: Pointwise Cross-Entropy
PCE (Classification)
$$\Delta_{PCE}(p_\theta(q, d, y)) = y \log p_\theta(q, d) + (1-y) \log (1 - p_\theta(q,d))$$
Easy to implement
Can be unstable during training
► Loss: Max-Margin (Pairwise, Contrastive)
Max-Margin / Triplet Loss
$$\Delta(f_\theta(q, d_+), f_\theta(q, d_-)) = \max\left\{0, 1 - (f_\theta(q, d_+) - f_\theta(q, d_-))\right\}$$
Minimum (0) achieved when $f_\theta(q, d_+) > f_\theta(q, d_-) + 1$
► Loss: InfoNCE (Listwise, Contrastive)
InfoNCE
Loss defined over a list of documents $\approx$ IR metric
Currently the most widely used in L2R / IR
$$\Delta(f, q, \tilde D) = \sum_{d_+ \in \tilde D \cap D_q^+} R(q, d_+) \log \frac{\exp( f(q, d_+) )}{\sum_{d\in \tilde D} \exp( f(q, d) )}$$
where $R$ is 1 if $d$ is relevant for $q$ (0 otherwise)
Very common for pairwise ($\tilde D$ with two documents) re-ranking
For ranking, use batch documents as negatives
Key challenge: finding the best $\tilde D$
Lindgren, E. et al.
2021. Efficient Training of Retrieval Models Using Negative Cache.
► Loss: SoftRank (Listwise)
Taylor, M. et al.
2008. SoftRank: Optimizing Non-Smooth Rank Metrics. WSDM.
Can approximate nDCG with SoftNDCG
$$\mathbb{E}\left[nDCG\right] \approx \sum_{q \in \mathcal{Q}} \frac{g(d|q)}{CG_{\max}(q)} \sum_{r\ge 1} d(r) \cdot p(\mathbf{R} = r | q, d)$$
Two questions
  1. Why $\approx$?
  2. How to estimate $p(\mathbf{R} = r | q, d)$?
Use normal distribution to compute $p(\mathbf{R} = r | q, d)$
Let $\pi_{ij}$ be probability that $d_i$ ranks before $d_j$
Assuming $S_i \sim \mathcal{N}(\mu_i, \sigma^2)$ where $\mu_i$ is the retrieval score
$\pi_{ij} \Leftrightarrow S_i - S_j > 0$ corresponds to CDF of normal distribution (differentiable)

Training Strategies

► Weak Supervision
More data but noisier
User actions
  • Query reformulations
  • Clicks
  • Dwell time
Few labeled data but have models
We have queries (logs or generated, e.g., anchor text)
... but no relevance labels
Use existing models as teachers!
Dehghani, M. et al.
2017. Learning to Attend, Copy, and Generate for Session-Based Query Suggestion.
► Knowledge Distillation for IR
Born Again Neural Networks
A student trained to mimic a teacher can match or exceed the teacher's performance
Furlanello, T. et al.
2018. Born-Again Neural Networks. ICML.

Why Distillation in IR?

  1. Expensive teachers: Cross-encoder models are accurate but too slow for retrieval
  2. False negatives: Collections have few labels, many relevant docs marked as non-relevant
  3. No labels: We have queries (logs, generated) but no relevance judgments
► Distillation Pipeline

The Idea

Ding, Y.Q.Y. et al.
2020. RocketQA: An Optimized Training Approach to Dense Passage Retrieval for Open-Domain Question Answering. NAACL.
Gao, L. et al.
2020. Understanding BERT Rankers Under Distillation.
Hofstätter, S. et al.
2021. Efficiently Teaching an Effective Dense Retriever with Balanced Topic Aware Sampling.
Train a fast student model to mimic a powerful (but slow) teacher
Step 1: Retrieve candidates
Use a fast retriever (BM25, sparse model, or dense index)
query: "best pizza in NYC"
candidates: [d1, d2, d3, d4, d5, ...]  (top-k from BM25)
Step 2: Re-score with teacher
Use a powerful model (cross-encoder, or LLM with zero-shot)
teacher scores: [d1: 0.92, d2: 0.31, d3: 0.87, d4: 0.12, d5: 0.65, ...]
Step 3: Train student
Resulting dataset for training:
(q, [(d1, 0.92), (d2, 0.31), (d3, 0.87), (d4, 0.12), ...])
► Distillation Losses
Hofstätter, S. et al.
2021. Efficiently Teaching an Effective Dense Retriever with Balanced Topic Aware Sampling.

Margin-MSE

Match the margin between positive and negative pairs
$$\mathcal{L} = \left| (t^+ - t^-) - (s^+ - s^-) \right|^2$$
where $t^+, t^-$ are teacher scores, $s^+, s^-$ are student scores

KL Divergence

Match the full score distribution
$$\mathcal{L} = \text{KL}(\text{softmax}(t / \tau) \| \text{softmax}(s / \tau))$$
with temperature $\tau$ to soften distributions
We have seen how train an IR model...
... but how to pre-train it in the first place?
► Pre-training for IR
Better pre-training improves performance
Gao, L. and Callan, J.
2021. Condenser: A Pre-training Architecture for Dense Retrieval.
Force CLS to encode semantic information
Use document chunks as pseudo-queries
► RetroMAE: Masked Auto-Encoder for Retrieval
RetroMAE: Pre-Training Retrieval-oriented Language Models Via Masked Auto-Encoder:
2022. http://arxiv.org/abs/2205.12035.

Key Ideas

  1. Asymmetric encoder-decoder: Full BERT encoder, 1-layer decoder
  2. Asymmetric masking: Moderate for encoder (15-30%), aggressive for decoder (50-70%)
  3. MAE workflow: Encoder sees masked input → produces embedding → decoder reconstructs original

Why it Works

  • Encoder must compress all information into the embedding (aggressive decoder masking)
  • Forces the [CLS] representation to be semantically rich
  • Simple to implement, achieves SOTA on MS MARCO and BEIR

Architecture

Input: "The cat sat on the mat"
Encoder input (30% masked): "The [M] sat on the [M]" → embedding e
Decoder input (70% masked): "[M] [M] [M] on [M] mat" + e → reconstruct original
► Learning to Rank: Conclusion
Careful attention to sampling (ranking vs re-ranking)
Weak supervision possible (user interactions and/or classical models)
Distillation is very effective
Beware of transfer problems
Thakur, N. et al.
2021. BEIR: A Heterogenous Benchmark for Zero-shot Evaluation of Information Retrieval Models.
Zhan, J. et al.
2022. Evaluating Interpolation and Extrapolation Performance of Neural Retrieval Models. Proceedings of the 31st ACM International Conference on Information & Knowledge Management.
Can learn while indexing (Product Quantization)
Zhan, J. et al.
2021. Learning Discrete Representations via Constrained Clustering for Effective and Efficient Dense Retrieval.

Conclusion

► Key Takeaways
  • RAG Framework
    • Grounds generation in retrieved facts
    • Reduces hallucinations
    • Enables access to private/recent information
  • Neural IR Models
    • Dense models: fast but less precise
    • Cross-encoders: accurate but expensive
    • ColBERT: good balance with indexing capability
    • Sparse models: leverage inverted indices
  • Training & Deployment
    • Distillation from cross-encoders is effective
    • Two-stage retrieval is standard practice
    • Choose index based on scale and accuracy needs