Skip to content
AIAI Wranglers

32 Generative Models in Retrieval: From Memory to Meaning

The Philosophy of Retrieval – What Does It Mean to Remember?

You have lost your keys. You stand in the hallway, pockets empty, mind racing. Where did you last see them? You close your eyes. An image surfaces – the kitchen counter, the morning light, a coffee cup beside a set of keys. You walk to the kitchen. There they are.

What just happened? On the surface, a trivial act of memory. Beneath the surface, one of the most profound computational processes known to science. Your brain, without being told where to look, without scanning every object in the house, without any external index or catalogue, reconstructed a scene from partial cues, identified the relevant fragment, and translated that fragment into an action. It did not search for the keys in any mechanical sense. It remembered them – which is to say, it generated a plausible past from compressed traces of experience.

This chapter is about retrieval – the problem of finding relevant information given a need. But we begin with a confession: the word “retrieval” is misleading. It suggests a filing cabinet, a librarian pulling a book from a shelf, a database returning a row. These metaphors imply that the information exists somewhere in its original form, waiting to be fetched. The truth, as neuroscience and modern generative AI reveal, is far stranger. What we call retrieval is often closer to reconstruction, to generation, to the creative act of assembling meaning from fragments. Understanding this distinction – between retrieval as lookup and retrieval as generation – is the central theme of everything that follows.

Plato's Anamnesis: All Learning Is Recollection

Twenty-four centuries ago, Plato proposed a theory of knowledge that sounds, to modern ears, both mystical and eerily prescient. In the Meno dialogue, Socrates demonstrates that an uneducated slave boy can derive geometric truths when prompted with the right questions. Socrates' conclusion is startling: the boy did not learn these truths; he remembered them. The soul, Plato argues, has encountered all truths in a prior existence; what we call learning is merely anamnesis – recollection of what we already know.

Strip away the metaphysics, and Plato's insight contains a kernel that resonates with modern retrieval systems. The idea that knowledge is not acquired but recovered – that the answer to a question already exists, latent, in some compressed form, and the task is to surface it – is precisely what happens when a large language model answers a query. The model does not search an external database. It reaches into its parameters, into the compressed traces of billions of documents encountered during training, and reconstructs an answer. The parameters are the model's soul; inference is its anamnesis.

Remark 1.

Plato's anamnesis is not merely a historical curiosity. It foreshadows the distinction between retrieval-based and parametric knowledge systems that dominates modern NLP. A retrieval-based system consults an external corpus at query time. A parametric system (such as a language model) stores knowledge implicitly in its weights. The tension between these paradigms – and their eventual synthesis in retrieval-augmented generation – is a central arc of this chapter.

Aristotle's Associations: Similarity, Contiguity, Contrast

Where Plato looked upward to transcendent Forms, his student Aristotle looked around at the empirical world. In De Memoria et Reminiscentia (On Memory and Reminiscence), Aristotle proposed that memories are retrieved through three principles of association:

  1. Similarity. We recall things that resemble the current stimulus. The smell of cinnamon recalls your grandmother's kitchen. In computational terms, this is nearest-neighbour search in a feature space.

  2. Contiguity. We recall things that occurred together in space or time. The sight of a lecture hall recalls a specific class. This is co-occurrence statistics, the foundation of methods from TF-IDF to word embeddings [1].

  3. Contrast. We recall things that are opposite to the current stimulus. The word “hot” triggers “cold.” This is negative sampling, the mechanism by which modern embedding methods learn discriminative representations.

It is remarkable how directly these twenty-three-century-old principles map onto the core mechanisms of modern information retrieval. Similarity retrieval is the foundation of vector search. Contiguity is exploited by language models that learn from co-occurrence patterns. Contrast is the training signal in contrastive learning and hard negative mining. Aristotle did not have matrices, but he had the right intuitions.

Borges' Library of Babel: The Retrieval Problem

In 1941, Jorge Luis Borges published a short story that is, arguably, the most profound meditation on the retrieval problem ever written. “The Library of Babel” describes a universe consisting of an enormous library containing every possible book of a fixed length – every possible arrangement of twenty-five characters across 410 pages. The library contains every truth ever uttered and every truth yet to be discovered. It contains the complete works of Shakespeare, the cure for cancer, the biography of every person who will ever live. It also contains every possible variation of these texts with a single character changed, and every text that is pure gibberish.

The inhabitants of the library are driven mad. Not because the knowledge is unavailable – it is all there, every last word of it – but because they cannot find it. The ratio of meaningful books to meaningless ones is vanishingly small; a librarian could wander the hexagonal galleries for a lifetime without finding a single coherent sentence. Storage is solved. Retrieval is impossible.

Key Idea.

The Borges Principle: Storage Without Retrieval Is Meaningless. The Library of Babel teaches us that the fundamental problem of information systems is not how much we can store, but how well we can retrieve. A petabyte database without an effective retrieval mechanism is no more useful than Borges' infinite library. This insight motivates the entire field of information retrieval: the challenge is not in having answers, but in connecting questions to answers.

The modern internet is eerily close to Borges' vision. As of 2024, the indexed web contains hundreds of billions of pages. The vast majority are irrelevant to any given query. Google's PageRank algorithm, the neural retrieval models we shall study in later sections, and the retrieval-augmented generation pipelines that power modern AI assistants are all, in essence, solutions to the Library of Babel problem: mechanisms for finding the needle of relevance in the haystack of all possible texts.

Wittgenstein and the Contextuality of Meaning

There is a deeper problem that Borges' library does not address. Even if we could find the right book, would we know it was the right one? Relevance is not a property of documents in isolation; it depends on the query, the querier, the context, and the purpose.

Ludwig Wittgenstein, in his Philosophical Investigations (1953), argued that the meaning of a word is not some fixed, Platonic entity but its use in a language game – the social, contextual, practical circumstances in which it is employed. The word “bank” means one thing to a fisherman and another to a financier. The query “How to deal with depression” means one thing to a psychologist and another to a meteorologist studying atmospheric pressure systems.

Wittgenstein's insight cuts at the heart of a fundamental limitation of early retrieval systems. Term-matching approaches like TF-IDF [5] treat queries and documents as bags of tokens, ignoring the vast web of contextual meaning that determines relevance. A query for “jaguar speed” could seek information about the animal, the car, or the Atari game. The string is identical; the meaning is determined entirely by context.

This is why the transition from lexical retrieval (matching words) to semantic retrieval (matching meanings) represents one of the most important revolutions in the history of the field. Dense retrieval models – which embed queries and documents into a shared vector space where distance reflects semantic similarity rather than lexical overlap – are the computational realisation of Wittgenstein's philosophy. They encode not strings, but uses, not words, but meanings in context.

Insight.

Retrieval Is Not String Matching; It Is Meaning Matching. The evolution from lexical to semantic retrieval recapitulates, in the history of computer science, the philosophical journey from Plato's fixed Forms to Wittgenstein's contextual language games. Each word, each query, each document is a node in a vast network of usage, and its meaning is determined by its position in that network. Modern dense retrieval models learn precisely this network structure from data.

The Formal Retrieval Problem

Having gathered philosophical motivation, we now make the retrieval problem precise. Every retrieval system, from the ancient librarian of Alexandria to GPT-4's retrieval-augmented generation pipeline, can be understood as an instance of the following formalism.

Definition 1 (The Retrieval Problem).

Let 𝒬 be a query space and 𝒟 be a document space (or, more generally, an item space). Let :𝒬×𝒟{0,1} be a relevance function, where (𝒒,𝒅)=1 if and only if document 𝒅 is relevant to query 𝒒. The retrieval problem is: given a query 𝒒𝒬 and a corpus 𝒞={d1,d2,,dN}𝒟, produce a ranked list π=(dπ(1),dπ(2),,dπ(N)) such that relevant documents appear before irrelevant ones.

Formally, we seek a scoring function s:𝒬×𝒟 such that the induced ranking πs, defined by s(𝒒,dπs(i))s(𝒒,dπs(j)) for all i<j, maximises some evaluation metric Φ (e.g., average precision, nDCG) with respect to : (Retrieval Objective)s=arg maxs𝒮𝔼𝒒p(𝒬)[Φ(πs(𝒒),(𝒒,))], where 𝒮 is a family of scoring functions and p(𝒬) is the distribution over queries.

Example 1.

In web search, 𝒬 is the set of all possible text queries, 𝒟 is the set of all web pages, is determined by human relevance judgments (e.g., TREC assessors [2]), and the scoring function s is a complex pipeline combining BM25, neural rankers, click models, and personalisation signals. The metric Φ is typically nDCG [3].

Example 2.

In human memory recall, 𝒬 is the set of all possible cues (a smell, a sound, a question on an exam), 𝒟 is the set of all encoded memories, is determined by relevance to the current cognitive task, and s is the unconscious pattern-completion process implemented by hippocampal–cortical circuits. Evolution has optimised s over millions of years.

The retrieval spectrum, from exact string matching to semantic understanding and generative reasoning. Each stage represents an increase in the system's ability to bridge the gap between the surface form of a query and the deeper meaning of relevance. Generative retrieval models, the focus of this chapter, operate at the rightmost end of this spectrum.

The retrieval spectrum shown in fig:ret:retrieval_spectrum illustrates the central trajectory of this chapter. We begin with exact match – the simplest and oldest form of retrieval – and progress through sparse methods, dense methods, and finally generative retrieval, where the system does not merely find relevant documents but generates answers, identifiers, or entirely new text that synthesises information from multiple sources.

Retrieval as Reconstruction

We arrive at the central philosophical claim of this chapter, the thread that will weave through every section that follows.

Key Idea.

Retrieval Is Not Lookup; It Is Reconstruction. Classical retrieval systems treat the corpus as a static archive and the retrieval process as a lookup operation: find the document that matches the query. Generative retrieval systems invert this paradigm. They compress the corpus into the parameters of a neural network and, at query time, reconstruct the answer – or the document identifier, or the passage – from this compressed representation. In this view, retrieval and generation are not opposites but two facets of the same process: the recovery of meaning from compressed memory.

This reconstruction view unifies several threads that have traditionally been studied in isolation. Autoregressive language models that answer questions from their parameters are performing retrieval by generation. Retrieval-augmented generation systems that condition on retrieved passages are performing generation by retrieval. The boundary between the two dissolves once we recognise that both are instances of the same fundamental operation: reconstructing relevant information from a combination of parametric memory (weights) and non-parametric memory (the corpus).

Historical Note.

The Library of Alexandria: Humanity's First Retrieval Crisis. The Great Library of Alexandria, founded around 283 BCE under Ptolemy II, was the ancient world's most ambitious attempt to collect all human knowledge. At its peak, it held an estimated 400,000 to 700,000 scrolls. But as the collection grew, a crisis emerged that will sound familiar to any modern information scientist: how to find anything.

The solution came from the poet and scholar Callimachus, who created the Pinakes – a 120-volume catalogue that organised the library's holdings by genre (rhetoric, law, epic poetry, tragedy, comedy, lyric poetry, history, medicine, mathematics, natural science, miscellaneous) and within each genre, alphabetically by author. The Pinakes was, in effect, the world's first inverted index.

The lesson of Alexandria is that the problem of retrieval is as old as the problem of knowledge itself. Every information explosion – from the invention of writing, to the printing press, to the internet – creates a retrieval crisis that demands new organisational principles. We are living through such a crisis now, and generative models are the latest attempt at a solution.

Exercise 1.

Consider a simplified Library of Babel containing all possible strings of length L over an alphabet of size |Σ|.

  1. How many books does the library contain?

  2. If a “meaningful” book is one whose characters form valid English with probability at least ϵ under a language model p, estimate the fraction of meaningful books as a function of L, |Σ|, and the per-character entropy 𝖧 of English (approximately 1.3 bits per character, per Shannon [4]).

  3. Argue that as L, the retrieval problem in Borges' library becomes arbitrarily hard under any uniform scanning strategy, but remains tractable if one has access to a good language model as an oracle.

Exercise 2.

Plato's theory of anamnesis claims that learning is recollection. A large language model stores knowledge in its parameters and “recollects” it at inference time.

  1. In what precise sense is a forward pass through a language model analogous to Platonic recollection? Identify the analogue of the “prior existence” where knowledge was acquired.

  2. What is the key disanalogy? (Hint: consider hallucination.)

  3. Propose a formal test to distinguish whether a model is “retrieving” a memorised training passage or “generating” a novel synthesis.

Exercise 3.

Wittgenstein argued that meaning depends on context.

  1. Give three queries where the same words have completely different retrieval intents depending on the user's context.

  2. For each query, describe how a dense retrieval model with access to user context could resolve the ambiguity.

  3. Formalise the notion of “context-dependent relevance” by extending Definition 1 to include a context variable 𝒄𝒞ctx.

Exercise 4.

Place the following systems on the retrieval spectrum of fig:ret:retrieval_spectrum: (a) grep, (b) Google circa 2004, (c) a BERT cross-encoder reranker, (d) ChatGPT answering from parametric memory, (e) a retrieval-augmented generation system. Justify each placement.

Exercise 5.

The claim that “retrieval is reconstruction” has testable consequences.

  1. Describe an experiment that would distinguish between a retrieval system that performs pure lookup (returns a stored passage verbatim) and one that performs reconstruction (generates a response influenced by, but not identical to, stored data).

  2. Large language models sometimes “hallucinate” – they generate plausible but factually incorrect text. Argue that hallucination is a predictable consequence of the reconstruction view of retrieval.

  3. Propose a metric that quantifies the degree to which a system's output is “retrieved” versus “generated.” (Hint: consider measuring the n-gram overlap with the training corpus.)

The Neuroscience of Memory and Retrieval

If we wish to build machines that retrieve information as fluidly as the human mind, we would do well to understand how the mind itself accomplishes this feat. The brain is, among many other things, the most sophisticated retrieval engine ever constructed – capable of recovering a specific childhood memory from a whiff of perfume, of completing a partial melody from its first three notes, of answering a novel question by synthesising information from decades of experience. How does it do this?

The answer, as we shall see, offers profound lessons for the design of artificial retrieval systems – and reveals that the brain's approach to retrieval is far closer to generation than to lookup.

The Hippocampus as a Retrieval Engine

In 1953, a young man known as patient H.M. underwent bilateral surgical removal of his medial temporal lobes, including most of his hippocampus, as a treatment for severe epilepsy. The seizures stopped, but something else was lost: H.M. could no longer form new long-term memories. He could remember his childhood, carry on a conversation, and solve puzzles, but five minutes after meeting someone, he had no recollection of the encounter [41].

H.M.'s tragedy transformed our understanding of memory. It revealed that the hippocampus is not a passive storage vault but an active indexing and retrieval system – a biological analogue of the very retrieval engines we build in software. The hippocampus performs two critical functions:

Rapid encoding.

The hippocampus can encode new associations in a single exposure – a property called one-shot learning in the machine learning literature. When you meet someone new, your hippocampus rapidly binds together the person's face, name, voice, and the context of the encounter into a unified memory trace. This is achieved through a form of sparse, pattern-separated encoding: the hippocampal dentate gyrus uses highly sparse activity patterns to represent distinct memories, ensuring that similar experiences are stored in non-overlapping representations [35].

Pattern completion.

When a partial cue arrives – a familiar face, a fragment of a song, the smell of rain – the hippocampus performs pattern completion: it takes the partial input, matches it against stored memory traces, and reactivates the full memory, including components that were not present in the cue. You see the face and recall the name, the voice, the restaurant where you met. This is not lookup; it is reconstruction. The hippocampus does not store memories as complete records. It stores indices – compressed pointers that, when activated, trigger the reconstruction of the full memory from distributed cortical representations.

The parallels to modern retrieval systems are striking. The hippocampus is the index; the neocortex is the document store. Pattern completion is approximate nearest-neighbour search – finding the stored representation most similar to the query cue and then expanding it into a full response.

Consider what happens when you try to remember a colleague's name. The cue – perhaps the person's face – arrives at the hippocampus. The hippocampus does not search through every memory trace sequentially (that would be O(N) and the brain has billions of traces). Instead, the sparse activity pattern generated by the cue directly activates a small number of candidate memory traces through content-addressable lookup – the biological equivalent of hash-based or graph-based approximate nearest-neighbour search. The best-matching trace “wins” through a competitive process (lateral inhibition in CA3), and the full memory – name, voice, context – is reconstructed from the index pointer.

The computational cost of this biological retrieval is remarkable. The hippocampus achieves sublinear query time through three mechanisms that have direct analogues in computer science: locality-sensitive hashing (through sparse, random projections in the dentate gyrus), winner-take-all competition (through lateral inhibition in CA3), and iterative refinement (through recurrent dynamics that converge to an attractor state). Each of these mechanisms has inspired a family of approximate nearest-neighbour algorithms.

The mapping between biological memory systems and artificial retrieval architectures. The hippocampus functions as a fast index that encodes and retrieves memory traces, while the neocortex serves as a distributed document store holding detailed representations. Pattern completion in the CA3 region of the hippocampus is the biological analogue of approximate nearest-neighbour search in a vector index.

Episodic and Semantic Memory

In 1972, the cognitive psychologist Endel Tulving proposed a distinction that has profoundly shaped our understanding of memory and, by extension, of retrieval [36]. He argued that long-term memory comprises at least two qualitatively different systems:

Episodic memory.

Episodic memory stores specific, personally experienced events, bound to a particular time and place. You remember eating breakfast this morning, your first day of school, the moment you heard a particular piece of news. These memories are rich in contextual detail and are associated with a subjective sense of “re-experiencing” – what Tulving called autonoetic consciousness.

Semantic memory.

Semantic memory stores general knowledge about the world, abstracted from any particular experience. You know that Paris is the capital of France, that water freezes at 0C, and that mammals are warm-blooded. You do not remember when or where you learned these facts; the knowledge has been separated from its experiential context.

The distinction maps elegantly onto two modes of artificial retrieval:

  • Passage retrieval is analogous to episodic memory: the system returns specific documents or passages, each tied to a particular source and context. The user “re-experiences” the original text.

  • Parametric knowledge in a language model is analogous to semantic memory: the model “knows” facts but has lost the connection to the specific training documents from which they were learned. It cannot cite its sources, just as you cannot remember where you learned that 2+2=4.

Insight.

The Brain Does Not Store Memories Like Files. A crucial finding from decades of memory research is that human memories are not stored as fixed, high-fidelity records. They are reconstructed each time they are retrieved, assembled on the fly from distributed fragments, coloured by current emotional state, biased by subsequent experiences, and shaped by the specific retrieval cue. This is why eyewitness testimony is unreliable, why memories of childhood change over a lifetime, and why the act of remembering can itself alter the memory.

Generative retrieval models exhibit exactly this property. A language model does not “look up” a fact from its training data; it generates a response that is influenced by training data but reconstructed in the context of the current query. This is why language models hallucinate: they are doing exactly what human memory does – filling in gaps with plausible confabulations.

Engrams: The Physical Trace of Memory

Where does a memory live? The question haunted neuroscience for a century. In the early 1900s, Richard Semon coined the term engram to denote the physical trace that a memory leaves in the brain – the material substrate of recollection. Karl Lashley spent decades searching for the engram, systematically lesioning rat brains and testing for memory loss. His conclusion, formulated as the “law of mass action,” was that memories are not localised to specific regions but are distributed across the cortex.

The mystery was partially resolved by Susumu Tonegawa's Nobel Prize-winning work, which demonstrated that specific populations of neurons – engram cells – are activated during memory encoding and reactivated during recall [34]. By using optogenetic techniques to artificially activate engram cells in mice, Tonegawa's group could implant false memories – compelling evidence that these cells are indeed the physical substrate of memory.

The engram concept connects directly to the representations learned by neural retrieval models. When a dense retrieval model encodes a document into a vector 𝒅d, that vector is the document's engram – a compressed trace that captures the essential semantic content. When a query vector 𝒒 activates the most similar document vectors through approximate nearest-neighbour search, the system is performing artificial pattern completion, reactivating the “memory” most compatible with the current cue.

Remark 2.

The connection between engrams and embeddings is more than metaphorical. Both are distributed, compressed representations that support content-addressable retrieval. Both exhibit interference (similar memories/documents compete for activation). Both are subject to forgetting (catastrophic forgetting in neural networks; memory decay in biological systems). The parallels suggest that the brain and artificial retrieval systems have converged on similar computational solutions to the same fundamental problem.

Memory Consolidation: From Encoding to Retrieval

A memory is not created in a single instant. The process of transforming an experience into a retrievable memory involves three distinct stages, each with a computational analogue:

  1. Encoding. The experience is perceived and processed by sensory cortices, then rapidly bound into a coherent memory trace by the hippocampus. Computational analogue: the document encoder that maps raw text to a dense embedding vector.

  2. Storage (Consolidation). Over hours to weeks, the hippocampal memory trace is gradually transferred to the neocortex through a process of replay – during sleep, the hippocampus reactivates recent memories, and the neocortex slowly integrates them into its long-term representations. Computational analogue: the indexing phase, where document embeddings are organised into data structures (inverted indices, HNSW graphs, product quantisation codebooks) that support efficient retrieval.

  3. Retrieval. A cue activates the hippocampal index, which triggers pattern completion and reactivates the relevant cortical representations. Computational analogue: the query processing phase, where the query embedding is compared against indexed document embeddings to produce a ranked list of results.

The consolidation stage is particularly illuminating. The brain does not simply dump memories into long-term storage; it replays them, extracting regularities, building abstractions, and gradually transforming episodic memories into semantic knowledge. During slow-wave sleep, the hippocampus replays the day's experiences at compressed timescales (up to 20 times faster than real time), broadcasting them to the neocortex, which gradually integrates the new information into its existing knowledge structures. Over weeks and months, a memory that was once hippocampal-dependent – vivid, contextual, episodic – becomes cortical – abstract, decontextualised, semantic.

This process bears a remarkable resemblance to the distillation and fine-tuning procedures used to train generative retrieval models, where a large corpus is gradually compressed into the parameters of a neural network through repeated exposure during training. The training loop of a neural retrieval model is, computationally speaking, a form of artificial memory consolidation: raw data (experiences) are replayed (iterated over in training epochs) and gradually compressed into the model's parameters (long-term cortical representations).

Remark 3.

The parallel between sleep replay and training epochs is not merely poetic. Kumaran et al. (2016) showed that artificial neural networks trained with interleaved replay of old examples – mimicking hippocampal replay during sleep – exhibit less catastrophic forgetting than networks trained sequentially. This “experience replay” technique, now standard in reinforcement learning, was directly inspired by the neuroscience of memory consolidation.

Hebbian Learning and Associative Retrieval

In 1949, Donald Hebb proposed the principle that has become the most famous sentence in neuroscience: “When an axon of cell A is near enough to excite cell B and repeatedly or persistently takes part in firing it, some growth process or metabolic change takes place in one or both cells such that A's efficiency, as one of the cells firing B, is increased.” Or, as it is colloquially summarised: neurons that fire together wire together.

This principle – that synaptic connections strengthen between neurons that are co-activated – is the biological foundation of associative retrieval. If you repeatedly experience coffee and mornings together, the neural representations of “coffee” and “morning” become linked by strengthened synapses. Activating one pattern (the smell of coffee) automatically activates the other (the sense of morning).

The Hebbian rule can be formalised as a simple outer product update: (Hebbian Update)Δ𝐖=η𝒙𝒙, where 𝐖d×d is the weight (synapse) matrix, 𝒙d is the activity pattern being stored, and η is the learning rate. After storing M patterns 𝒙1,,𝒙M, the weight matrix becomes: (Hebbian Weight)𝐖=ηm=1M𝒙m𝒙m.

Given a partial cue 𝒙~ that is close to one of the stored patterns, the network performs retrieval by computing: (Hebbian Retrieval)𝒙^=𝐖𝒙~=ηm=1M𝒙m(𝒙m𝒙~)=ηm=1M𝒙m,𝒙~𝒙m.

This is nothing other than a weighted sum of stored patterns, where the weight on each pattern is its inner product with the query. If the stored patterns are orthogonal, the cue 𝒙~𝒙k will produce 𝒙^η𝒙k2𝒙k – perfect retrieval. When the patterns are not orthogonal (which is the typical case when M>d), the retrieved pattern is contaminated by crosstalk from other stored patterns: (Hebbian Crosstalk)𝒙^=η𝒙k,𝒙~𝒙k+ηmk𝒙m,𝒙~𝒙m. The first term is the signal (the desired memory); the second is the interference (crosstalk from other memories). Successful retrieval requires that the signal dominates the interference, which imposes an upper bound on the number of patterns that can be stored – the capacity of the associative memory.

This is the simplest form of content-addressable memory, and it is the mathematical ancestor of modern attention mechanisms. The progression from Hebb's rule to Hopfield networks to the transformer's attention mechanism is one of the most remarkable intellectual lineages in the history of computing – a direct line from neuroscience to the systems that now power web search and question answering.

Definition 2 (Content-Addressable Memory).

A content-addressable memory (CAM) is a system that, given a partial or noisy query pattern 𝒙~, returns the stored pattern 𝒙 that best matches the query: (CAM)𝒙=arg max𝒙m{𝒙1,,𝒙M}sim(𝒙~,𝒙m), where sim:d×d is a similarity function (e.g., inner product, cosine similarity, or negative Euclidean distance).

In the Hopfield network formulation, retrieval is performed by iterating the dynamics 𝒙t+1=sign(𝐖𝒙t) until convergence to a fixed point, which corresponds to the stored pattern closest to the initial state.

Remark 4.

The connection between Hebbian CAMs and modern attention is direct. In the transformer attention mechanism, the output is: (Attention AS CAM)Attention(𝐐,𝐊,𝐕)=softmax(𝐐𝐊dk)𝐕. The keys 𝐊 are the stored patterns, the query 𝐐 is the retrieval cue, and the softmax-weighted sum over values 𝐕 is a soft version of the pattern completion in (Hebbian Retrieval). Ramsauer et al. (2021) proved this connection formally, showing that modern Hopfield networks with exponential interaction functions are equivalent to the attention mechanism.

Sparse Distributed Representations in the Brain

The brain faces the same challenge as any large-scale retrieval system: how to store and retrieve a vast number of patterns without catastrophic interference. If every memory activated a large fraction of neurons, memories would blur together hopelessly – a phenomenon called crosstalk in the associative memory literature.

The brain's solution is sparse distributed representations (SDRs): each memory is encoded by a small, randomly chosen subset of neurons from a large population. In the hippocampal dentate gyrus, only about 2–4% of neurons are active for any given memory, ensuring that different memories have minimal overlap.

The capacity advantage of sparse coding is dramatic. For a Hopfield network with d neurons storing dense patterns, the storage capacity is approximately 0.14d patterns before retrieval errors occur. With sparse patterns of sparsity k/d (i.e., k active neurons out of d), the capacity scales as d2/(klogd) – a quadratic improvement.

Proposition 1 (Capacity of Sparse Associative Memory).

Consider a network of d binary neurons storing M random patterns, each with exactly k active neurons (kd). Using the sparse Hebbian storage rule, the maximum number of patterns that can be reliably retrieved is: (Sparse Capacity)Mmax=Θ(d2klogd). For the dense case (k=d/2), this reduces to Mmax=Θ(d/logd), matching the classical Hopfield capacity.

This result has a direct lesson for retrieval system design: sparse representations enable higher-capacity memories. This principle underlies the success of sparse retrieval methods (where document representations have most entries equal to zero) and explains why hybrid systems that combine sparse and dense representations often outperform either approach alone.

Exercise 6.

Consider a Hopfield network with d=100 neurons.

  1. What is the approximate storage capacity for dense (i.e., ±1) random patterns?

  2. If instead you use sparse patterns with k=5 active neurons, estimate the storage capacity using Proposition 1.

  3. Implement a Hopfield network in your favourite language. Store 10 random dense patterns and verify that you can retrieve each from a cue that has 20% of its bits flipped.

  4. Repeat with 20 patterns. At what point does retrieval begin to fail?

Exercise 7.

The connection between Hopfield networks and attention ((Attention AS CAM)) is deep.

  1. Show that when dk0 (i.e., the temperature in the softmax approaches zero), the attention output converges to the value vector associated with the key that has the highest inner product with the query. This is the “hard attention” limit.

  2. Explain why soft attention (finite dk) can be interpreted as retrieving a weighted combination of stored patterns rather than a single pattern.

  3. What is the computational complexity of attention-based retrieval over N stored patterns? How does this compare to approximate nearest-neighbour search with sublinear query time?

Exercise 8.

The memory consolidation process (encoding storage retrieval) maps onto the retrieval system pipeline (embedding indexing search).

  1. Identify a biological process that has no clear computational analogue in standard retrieval systems. (Hint: consider dreaming.)

  2. Propose a retrieval system design that incorporates an analogue of sleep-dependent memory consolidation. How might periodically “replaying” and reorganising the index improve retrieval quality?

  3. The brain forgets – and this is a feature, not a bug. Design a retrieval system that intentionally “forgets” stale or low-quality documents. What metric would you use to decide what to forget?

Formal Foundations of Information Retrieval

We now turn from philosophy and neuroscience to the mathematical foundations upon which all modern retrieval systems are built. The preceding sections established that the brain solves the retrieval problem through content-addressable memory, sparse encoding, and pattern completion – mechanisms that are associative, parallel, and approximate. The formal methods we study now represent humanity's attempt to solve the same problem with a fundamentally different substrate: discrete symbols, sequential algorithms, and exact data structures. The tension between these two approaches – the brain's fuzzy, generative reconstruction versus the computer's precise, lookup-based retrieval – is not merely historical. It is the very tension that generative retrieval models seek to resolve by bringing the brain's strategy into the digital realm.

The story of information retrieval is a story of successive abstractions: from manual catalogues to Boolean queries, from Boolean queries to ranked retrieval, from hand-crafted scoring functions to learned representations. Each step brought us closer to the semantic ideal – retrieval based on meaning rather than surface form – and each left behind a mathematical framework that remains in use today.

From Library Catalogues to Automated Retrieval

The dream of automated information retrieval is older than the electronic computer. In 1945, Vannevar Bush – then Director of the U.S. Office of Scientific Research and Development – published a visionary essay in The Atlantic Monthly entitled “As We May Think.” Bush described a hypothetical device called the Memex: a mechanised desk that would store an individual's books, records, and communications on microfilm, with the ability to retrieve any item instantly via associative trails – chains of links between related items that could be created, shared, and traversed.

Historical Note.

Vannevar Bush and the Memex (1945). Bush wrote: “Consider a future device in which an individual stores all his books, records, and communications, and which is mechanized so that it may be consulted with exceeding speed and flexibility. It is an enlarged intimate supplement to his memory.”

The Memex was never built, but its influence was immense. It directly inspired Douglas Engelbart's work on hypertext and the mouse, Ted Nelson's concept of hypertext (and the term itself), and Tim Berners-Lee's World Wide Web. Most remarkably, Bush identified the core problem of retrieval – not storage, but selection – and proposed associative indexing as the solution, foreshadowing both hyperlink-based retrieval (PageRank) and the associative memory models we discussed in Hebbian Learning and Associative Retrieval.

The first practical automated retrieval systems emerged in the 1960s, driven by the rapid growth of scientific literature. Gerard Salton's SMART system at Cornell, developed between 1961 and the 1990s, introduced many of the foundational concepts that remain central to the field: the vector space model, term weighting, relevance feedback, and automatic indexing [5].

The Cranfield experiments, conducted by Cyril Cleverdon at the College of Aeronautics in Cranfield, England, established the methodology of laboratory-based evaluation that persists in the TREC (Text REtrieval Conference) tradition to this day [2]. By constructing standardised test collections – a fixed corpus, a set of queries, and human relevance judgments – Cleverdon showed that retrieval systems could be compared objectively. This seemingly obvious insight was revolutionary: it transformed information retrieval from an art into an experimental science.

The classical information retrieval pipeline. Documents are preprocessed and stored in an inverted index at indexing time. At query time, the user's query is processed, matched against the index, scored (e.g., using BM25), and returned as a ranked list. The separation of indexing and query processing is a fundamental architectural pattern that persists in modern neural retrieval systems.

The Vector Space Model

The conceptual breakthrough that enabled quantitative retrieval was deceptively simple: represent both queries and documents as vectors in a high-dimensional space, and measure their similarity geometrically.

Let V={w1,w2,,w|V|} be the vocabulary – the set of all distinct terms that appear in the corpus. Each document d is represented as a vector 𝒅|V|, where the i-th component di encodes the importance of term wi in document d. Similarly, a query q is represented as a vector 𝒒|V|.

The relevance of document d to query q is then measured by the cosine similarity: (Cosine)cos(𝒒,𝒅)=𝒒,𝒅𝒒𝒅=i=1|V|qidii=1|V|qi2i=1|V|di2.

The critical question is: how should we set the weights di and qi? The simplest choice – binary indicators of term presence – is too crude. The term “the” appears in nearly every English document and provides no discrimination. The term “hippocampus” is rare and highly informative. We need a weighting scheme that captures both the local importance of a term within a document and its global discrimination power across the corpus.

TF-IDF: A First-Principles Derivation

The term frequency–inverse document frequency (TF-IDF) weighting scheme is perhaps the most important single formula in information retrieval. We derive it from first principles, motivating each component.

Term frequency (TF).

The more often a term w appears in a document d, the more likely the document is about a topic related to w. The raw term frequency is simply the count: (RAW TF)tf(w,d)=fw,d, where fw,d is the number of times w appears in d. However, raw counts are problematic. A document that mentions “retrieval” 100 times is not 100 times more relevant than one that mentions it once; the relationship between count and relevance is sublinear. Common choices for dampening include the logarithmic transform: (LOG TF)tflog(w,d)={1+logfw,dif fw,d>0,0otherwise, and the sublinear normalisation used in BM25, which we derive below.

Document frequency and inverse document frequency (IDF).

A term that appears in many documents is a poor discriminator. The word “the” may have high term frequency in a relevant document, but it also has high term frequency in every document. We penalise such terms using the inverse document frequency: (IDF)idf(w)=logNdf(w), where N is the total number of documents in the corpus and df(w) is the number of documents containing term w. Terms that appear in every document get idf=0; terms that appear in a single document get idf=logN.

The TF-IDF product.

The weight assigned to term w in document d is the product: (Tfidf)tfidf(w,d)=tf(w,d)idf(w).

Definition 3 (TF-IDF Scoring).

Given a query q={w1,,w|q|} (treated as a set or multiset of terms) and a document d, the TF-IDF relevance score is: (Tfidf Score)stfidf(q,d)=wqtf(w,d)idf(w). This is equivalent to the inner product 𝒒,𝒅 where 𝒒 and 𝒅 are the TF-IDF-weighted vectors of the query and document, respectively.

Example 3.

Consider a corpus of N=1,000,000 documents. A query contains the terms “generative” and “retrieval.” Suppose:

  • “generative” appears in 1,000 documents: idf=log(106/103)=log10006.91.

  • “retrieval” appears in 10,000 documents: idf=log(106/104)=log1004.61.

For a document where “generative” appears 5 times and “retrieval” appears 3 times, the score is: s=5×6.91+3×4.61=34.55+13.83=48.38. The rarer term “generative” contributes more to the score, despite appearing only slightly more often than “retrieval” in this document. This is the IDF component at work: it rewards specificity.

BM25: From Probabilistic Principles to Practice

TF-IDF, for all its elegance, is an ad hoc weighting scheme. Can we derive a principled scoring function from probability theory? The answer is yes, and the result is BM25 (“Best Match 25”), the most widely used retrieval scoring function in the world, powering everything from Elasticsearch to the first stage of Google's ranking [6].

The derivation begins with the Probabilistic Relevance Framework (PRF), developed by Stephen Robertson and Karen Spärck Jones in the 1970s.

The Binary Independence Model

Assume each document is represented as a binary vector 𝒅{0,1}|V|, where di=1 if term wi appears in the document and di=0 otherwise. Given a query q, we wish to estimate the probability that document d is relevant: P(R=1|𝒅,q), where R is a binary relevance variable.

By Bayes' theorem: (BIM Bayes)P(R=1|𝒅,q)=P(𝒅|R=1,q)P(R=1|q)P(𝒅|q).

The binary independence assumption states that, conditioned on relevance (or non-relevance), the terms in the document are independent: (BIM Independence)P(𝒅|R,q)=i=1|V|P(di|R,q).

Taking the log-odds ratio of relevance to non-relevance and applying the independence assumption yields the Retrieval Status Value (RSV): (BIM RSV)RSV(d,q)=logP(R=1|𝒅,q)P(R=0|𝒅,q)=i:di=1,qi=1logpi(1ri)ri(1pi)+C, where pi=P(di=1|R=1,q) is the probability that a relevant document contains term wi, ri=P(di=1|R=0,q) is the probability that a non-relevant document contains term wi, and C is a query-dependent constant that does not affect the ranking.

The 2-Poisson Model and BM25 Derivation

The binary independence model ignores term frequency: it knows only whether a term is present or absent. To incorporate term frequency, Robertson and Walker proposed the 2-Poisson model [42], which assumes that term occurrences in relevant documents follow a mixture of two Poisson distributions – one for “elite” terms (terms central to the document's topic) and one for non-elite terms: (2poisson)P(fw,d=k|R)=λeμ1μ1kk!+(1λ)eμ2μ2kk!, where μ1>μ2 and λ is the mixing weight.

The full derivation of BM25 from the 2-Poisson model involves substantial algebra. The key insight is that the log-odds contribution of term frequency can be approximated by a saturating function that increases with fw,d but approaches an asymptote. Robertson and Walker showed that the following formula provides an excellent approximation [6]:

Definition 4 (BM25 Scoring Function).

Given a query q={w1,,w|q|} and a document d of length dl(d) in a corpus of N documents with average document length avgdl, the BM25 score is: (BM25)sBM25(q,d)=wqidf(w)fw,d(k1+1)fw,d+k1(1b+bdl(d)avgdl), where:

  • fw,d is the frequency of term w in document d;

  • k1[1.2,2.0] is the term frequency saturation parameter – higher values allow term frequency to have more influence;

  • b[0,1] is the document length normalisation parameter – b=0 means no normalisation, b=1 means full normalisation relative to average document length;

  • idf(w) is typically computed as: (BM25 IDF)idf(w)=logNdf(w)+0.5df(w)+0.5.

The BM25 formula has a beautiful structure. The numerator fw,d(k1+1) ensures that the contribution grows with term frequency. The denominator introduces saturation: as fw,d, the TF component approaches k1+1, preventing any single term from dominating the score. The document length normalisation factor 1b+bdl(d)/avgdl ensures that longer documents are not unfairly rewarded simply for containing more terms.

BM25's term frequency saturation. Unlike raw TF (dashed red), BM25's TF component approaches an asymptote controlled by k1. Lower k1 values cause faster saturation, meaning that repeating a term beyond a few occurrences adds diminishing returns. This prevents keyword-stuffed documents from dominating results.

Proposition 2 (BM25 Limiting Behaviours).

The BM25 scoring function exhibits the following limiting behaviours:

  1. k10: The TF component becomes fw,d1fw,d+0=1 for all fw,d>0. BM25 reduces to binary term presence weighted by IDF – equivalent to the binary independence model.

  2. k1: The TF component approaches fw,d (linear TF). BM25 reduces to TF-IDF with document length normalisation.

  3. b=0: No document length normalisation. Longer documents are favoured because they naturally contain more term occurrences.

  4. b=1: Full length normalisation. The effective TF is divided by dl(d)/avgdl, fully compensating for document length.

Proof.

Part (1): Setting k1=0 in (BM25), the TF component becomes fw,d1/(fw,d+0)=1 for fw,d>0. The score reduces to wqdidf(w).

Part (2): For large k1, the denominator is dominated by k1, so the TF component approaches fw,d(k1+1)/(k1(1b+bdl/avgdl))fw,d/(1b+bdl/avgdl).

Parts (3) and (4) follow directly from substituting b=0 and b=1 into the length normalisation factor.

Probabilistic Language Models for Retrieval

An elegant alternative to the vector space approach is to view retrieval through the lens of language modelling. The core idea, introduced by Ponte and Croft (1998), is disarmingly simple: rank documents by the probability that the query was generated by the document's language model.

For each document d, we estimate a unigram language model p(|d) that defines a probability distribution over terms. The probability of generating query q=(w1,w2,,w|q|) from this model is: (Query Likelihood)p(q|d)=i=1|q|p(wi|d).

The maximum likelihood estimate of p(w|d) is simply the relative frequency: p^(w|d)=fw,d/|d|, where |d| is the length of document d. But this assigns zero probability to query terms not in the document, making any such document irretrievable. The solution is smoothing:

Jelinek-Mercer smoothing.

(JM Smoothing)pJM(w|d)=(1λ)fw,d|d|+λp(w|𝒞), where λ(0,1) is a smoothing parameter and p(w|𝒞) is the background language model estimated from the entire corpus.

Dirichlet smoothing.

(Dirichlet Smoothing)pμ(w|d)=fw,d+μp(w|𝒞)|d|+μ, where μ>0 is the Dirichlet prior parameter. This has the appealing property that shorter documents are smoothed more heavily (they have less evidence), while longer documents are smoothed less.

Taking the log of the query likelihood and dropping query-independent constants, the ranking function becomes: (LM Ranking)logp(q|d)=wqlogp(w|d)wqdlogp(w|d)p(w|𝒞)+C(q), where C(q) depends only on the query. The log-ratio log(p(w|d)/p(w|𝒞)) is positive when the term is more common in the document than in the corpus – a natural notion of term importance that arises automatically from the probabilistic framework, without the need to hand-design a weighting scheme like TF-IDF.

Theorem 1 (Equivalence of Language Model Retrieval and TF-IDF).

Under Jelinek-Mercer smoothing with λ0, the language model ranking of (LM Ranking) is equivalent to TF-IDF ranking with logarithmic TF and a specific IDF formula. Specifically, for documents of equal length and λ0: (LM Tfidf Equiv)logpJM(w|d)p(w|𝒞)logtf(w,d)+idf(w)+C, where C is a constant independent of d.

Proof.

With Jelinek-Mercer smoothing and λ0: pJM(w|d)fw,d/|d| for terms present in d. The background model is p(w|𝒞)=cf(w)/|𝒞|, where cf(w) is the total count of w in the corpus. Then: logpJM(w|d)p(w|𝒞)=logfw,d|𝒞||d|cf(w). For equal-length documents, |d| is constant. Writing cf(w)df(w)f, where f is the average within-document frequency, we get: logfw,d+log|𝒞||d|flogdf(w)=logfw,d+idf(w)+C. The first term is logarithmic TF; the second is an IDF-like term; the third is a constant.

The language model approach to retrieval is philosophically significant because it inverts the traditional direction of the retrieval problem. Instead of asking “how similar is this document to the query?” (a matching perspective), it asks “how likely is it that this document generated the query?” (a generative perspective). This inversion – from discriminative matching to generative modelling – is a precursor to the full generative retrieval paradigm that we develop in later sections. When we later study models that generate document identifiers autoregressively, we are taking the language model view of retrieval to its logical conclusion: the entire retrieval process becomes an act of conditional generation.

Remark 5.

The connection between smoothing and the exploration–exploitation trade-off is worth noting. Dirichlet smoothing with small μ emphasises the document's own statistics (exploitation – trust the document), while large μ defaults to the corpus statistics (exploration – hedge against sparse data). The optimal μ trades off between these extremes, and Zhai and Lafferty (2001) showed that μ2000 works well across many collections – a value that can be interpreted as saying “trust the document after you have seen about 2000 words of evidence.”

Latent Semantic Indexing

The term-document matrix is vast and sparse. A typical corpus with N=106 documents and vocabulary |V|=105 yields a matrix with 1011 entries, the overwhelming majority of which are zero. Worse, the raw term space suffers from two plagues:

  • Synonymy: different terms with the same meaning (“car” and “automobile”) have orthogonal representations, so a query for “car” will miss documents about “automobiles.”

  • Polysemy: the same term with different meanings (“bank”) conflates unrelated concepts into a single dimension.

Latent Semantic Indexing (LSI), introduced by Deerwester et al. [7], addresses both problems by projecting the term-document matrix onto a low-dimensional subspace using the truncated singular value decomposition (SVD).

Let 𝐀|V|×N be the TF-IDF-weighted term-document matrix. The rank-k truncated SVD is: (SVD)𝐀𝐀k=𝐔k𝚺k𝐕k, where 𝐔k|V|×k contains the top k left singular vectors (a basis for the “topic” space), 𝚺kk×k is diagonal with the top k singular values, and 𝐕kN×k contains the top k right singular vectors.

Each document dj is now represented by the j-th row of 𝐕k𝚺k – a k-dimensional vector in the latent topic space. A query 𝒒 is projected into the same space via: (LSI Query)𝒒^=𝒒𝐔k𝚺k1.

Retrieval is performed by computing cosine similarity between the projected query and the projected documents.

LSI resolves the synonymy problem by projecting documents from the high-dimensional term space to a low-dimensional latent topic space. In the original space, “car” and “automobile” are orthogonal, so documents using different synonyms appear distant. After SVD projection, semantically related documents cluster together in the topic space, enabling retrieval across synonym boundaries.

Theorem 2 (LSI as Optimal Low-Rank Approximation).

The rank-k truncated SVD 𝐀k is the optimal rank-k approximation to 𝐀 in both the Frobenius norm and the operator (spectral) norm: (Eckart Young)𝐀k=arg minrank(𝐁)k𝐀𝐁F, and 𝐀𝐀kF2=i=k+1min(|V|,N)σi2, where σi are the singular values of 𝐀 in decreasing order (Eckart–Young–Mirsky theorem).

Remark 6.

LSI was a conceptual breakthrough: it showed that retrieval could benefit from dimensionality reduction, and that the “noise” in the term-document matrix (due to synonymy and polysemy) could be filtered by discarding small singular values. However, LSI has significant practical limitations: the SVD is expensive to compute for large corpora (O(|V|Nk) for the top k components), updating the decomposition when documents are added is non-trivial, and the latent dimensions lack interpretability. These limitations motivated the development of probabilistic topic models.

Latent Dirichlet Allocation

Where LSI finds latent topics via matrix factorisation, Latent Dirichlet Allocation (LDA) discovers them via probabilistic generative modelling [8]. LDA posits that documents are generated by the following process:

  1. For each topic k{1,,K}, draw a distribution over words: 𝝓kDir(𝜷).

  2. For each document d: enumerate

  3. Draw a distribution over topics: 𝜽dDir(𝜶).

  4. For each word position n in document d: enumerate

  5. Draw a topic assignment: zd,nCategorical(𝜽d).

  6. Draw the word: wd,nCategorical(𝝓zd,n). enumerate enumerate

Definition 5 (Latent Dirichlet Allocation).

LDA is a generative probabilistic model over a corpus of documents. The joint distribution over observed words 𝒘 and latent variables (topic proportions 𝜽d and topic assignments 𝒛d) for a single document is: (LDA Joint)p(𝒘d,𝒛d,𝜽d|𝜶,𝜷)=p(𝜽d|𝜶)n=1Ndp(zd,n|𝜽d)p(wd,n|zd,n,𝝓). The marginal likelihood (evidence) is obtained by integrating over 𝜽d and summing over 𝒛d: (LDA Evidence)p(𝒘d|𝜶,𝜷)=p(𝜽d|𝜶)n=1Ndzd,n=1Kp(zd,n|𝜽d)p(wd,n|zd,n,𝝓)d𝜽d. This integral is intractable; inference requires variational methods or Markov chain Monte Carlo.

For retrieval, LDA provides a principled way to represent documents as probability distributions over topics. The KL-divergence (or Jensen–Shannon divergence) between topic distributions serves as a similarity measure that captures thematic overlap regardless of lexical overlap: (LDA Retrieval)sLDA(q,d)=𝖣KL(𝜽q𝜽d)=k=1Kθq,klogθq,kθd,k.

Remark 7.

LDA represents a philosophical shift from LSI. Where LSI finds topics by optimising a matrix approximation criterion (minimise reconstruction error), LDA finds topics by fitting a generative model (maximise the probability of the observed data). The generative perspective is crucial: it means that LDA's topics are not just mathematical artefacts but interpretable probability distributions over words. This interpretability – the ability to examine a topic and see that it is “about” medicine, or politics, or cuisine – is one of LDA's enduring contributions.

LDA also reveals a deep connection between generative modelling and retrieval that foreshadows the central theme of this chapter. In LDA, each document is “explained” by a generative story: a mixture of topics, each of which generates words. Retrieval is then the inverse of generation – given the observed words (the query), infer the latent topics, and find documents with similar topic distributions. This pattern – train a generative model, then use its learned representations for retrieval – will recur throughout this chapter at increasing levels of sophistication, from topic models to variational autoencoders to autoregressive language models that generate document identifiers directly.

Proposition 3 (LDA Posterior Intractability).

The posterior distribution p(𝜽d,𝒛d|𝒘d,𝜶,𝜷) in LDA is intractable to compute exactly. Specifically, the normalising constant (evidence) p(𝒘d|𝜶,𝜷) requires summing over KNd possible topic assignments, which is exponential in document length.

Proof.

The evidence is: p(𝒘d|𝜶,𝜷)=𝒛d{1,,K}Ndp(𝜽d|𝜶)n=1Ndp(zd,n|𝜽d)p(wd,n|zd,n,𝝓)d𝜽d. The sum over 𝒛d has KNd terms (each word can be assigned to any of K topics), and the integral over 𝜽d does not factorise because the topic proportions couple all word positions. Both variational inference (which approximates the posterior with a factored distribution) and collapsed Gibbs sampling (which integrates out 𝜽d and samples 𝒛d) are used in practice.

Evaluation Metrics for Information Retrieval

A retrieval system is only as good as our ability to measure its quality. The field of information retrieval has developed a rich vocabulary of evaluation metrics, each capturing a different aspect of retrieval quality. We present the major metrics here, as they will be used throughout the chapter.

Let π=(dπ(1),,dπ(N)) be a ranked list of documents produced by a retrieval system for a given query, and let rel(d){0,1} (or {0,1,2,} for graded relevance) denote the relevance of document d.

Definition 6 (Precision and Recall at k).

(Precision AT K)P@k=1ki=1krel(dπ(i)),R@k=i=1krel(dπ(i))d𝒞rel(d). Precision at k measures the fraction of retrieved documents (in the top k) that are relevant. Recall at k measures the fraction of all relevant documents that appear in the top k.

Definition 7 (Average Precision and Mean Average Precision).

The average precision (AP) for a single query is: (AP)AP=1|{d:rel(d)=1}|k=1NP@krel(dπ(k)). AP rewards systems that place relevant documents at the top of the ranked list. The mean average precision (MAP) averages AP over a set of queries: MAP=1|𝒬|q𝒬AP(q).

Definition 8 (Mean Reciprocal Rank).

The reciprocal rank (RR) is the reciprocal of the rank of the first relevant document: (MRR)RR=1min{k:rel(dπ(k))=1}. The mean reciprocal rank (MRR) averages over queries.

Definition 9 (Discounted Cumulative Gain and nDCG).

For graded relevance judgments rel(d){0,1,2,}, the discounted cumulative gain at position k is [3]: (DCG)DCG@k=i=1k2rel(dπ(i))1log2(i+1). The logarithmic discount penalises relevant documents that appear deep in the ranked list. The normalised DCG is: (NDCG)nDCG@k=DCG@kIDCG@k, where IDCG@k is the DCG of the ideal ranking (documents sorted by decreasing relevance). Thus nDCG[0,1].

Example 4.

Suppose a query has 5 relevant documents with graded relevance {3,2,3,1,2}, and a retrieval system returns them in the order with relevance grades [3,0,2,1,0] for positions 1–5. Then: DCG@5=231log22+201log23+221log24+211log25+201log26=7+0+1.5+0.43+0=8.93. The ideal ordering [3,3,2,2,1] gives IDCG@5=7+4.42+1.5+1.29+0.39=14.60 (the fifth ideal term is 1/log26=0.39). Hence nDCG@5=8.93/14.60=0.612.

Inverted Indices: The Data Structure of Retrieval

All the scoring functions discussed above – TF-IDF, BM25, query likelihood – share a common computational pattern: they sum contributions from query terms that appear in a document. The naive approach – iterating over all N documents for each query – is prohibitively expensive for web-scale corpora. The solution is the inverted index, the fundamental data structure of information retrieval.

Definition 10 (Inverted Index).

An inverted index maps each term w in the vocabulary to a posting list – an ordered sequence of (docID,payload) pairs for every document containing w: (Inverted Index):w[(d1,payload1),(d2,payload2),], where the payload typically includes the term frequency fw,d and possibly term positions. Posting lists are sorted by docID to enable efficient intersection and union operations.

Algorithm 1 (BM25 Retrieval with Inverted Index).

  1. Input: Query q={w1,,w|q|}, inverted index , parameter k
  2. Output: Top-k documents ranked by BM25 score
  3. Initialise score accumulator: scores[]0
  4. for each query term wiq
  5. Compute idf(wi) using (BM25 IDF)
  6. Retrieve posting list Li(wi)
  7. for each (d,fwi,d)Li
  8. tf_componentfwi,d(k1+1)fwi,d+k1(1b+bdl(d)/avgdl)
  9. scores[d]+=idf(wi)tf_component
  10. return top-k entries from scores by value

The efficiency of the inverted index comes from a simple observation: most documents do not contain most query terms. For a query with m terms, only documents that appear in at least one posting list are scored. If the average posting list length is L, the total work is O(mL+klogk) – typically far less than O(N) for sparse queries on large corpora.

The structure of an inverted index. Each vocabulary term maps to a posting list containing document identifiers and term frequencies. Posting lists are sorted by document ID to enable efficient intersection (for Boolean AND queries) and union (for Boolean OR or ranked retrieval). The index transforms retrieval from a scan over all documents to a traversal of only the posting lists for query terms.

Comparison of Classical Methods

MethodRepresentationQuery TimeHandles Synonymy?Interpretable?
TF-IDF [5]Sparse, |V|-dimO(mL)NoYes
BM25 [6]Sparse, |V|-dimO(mL)NoYes
LSI [7]Dense, k-dimO(Nk)YesNo
LDA [8]Dense, K-dimO(NK)YesYes
Comparison of classical information retrieval methods. Complexity is stated for scoring a single query against a corpus of N documents with vocabulary size |V|. k denotes the number of latent dimensions (LSI) or topics (LDA); L denotes the average posting list length.

Table 1 summarises the strengths and weaknesses of the classical methods. Sparse methods (TF-IDF, BM25) are fast and interpretable but cannot handle synonym mismatch. Dense methods (LSI, LDA) address synonymy through dimensionality reduction but sacrifice the efficiency of inverted indices – computing similarity in a dense space requires either scanning all documents or building specialised approximate nearest-neighbour indices, which we discuss in later sections.

The resolution of this tension – achieving the semantic power of dense representations with the efficiency of sparse retrieval – is one of the driving forces behind the dense retrieval revolution and the generative retrieval models that are the ultimate subject of this chapter.

It is worth noting that the methods surveyed so far represent only the scoring component of a retrieval system. The broader discipline of learning to rank [43] studies how to learn the scoring function from data, combining multiple signals – BM25 scores, PageRank, click-through data, document freshness, query-document feature vectors – into a single relevance prediction. Learning-to-rank methods (pointwise, pairwise, and listwise) laid the intellectual groundwork for the neural ranking models that would follow, establishing the principle that retrieval scoring should be learned, not hand-designed.

Caution.

BM25 Is Not Dead. Despite the rise of neural retrieval models, BM25 remains a remarkably strong baseline. In many TREC benchmarks and industrial settings, BM25 with careful tuning (k11.2, b0.75) is competitive with or superior to naive neural approaches. The lesson: always compare against BM25 before claiming that a neural retrieval model represents an advance. A neural model that cannot beat a well-tuned BM25 is not ready for deployment.

Exercise 9.

Implement TF-IDF from scratch.

  1. Build an inverted index for a small corpus of 10 documents (use any text of your choice).

  2. Implement the TF-IDF scoring function of Definition 3.

  3. Rank the documents for three queries and verify that the results are sensible.

  4. Now implement BM25 (Definition 4) with k1=1.2 and b=0.75. Compare the rankings to TF-IDF. On which queries do they differ, and why?

Exercise 10.

Explore BM25's parameter space.

  1. Plot the BM25 TF component as a function of fw,d for k1{0.5,1.2,2.0,5.0} with b=0.75 and dl(d)=avgdl.

  2. For a fixed query term with df(w)=100 in a corpus of N=106, compute the BM25 score for a document where fw,d=1 versus fw,d=100. What is the ratio of scores? How does this compare to the ratio under raw TF-IDF?

  3. Prove that BM25's IDF formula ((BM25 IDF)) can assign negative IDF to very common terms (those appearing in more than N/2 documents). Is this desirable? Propose a modification that prevents negative IDF.

Exercise 11.

Implement LSI on the “20 Newsgroups” dataset.

  1. Construct the TF-IDF term-document matrix.

  2. Compute the truncated SVD for k{10,50,100,300}.

  3. For each value of k, evaluate retrieval quality using MAP on a held-out set of queries. Plot MAP versus k.

  4. Examine the top 10 terms for the first five latent dimensions. Can you assign interpretable “topic” labels?

  5. Compare retrieval quality to BM25. Under what conditions does LSI outperform BM25?

Exercise 12.

Train an LDA model on a corpus of your choice with K=20 topics.

  1. Display the top 10 words for each topic. Assign interpretable labels to at least 10 topics.

  2. Use the inferred topic distributions 𝜽d to retrieve documents for a query. Compare with BM25.

  3. Compute the perplexity of the held-out documents as a function of K. Does lower perplexity correlate with better retrieval quality?

Exercise 13.

The choice of evaluation metric can significantly affect system rankings.

  1. Construct a ranked list of 10 documents where MAP ranks system A above system B, but nDCG@10 ranks system B above system A.

  2. Prove that for binary relevance (rel{0,1}), nDCG@k reduces to a specific function of precision values at each rank.

  3. Argue that MRR is appropriate when the user wants exactly one answer (e.g., factoid question answering) but inappropriate when multiple relevant documents exist.

We have now laid the three pillars upon which the rest of this chapter stands. The philosophical framework of The Philosophy of Retrieval – What Does It Mean to Remember? established that retrieval is not mere lookup but reconstruction of meaning. The neuroscience of The Neuroscience of Memory and Retrieval showed that the brain implements retrieval through content-addressable memory, pattern completion, and generative reconstruction – mechanisms that neural networks are now learning to emulate. The formal foundations of Formal Foundations of Information Retrieval gave us the mathematical vocabulary – scoring functions, evaluation metrics, indexing structures – that we need to reason precisely about retrieval quality.

In the sections that follow, we will see how deep learning transforms every component of the retrieval pipeline. We begin with the dense retrieval revolution: the replacement of sparse bag-of-words representations with learned dense embeddings that capture semantic meaning. From there, we will progress to the most radical idea in modern retrieval: generative retrieval, where the index, the scoring function, and even the documents themselves are absorbed into the parameters of a single neural network. The journey from TF-IDF to generative retrieval is, in a sense, the journey from Aristotle's associations to Plato's anamnesis – from matching surface patterns to recovering meaning from compressed memory.

Dense Retrieval Revolution

The previous section laid the mathematical foundations of information retrieval in the language of probability, relevance, and term statistics. Those foundations are elegant, but they rest on an assumption so deeply embedded that it is easy to overlook: that documents and queries are best represented by the words they contain. The bag-of-words assumption – that the meaning of a text is captured by the multiset of its tokens – served the field for half a century. It powered TF-IDF, BM25, and the probabilistic models that built the modern web. But it harbours a fatal weakness: it cannot recognise that “automobile” and “car” refer to the same concept, that “heart attack” and “myocardial infarction” describe the same event, that a question about “the capital of France” should match a document that says “Paris is where the French government sits” even though the two texts share almost no words.

This is the vocabulary mismatch problem, and it is not a minor annoyance. Studies have repeatedly shown that users and authors use different words for the same concepts roughly 70–80% of the time [44]. Techniques like query expansion, stemming, and pseudo-relevance feedback provide partial remedies, but they are fundamentally patches on a representational framework that was never designed to capture meaning.

The dense retrieval revolution replaces this framework entirely. Instead of representing documents as sparse vectors over a vocabulary of hundreds of thousands of tokens, dense retrieval maps both queries and documents into a shared continuous vector space of a few hundred dimensions, where semantic similarity is captured by geometric proximity. A query about automobiles and a document about cars end up as nearby points – not because they share tokens, but because a neural network has learned that they share meaning.

The shift from sparse to dense is not merely a change of technique. It is a change of philosophy. Sparse retrieval asks: “Does this document contain the right words?” Dense retrieval asks: “Does this document mean the right thing?” The former is a syntactic question; the latter is a semantic one. And as we shall see, the answer to the semantic question requires us to learn representations – which in turn requires data, computation, and the entire apparatus of modern deep learning.

From Sparse to Dense: The Paradigm Shift

Let us make the contrast precise. In sparse retrieval, a document d with vocabulary V is represented as a vector 𝒅sparse|V| where most entries are zero. For BM25, the non-zero entries are the BM25 term weights. The dimensionality is enormous – typically |V|105 – but the vectors are extremely sparse, with only a few hundred non-zero entries per document. This sparsity enables efficient inverted-index lookups, but it means that two documents can have zero overlap in their representations even when they are semantically identical.

In dense retrieval, we learn an encoder f𝜽 that maps a text x (query or document) to a dense vector 𝒙=f𝜽(x)d where d is typically 128–1024. Every dimension carries information; there are no structural zeros. Retrieval reduces to finding the documents whose dense vectors are closest to the query vector: (Dense Retrieval)d=arg maxd𝒟sim(f𝜽(q),f𝜽(d)), where sim is typically the inner product or cosine similarity.

Definition 11 (Dense Retrieval Problem).

Given a query encoder f𝜽Q:𝒬d, a document encoder f𝜽D:𝒟d, a corpus 𝒞={d1,,dN}, and a similarity function s:d×d, the dense retrieval problem is to return, for each query q, the set k(q)=top-kd𝒞s(f𝜽Q(q),f𝜽D(d)). When f𝜽Q=f𝜽D we call the architecture a single-encoder (or shared-encoder) model. When they are distinct, we call it a dual-encoder (or bi-encoder) model.

Historical Note.

The idea of mapping documents to dense vectors long predates the neural era. Latent Semantic Indexing (LSI), introduced by Deerwester et al. in 1990, used singular value decomposition to project the term-document matrix into a low-dimensional space. LSI could capture some synonymy – “car” and “automobile” might project to similar vectors – but it operated on the same bag-of-words representations and could not model compositionality or word order. Latent Dirichlet Allocation (LDA) offered a probabilistic alternative in 2003 but suffered from similar limitations. The true revolution came when deep learning provided encoders – first with word2vec and GloVe, then with BERT and its descendants – that could map sequences of tokens to dense vectors that captured syntactic and semantic structure.

DPR: Dense Passage Retrieval

The work that crystallised the dense retrieval paradigm for open-domain question answering was Dense Passage Retrieval (DPR) [45], published by Karpukhin et al. in 2020. DPR demonstrated that a simple dual-encoder architecture, trained with the right contrastive objective, could outperform BM25 on multiple open-domain QA benchmarks – a result that many in the community found surprising, given the decades of engineering that had gone into sparse retrieval systems.

Architecture.

DPR uses two independent BERT encoders: one for queries (BERTQ) and one for passages (BERTP). Each encoder takes a text as input and produces a d-dimensional vector by extracting the [CLS] token representation from the final layer: (DPR Query)𝒒=BERTQ(q)[𝙲𝙻𝚂]d,𝒑=BERTP(p)[𝙲𝙻𝚂]d. The similarity between a query and a passage is the inner product: (DPR SIM)s(q,p)=𝒒,𝒑=𝒒𝒑.

Training objective.

Given a query qi with a positive passage pi+ and a set of negative passages {pi,1,,pi,m}, DPR minimises the negative log-likelihood of the positive passage: (DPR LOSS)DPR=logexp(𝒒i,𝒑i+)exp(𝒒i,𝒑i+)+j=1mexp(𝒒i,𝒑i,j). This is an instance of the InfoNCE loss [40]. The critical engineering insight in DPR is the use of in-batch negatives: within a mini-batch of B query–passage pairs, the positive passage for query qi serves as a negative for all other queries qj (ji), yielding B1 negatives per query at no additional computational cost.

Hard negative mining.

Not all negatives are equally informative. Random negatives are easily distinguished from positives and provide weak gradient signal – their similarity to the query is so low that the softmax in (DPR LOSS) assigns them negligible weight, producing near-zero gradients. DPR addresses this by mining hard negatives – passages that are similar to the query according to BM25 but are not the gold positive. These negatives force the model to learn fine-grained distinctions that go beyond lexical overlap.

Concretely, for each training query, DPR retrieves the top-100 BM25 results and selects passages that do not contain the answer string as hard negatives. The original DPR paper found that using one BM25 hard negative per query, combined with in-batch negatives, yielded the best results. Adding a gold passage from a different query as a “gold negative” provided a further small improvement.

Algorithm 2 (DPR Training with In-Batch Negatives).

  1. Input: Training set {(qi,pi+,pi,1,,pi,h)}i=1N, batch size B, learning rate η, epochs T
  2. Output: Trained encoders BERTQ, BERTP
  3. for t=1 to T
  4. for each mini-batch ={(qi,pi+,pi,1,,pi,h)}i=1B
  5. for i=1 to B
  6. 𝒒iBERTQ(qi)[𝙲𝙻𝚂] Encode query
  7. 𝒑i+BERTP(pi+)[𝙲𝙻𝚂] Encode positive passage
  8. for j=1 to h
  9. 𝒑i,jBERTP(pi,j)[𝙲𝙻𝚂] Encode hard negatives
  10. 𝒩i{pj+:ji}{pi,1,,pi,h} In-batch + hard negs
  11. for i=1 to B
  12. ilogexp(𝒒i,𝒑i+)exp(𝒒i,𝒑i+)+𝒑𝒩iexp(𝒒i,𝒑)
  13. 1Bi=1Bi
  14. Update 𝜽 with gradient 𝜽 using Adam with learning rate η

ColBERT: Late Interaction for Token-Level Matching

The dual-encoder architecture of DPR is efficient – query and document encodings are computed independently and can be cached – but it compresses the entire semantics of a passage into a single vector. This is a severe bottleneck. A passage about “the bank of the river” and a passage about “the bank approved the loan” might end up with similar single-vector representations because the word “bank” dominates both, even though the passages are about entirely different topics.

ColBERT (Contextualised Late Interaction over BERT) [46] addresses this by retaining token-level representations and deferring the matching computation to query time. Instead of a single vector per document, ColBERT produces a matrix: (Colbert Query)𝐄q=BERTQ(q)nq×d,𝐄d=BERTD(d)nd×d, where nq and nd are the token lengths of the query and document, respectively. The similarity is computed via the MaxSim operator: (Maxsim)sColBERT(q,d)=i=1nqmaxj{1,,nd}𝒒i,𝒅j, where 𝒒i is the i-th row of 𝐄q and 𝒅j is the j-th row of 𝐄d. Each query token finds its best-matching document token, and these maximum similarities are summed.

The MaxSim operator has an intuitive interpretation: it performs a soft word-by-word alignment between query and document. If the query is “When was the Eiffel Tower built?”, the token “Eiffel” will align with the document token “Eiffel” (or “tower” or “Tour”), “built” will align with “constructed” or “completed”, and “when” will align with a date or year token. Each alignment contributes its similarity to the total score, so documents that match on more query tokens receive higher scores. This is far more expressive than a single inner product, which cannot distinguish which aspects of the query are matched.

Remark 8.

The MaxSim operator can be viewed as a soft alignment between query and document tokens. Unlike cross-attention in a cross-encoder, the alignment is computed without any learnable interaction parameters – it is purely geometric. This makes ColBERT a late interaction model: the encoders operate independently, but the final scoring involves token-level interaction.

Proposition 4 (Expressiveness of Late Interaction).

Let DE denote the family of scoring functions realisable by dual-encoder models (single-vector inner product) and LI denote the family realisable by late-interaction models with MaxSim. Then DELI.

Proof.

We show (i) inclusion and (ii) strict separation.

Inclusion. Any dual-encoder score s(q,d)=𝒒,𝒅 can be expressed in the ColBERT framework by setting nq=nd=1 (single-token representations). Then sColBERT=maxj{1}𝒒1,𝒅1=𝒒,𝒅. Hence DELI.

Strict separation. Consider two documents dA and dB with identical mean token embeddings: 1ndj𝒅jA=1ndj𝒅jB, but different token-level distributions. A dual-encoder that pools via mean pooling cannot distinguish them: 𝒒,𝒅A=𝒒,𝒅B. However, ColBERT's MaxSim can assign different scores by aligning individual query tokens to different document tokens. Concretely, let d=2, nq=1 with 𝒒1=(1,0), nd=2 with 𝒅1A=(1,0), 𝒅2A=(0,1) and 𝒅1B=(0.5,0.5), 𝒅2B=(0.5,0.5). Both documents have the same mean (0.5,0.5), so the dual-encoder gives score 0.5 to both. But MaxSim gives max(1,0)=1 for dA and max(0.5,0.5)=0.5 for dB. Thus DELI.

Contrastive Learning for Retrieval

The DPR loss in (DPR LOSS) is a specific instance of the InfoNCE objective. Let us state the general form and analyse the role of temperature.

Given an anchor 𝒒, a positive 𝒑+, and K negatives {𝒑1,,𝒑K}, the InfoNCE loss with temperature τ>0 is: (Infonce)InfoNCE=logexp(𝒒,𝒑+/τ)exp(𝒒,𝒑+/τ)+k=1Kexp(𝒒,𝒑k/τ).

The temperature τ controls the sharpness of the softmax distribution over candidates. Small τ makes the distribution peaky, assigning nearly all probability to the most similar candidate and creating strong gradients for hard negatives. Large τ makes the distribution uniform, treating all negatives more equally.

Theorem 3 (Optimal Temperature for Contrastive Retrieval).

Consider the InfoNCE loss in (Infonce) with K negatives drawn i.i.d. from a distribution p over unit-norm embeddings. Let μ+=𝔼[𝒒,𝒑+] denote the expected positive similarity and μ=𝔼[𝒒,𝒑] the expected negative similarity, with σ the standard deviation of negative similarities. In the limit of large K, the temperature that minimises the variance of the gradient estimator satisfies (Optimal Temperature)τ=σ2(1+𝒪(1K)).

Proof.

Write the loss as =𝒒,𝒑+/τ+log[exp(𝒒,𝒑+/τ)+kexp(𝒒,𝒑k/τ)]. The gradient with respect to 𝒒 involves the softmax weights wk=exp(𝒒,𝒑k/τ)/Z where Z is the partition function. The variance of 𝒒 is dominated by the variance of kwk𝒑k.

For large K, the log-sum-exp concentrates around μ/τ+logK+(σ)2/(2τ2) by a standard Laplace approximation. The effective number of negatives contributing to the gradient is approximately Keff=Kexp((σ)2/(2τ2)). The gradient variance scales as 1/Keff. Simultaneously, the gradient magnitude scales as 1/τ. The signal-to-noise ratio of the gradient is therefore SNR(τ)1/τ1/Keff=Kτexp((σ)24τ2). Differentiating logSNR(τ) with respect to τ and setting the derivative to zero: ddτ[logτ(σ)24τ2]=01τ+(σ)22τ3=0τ=σ2. The correction term 𝒪(1/K) arises from finite-sample effects in the Laplace approximation.

Remark 9.

In practice, the temperature is often treated as a learnable parameter (as in CLIP) or tuned on a validation set. The theorem provides guidance: τ should be proportional to the spread of negative similarities, not set arbitrarily.

SPLADE: Learned Sparse Representations

Dense retrieval captures semantics but sacrifices the efficiency of inverted indices. Sparse retrieval is efficient but misses semantics. SPLADE (SParse Lexical AnD Expansion model) [47] bridges the two worlds by using a neural network to produce sparse representations – vectors in |V| with mostly zero entries – but where the non-zero entries are learned rather than derived from term frequency statistics.

The key idea is to use a BERT-based masked language model head to predict a distribution over the entire vocabulary for each token position, then aggregate across positions: (Splade)wj(x)=i=1nlog(1+ReLU(𝐖MLM𝒉i+𝒃)j), where 𝒉i is the contextual representation of the i-th token, 𝐖MLM is the MLM projection matrix, and j indexes the vocabulary. The log(1+ReLU()) transformation ensures non-negative weights with a saturating growth. SPLADE adds a regularisation term to encourage sparsity: (Splade REG)SPLADE=InfoNCE+λq𝒘(q)1+λd𝒘(d)1.

Because the resulting representations are sparse and non-negative, they can be stored and searched using standard inverted indices – the same infrastructure that powers BM25. Yet SPLADE performs term expansion: a document about “heart attack” will have non-zero weights for “cardiac”, “myocardial”, and “infarction” even if those words never appear in the text.

Example 5.

Consider the query “What causes high blood pressure?” A BM25 system must match on the exact terms “high”, “blood”, and “pressure”. A SPLADE encoder, having seen many medical texts during training, produces a sparse vector with non-zero weights for “hypertension” (weight 2.8), “blood” (weight 2.1), “pressure” (weight 1.9), “cardiovascular” (weight 1.4), “sodium” (weight 0.9), “arterial” (weight 0.8), and dozens of other related terms. This expansion vector can be looked up in a standard inverted index, bridging the vocabulary gap without the computational cost of dense nearest-neighbour search.

The SPLADE family has evolved through several versions. SPLADE v2 introduced document-side distillation from a cross-encoder, which significantly improved the quality of learned term weights. SPLADE++ further explored the design space of self-distillation and ensemble distillation, achieving results competitive with dense retrieval on the BEIR benchmark while retaining the efficiency of inverted-index retrieval.

Remark 10.

SPLADE occupies a fascinating position in the retrieval landscape: it is technically a sparse method (its representations live in |V| with mostly zero entries), but its representations are semantically dense (the non-zero entries capture meaning far beyond the literal text). This challenges the neat sparse/dense dichotomy and suggests that the fundamental distinction is not about the shape of the vector, but about whether the representation is learned or hand-crafted.

Hybrid Retrieval

In practice, the best retrieval systems combine sparse and dense signals. The intuition is straightforward: sparse retrieval excels at exact lexical matching (entity names, rare terms, identifiers), while dense retrieval excels at semantic matching (paraphrases, synonyms, implicit relevance). The two failure modes are largely complementary.

The simplest hybrid approach is a linear interpolation of scores: (Hybrid Score)shybrid(q,d)=αssparse(q,d)+(1α)sdense(q,d), where α[0,1] is a mixing weight. Because the two score distributions may have different scales, it is common to normalise each score to [0,1] before interpolation, for instance via min-max normalisation within the retrieved set: (Hybrid NORM)s^(q,d)=s(q,d)minds(q,d)maxds(q,d)minds(q,d).

A more principled approach is Reciprocal Rank Fusion (RRF), which combines ranked lists rather than scores: (RRF)sRRF(q,d)=r1k+rankr(d), where is the set of retrieval systems and k is a smoothing constant (typically k=60).

RRF has the advantage of being score-agnostic: it requires only ranked lists, not calibrated scores, making it robust to the different score distributions produced by sparse and dense systems. Empirically, RRF with k=60 is remarkably difficult to beat with more sophisticated learned combination methods, a fact that has surprised many researchers.

Multi-stage retrieval.

Production search systems often use a multi-stage pipeline rather than a single fusion step:

  1. First stage (recall). Run BM25 and/or a dual-encoder to retrieve a large candidate set (1000 documents). The goal is high recall, not precision.

  2. Second stage (reranking). Apply a cross-encoder reranker to score each candidate in the context of the query. The cross-encoder sees the concatenation [q;d] and can model fine-grained query-document interactions.

  3. Third stage (optional). Apply a generative model to rewrite or summarise the top candidates, further improving relevance.

This pipeline exploits the complementary strengths of each approach: fast but coarse first-stage retrieval followed by slow but precise reranking.

Caution.

A common pitfall in hybrid retrieval is score incompatibility: BM25 scores are unbounded and depend on document length, while dense retrieval scores (inner products or cosines) are bounded. Naive interpolation without normalisation can cause one system to dominate the other regardless of α. Always normalise scores before combining them, or use rank-based fusion methods like RRF.

Architecture Comparison

The three dominant neural retrieval architectures – dual-encoder, cross-encoder, and late interaction – represent different points on the efficiency-effectiveness trade-off.

Dual-encoder.

The dual-encoder computes query and document representations independently. Document encodings can be precomputed and cached, so online latency scales only with the ANN search cost, not with the number of documents. However, the single-vector bottleneck limits the model's ability to capture fine-grained query-document interactions.

Cross-encoder.

The cross-encoder processes the concatenation [q;d] through a single transformer, allowing full cross-attention between query and document tokens. This is the most expressive architecture – the model can learn arbitrary interactions between query and document words. But it is also the slowest: each query-document pair requires a separate forward pass, making it impractical as a first-stage retriever for large corpora. Cross-encoders are typically used as rerankers for a small set of candidates retrieved by a dual-encoder or BM25.

Late interaction.

ColBERT's late interaction occupies the middle ground: encodings are independent (enabling precomputation), but scoring involves token-level matching (enabling expressiveness). The storage cost is higher than a dual-encoder (ndd floats per document instead of d), but ColBERTv2 addresses this with residual compression, reducing storage to approximately 2 bytes per token.

fig:retrieval-architectures illustrates the key structural differences.

Three neural retrieval architectures. The dual-encoder compresses each text to a single vector; the cross-encoder processes the concatenation jointly; late interaction retains token-level representations and computes fine-grained matching at query time.
Sparse vs. dense representations. Sparse vectors live in vocabulary space with mostly zero entries and rely on exact term matching. Dense vectors live in a learned embedding space where every dimension carries semantic information.
MethodTop-5Top-20Top-100
BM2543.862.978.3
DPR68.380.186.1
DPR + BM25 hard negs72.182.687.3
ColBERT73.283.988.7
SPLADE v272.883.588.1
Hybrid (BM25 + DPR)74.184.389.0
Retrieval accuracy on Natural Questions (open-domain, test set). Top-k accuracy measures whether the correct answer passage appears in the top-k retrieved results.

Exercises

Exercise 14.

Consider a DPR model trained with batch size B=128 and h=1 hard negative per query. How many total negatives does each query see per training step? If we double the batch size to B=256, by what factor does the number of negatives increase? Discuss why larger batch sizes tend to improve dense retrieval performance.

Exercise 15.

Analyse the computational complexity of ColBERT's MaxSim scoring. Given a query of length nq and a document of length nd with embedding dimension d, what is the time complexity of computing sColBERT(q,d)? Compare this to the cost of a single inner product in a dual-encoder. How does ColBERTv2's token compression reduce this cost?

Exercise 16.

Implement the InfoNCE loss ((Infonce)) in PyTorch. Train a simple dual-encoder on a synthetic dataset of 10,000 query–passage pairs (embed with random features for simplicity). Sweep the temperature τ over {0.01,0.05,0.1,0.5,1.0,5.0} and plot (a) the final loss, (b) the retrieval accuracy (top-5), and (c) the gradient norm as functions of τ. Does the optimal τ align with Theorem 3?

Exercise 17.

A hybrid retrieval system uses the interpolation in (Hybrid Score). Derive the value of α that maximises NDCG@10 on a validation set, assuming you have access to relevance labels. Is this a convex optimisation problem? What happens at the boundaries α=0 and α=1?

Approximate Nearest Neighbour Search

Dense retrieval transforms the problem of finding relevant documents into the problem of finding nearby vectors. At training time, we learn to map semantically similar texts to nearby points in d. At inference time, we must find, among billions of document vectors, the k vectors closest to the query vector. This is the nearest neighbour search problem, and in its exact form it is one of the oldest and most studied problems in computational geometry.

Unfortunately, exact nearest neighbour search in high dimensions is intractable at the scales required by modern retrieval. This is a consequence of the curse of dimensionality: in spaces with more than about 10–20 dimensions, all known exact search algorithms degrade to brute-force linear scan. The intuition is that in high dimensions, distances become increasingly uniform – the ratio between the nearest and farthest neighbour approaches 1 – and geometric partitioning structures (trees, grids, Voronoi cells) become ineffective because query balls intersect exponentially many cells.

For a corpus of N=109 vectors in d=768 dimensions, a brute-force scan requires Nd floating-point multiplications per query – roughly 7.7×1011 operations, or about 100 milliseconds on a modern GPU. For an interactive search engine handling thousands of queries per second, this is unacceptable.

More formally, the difficulty is captured by the following observation. Let 𝒙1,,𝒙N be N points drawn uniformly from [0,1]d. For a query 𝒒, let NN(𝒒) be the nearest neighbour and FN(𝒒) the farthest neighbour. Then for large d: (Curse OF DIM)𝔼[dist(𝒒,FN(𝒒))]𝔼[dist(𝒒,NN(𝒒))]1as d. When all distances are approximately equal, the very concept of “nearest neighbour” becomes ill-defined, and no partitioning scheme can prune the search space effectively.

The solution is to accept approximate answers. Approximate nearest neighbour (ANN) methods trade a small amount of accuracy (typically 95–99% of exact recall) for orders-of-magnitude speedups, reducing query latency from seconds to microseconds. The key insight is that for retrieval applications, we do not need the exact nearest neighbour – we need a set of candidates that is good enough to contain the relevant documents, which a subsequent reranking stage can then sort precisely.

Locality-Sensitive Hashing

Locality-sensitive hashing (LSH) was among the first theoretically grounded approaches to ANN search. The key idea is to design hash functions that map similar items to the same hash bucket with high probability and dissimilar items to different buckets.

Definition 12 (Locality-Sensitive Hash Family).

A family ={h:d{0,1}} is called (r1,r2,p1,p2)-sensitive for a distance function dist if for any 𝒙,𝒚d:

  1. If dist(𝒙,𝒚)r1, then Pr[h(𝒙)=h(𝒚)]p1.

  2. If dist(𝒙,𝒚)r2, then Pr[h(𝒙)=h(𝒚)]p2.

The family is useful when r1<r2 and p1>p2.

For cosine similarity, the standard construction uses random hyperplane hashing. Each hash function is defined by a random vector 𝒓𝒩(0,𝐈d): (LSH Hyperplane)h𝒓(𝒙)={1if 𝒓𝒙0,0otherwise.

Lemma 1 (Collision Probability for Random Hyperplane LSH).

For the random hyperplane hash family, the collision probability is: (LSH Collision)Pr[h𝒓(𝒙)=h𝒓(𝒚)]=1θ(𝒙,𝒚)π, where θ(𝒙,𝒚)=arccos(𝒙,𝒚𝒙𝒚) is the angle between 𝒙 and 𝒚.

Proof.

The hash function h𝒓 partitions d into two half-spaces by the hyperplane {𝒛:𝒓𝒛=0}. Since 𝒓 is drawn from a spherically symmetric distribution, the hyperplane orientation is uniformly random. Two vectors 𝒙 and 𝒚 receive different hash values if and only if the random hyperplane separates them – i.e., the hyperplane normal 𝒓 falls in the double cone of directions between 𝒙 and 𝒚.

The fraction of random directions that separate 𝒙 and 𝒚 is exactly θ(𝒙,𝒚)/π, because the set of separating hyperplane normals forms a great circle arc of angular measure θ out of a total of π. Therefore: Pr[h𝒓(𝒙)h𝒓(𝒚)]=θ(𝒙,𝒚)πPr[h𝒓(𝒙)=h𝒓(𝒚)]=1θ(𝒙,𝒚)π.

A single random hyperplane provides only weak discrimination. If two vectors have angle θ=60°, the collision probability is 160/180=2/3 – better than chance, but not enough to build a reliable index. To amplify the gap between collision probabilities, we use AND-OR composition: concatenate b hash functions to form a band (AND amplification), then use L independent bands (OR amplification). Two items collide if they agree on all b hashes within at least one band.

The AND step makes the collision probability drop rapidly for dissimilar items (since all b hashes must agree), while the OR step ensures that similar items collide in at least one of the L bands. The overall collision probability for items at angle θ is: (LSH Amplified)P(b,L,θ)=1(1(1θπ)b)L.

Random hyperplane LSH. Three random hyperplanes (h1,h2,h3) partition the space. Similar points 𝒙 and 𝒚 (small angle θ) receive the same hash code, while the distant point 𝒛 is mapped to a different bucket.

Tree-Based Methods

KD-trees partition space by recursively splitting along coordinate axes. At each node, the dimension with the greatest spread is chosen, and the split is placed at the median value, yielding a balanced binary tree of depth 𝒪(logN). For query processing, the tree is traversed by following the branch that contains the query, then backtracking to check sibling branches that could contain closer neighbours.

In low dimensions (d20), KD-trees achieve query times of 𝒪(logN). In high dimensions, however, the backtracking becomes so frequent that performance degrades to 𝒪(N) – no better than brute force. Ball trees improve on KD-trees by using hyperspheres rather than axis-aligned splits, which better captures the geometry of clustered data, but they suffer from the same fundamental curse of dimensionality.

The failure of tree-based methods in high dimensions can be quantified precisely. For a KD-tree with N points in d, the expected number of cells visited during a nearest-neighbour query is: (Kdtree Cells)𝔼[cells visited]=Ω(N11/d), which for d=768 is essentially Ω(N) – brute force.

Remark 11.

Annoy (Approximate Nearest Neighbours Oh Yeah), used by Spotify for music recommendation, uses random-projection trees – a variant of KD-trees where the split direction is chosen randomly rather than along a coordinate axis. By building a forest of many such trees and taking the union of candidates, Annoy achieves reasonable recall in moderate dimensions (d256). The number of trees controls the accuracy-speed trade-off: more trees yield higher recall at the cost of more memory and slower queries.

Remark 12.

Despite their limitations in high dimensions, tree-based methods remain useful in two scenarios: (1) after dimensionality reduction (e.g., PCA to 32 dimensions), where the effective dimensionality is low enough for trees to work well; and (2) as a component of hybrid indices, where trees provide a coarse first-stage partition that is refined by other methods.

Product Quantization

Product Quantization (PQ) [48] takes a fundamentally different approach: rather than building search structures, it compresses the vectors themselves so that distance computation becomes fast.

The idea is to decompose each d-dimensional vector into M disjoint subvectors of dimension d/M, quantise each subvector independently using a codebook of K centroids, and represent the entire vector by M codebook indices. This reduces memory from d32 bits (for float32) to Mlog2K bits – a compression ratio of roughly 50× to 380× depending on M (for d=768, K=256: from 48× at M=64 to 384× at M=8).

Definition 13 (Product Quantization).

Let 𝒙d be decomposed into M subvectors: 𝒙=[𝒙1;𝒙2;;𝒙M] where 𝒙md/M. A product quantizer PQ assigns each subvector to its nearest centroid in a learned codebook 𝒞m={c1m,,cKm}: PQ(𝒙)=(arg mink𝒙1ck12,,arg mink𝒙MckM2). The approximate squared distance between a query 𝒒 and a database vector 𝒙 is: (PQ Distance)d^(𝒒,𝒙)2=m=1M𝒒mckm(𝒙)m2, where km(𝒙) is the centroid index assigned to 𝒙m.

Codebook learning.

The codebooks 𝒞1,,𝒞M are learned by running k-means independently in each subspace. Specifically, the database vectors are split into subvectors, and k-means with K clusters is run on each set of subvectors. The total training cost is 𝒪(MNKd/M)=𝒪(NKd), which is linear in the database size. The choice of M and K determines the trade-off between compression ratio and quantisation error. Typical values are M=864 and K=256 (so each index fits in one byte), giving PQ codes of 8–64 bytes per vector.

Asymmetric distance computation.

The key efficiency trick is asymmetric distance computation (ADC): we do not quantise the query. Instead, we precompute a lookup table of distances 𝒒mckm2 for all M subspaces and all K centroids – a table of size M×K. Then the distance to any database vector requires only M table lookups and additions, regardless of d. The lookup table computation costs 𝒪(MKd/M)=𝒪(Kd), which is amortised over all N database vectors. The total query cost is therefore 𝒪(Kd+NM), which for K=256, d=768, M=64 is roughly 2×105+64N – dominated by the 64N term, which is 64/7688% of the brute-force cost.

Product Quantization decomposes a vector into M subvectors, quantises each with an independent codebook of K centroids, and stores only the centroid indices. Distance computation uses precomputed lookup tables.

HNSW: Hierarchical Navigable Small World Graphs

Hierarchical Navigable Small World (HNSW) [49] is currently the most widely used ANN index, powering systems from Faiss to Pinecone to Weaviate. It combines two ideas: the navigable small world property of proximity graphs and a hierarchical structure inspired by skip lists.

Navigable small world graphs.

A navigable small world (NSW) graph connects each vector to a set of neighbours. Crucially, each node maintains both short-range links (to nearby vectors) and long-range links (to distant vectors). This combination enables greedy search – always moving to the neighbour closest to the query – to find near-optimal results in polylogarithmic time, analogous to the “six degrees of separation” phenomenon in social networks. The theoretical foundation is Kleinberg's result on navigable networks: if long-range links are distributed according to an inverse-power-law of distance, greedy routing finds near-optimal paths in 𝒪(log2N) steps.

Hierarchical structure.

HNSW organises the NSW graph into L layers, numbered 0 (bottom, containing all vectors) through L1 (top, containing very few vectors). Each vector is assigned a maximum layer ln(Uniform(0,1))mL where mL is a normalisation constant. This gives an exponentially decaying probability of appearing in higher layers – exactly like a skip list.

Search proceeds top-down: starting from the entry point at the top layer, greedy search finds the closest node in that layer, then descends to the next layer using that node as the starting point, and repeats. The upper layers provide long-range navigation, while the bottom layer provides fine-grained local search.

Algorithm 3 (HNSW Search).

  1. Input: Query 𝒒, entry point ep at layer L, number of neighbours k, candidate list size 𝑒𝑓
  2. Output: Approximate k-nearest neighbours 𝒲
  3. 𝒲{ep} Current best set
  4. for =L downto 1 Greedy search in upper layers
  5. 𝒲\CallSearchLayer𝒒,𝒲,1, Keep only 1 candidate
  6. 𝒲\CallSearchLayer𝒒,𝒲,𝑒𝑓,0 Beam search in bottom layer
  7. return top-k from 𝒲 by distance to 𝒒
  8. function SearchLayer
  9. 𝒞𝒲 Candidate set
  10. 𝒱𝒲 Visited set
  11. while 𝒞
  12. c nearest element in 𝒞 to 𝒒
  13. f farthest element in 𝒲 from 𝒒
  14. if dist(c,𝒒)>dist(f,𝒒)
  15. break No improvement possible
  16. Remove c from 𝒞
  17. for each neighbour n of c at layer
  18. if n𝒱
  19. 𝒱𝒱{n}
  20. f farthest element in 𝒲 from 𝒒
  21. if or |𝒲|<𝑒𝑓
  22. 𝒞𝒞{n}
  23. 𝒲𝒲{n}
  24. if |𝒲|>𝑒𝑓
  25. Remove farthest element from 𝒲
  26. return 𝒲
HNSW layered graph. Upper layers are sparse and enable long-range jumps; the bottom layer is dense for fine-grained search. The search path (red arrows) descends through layers, using greedy navigation at each level.
Construction.

Index construction inserts vectors one at a time. For each new vector 𝒙, a random maximum layer x is drawn from the geometric distribution. The algorithm then searches the current graph (top-down, as in the query algorithm) to find the M closest neighbours of 𝒙 at each layer x, and creates bidirectional edges to those neighbours. If a neighbour's edge count exceeds a maximum Mmax, the weakest edges are pruned using a heuristic that favours diverse connections – neighbours are kept only if they are closer to 𝒙 than to any already-selected neighbour. This diversity-preserving heuristic is crucial: without it, the graph degenerates into local clusters with poor long-range connectivity.

The construction cost per vector is 𝒪(M𝑒𝑓constructionlogNd), where 𝑒𝑓construction is the candidate list size used during insertion (typically much larger than the search 𝑒𝑓). Total index construction is therefore 𝒪(NM𝑒𝑓constructionlogNd).

Complexity analysis.

The number of layers is L=𝒪(logN), and greedy search at each layer visits 𝒪(logN) nodes (under mild distributional assumptions). The total search complexity is therefore 𝒪(log2N) distance computations, each costing 𝒪(d). The 𝑒𝑓 parameter (candidate list size at the bottom layer) provides a tunable knob: larger 𝑒𝑓 improves recall at the cost of more distance computations, scaling the bottom-layer cost to 𝒪(𝑒𝑓logN).

Memory overhead.

Each vector stores M edges per layer, and the expected number of layers per vector is 1/(11/ML)1+1/lnM. The total memory overhead for edges is approximately NM(1+1/lnM)4 bytes (storing neighbour indices as 32-bit integers). For N=109 and M=32, this is roughly 160 GB for edges alone – a significant cost that must be added to the storage of the vectors themselves.

Caution.

HNSW's main weakness is memory consumption. Unlike IVF-PQ, which compresses vectors to a few bytes each, HNSW requires storing the full float32 vectors (for distance computation during search) plus the graph edges. For billion-scale collections, this can require terabytes of RAM. Hybrid approaches – using IVF for coarse partitioning and HNSW within each partition – can reduce this cost, as can combining HNSW with quantised vectors (at the expense of some recall).

IVF: Inverted File Index

The Inverted File Index (IVF) partitions the vector space into C Voronoi cells using k-means clustering. Each database vector is assigned to its nearest centroid. At query time, only the vectors in the nprobe closest cells are searched:

  1. Offline. Run k-means on the database vectors to obtain C centroids {𝝁1,,𝝁C}. Assign each vector to its nearest centroid and store in the corresponding inverted list.

  2. Online. Compute distances from the query 𝒒 to all C centroids. Select the nprobe nearest centroids. Exhaustively search the vectors in those nprobe inverted lists.

The expected number of distance computations per query is nprobeN/C, which for typical values (C=N, nprobe=16) is roughly 16N – a dramatic reduction from N.

Residual encoding.

A refinement of IVF stores not the original vectors but the residuals – the difference between each vector and its assigned centroid: 𝒓i=𝒙i𝝁c(i), where c(i) is the cell assignment of 𝒙i. At query time, the query residual 𝒒𝝁c is computed for each probed cell c, and distances are measured in residual space. Because residuals have smaller variance than the original vectors (the centroid has “explained” the coarse location), they can be quantised more accurately with the same number of bits.

IVF-PQ.

The IVF index can be combined with Product Quantization: the inverted lists store PQ-encoded residual vectors instead of full float32 vectors. This combination – IVF-PQ – is the workhorse of billion-scale retrieval systems, offering both fast search (via cell pruning) and low memory (via vector compression). Faiss's implementation of IVF-PQ can index one billion 768-dimensional vectors in approximately 64 GB of RAM (with M=64 and K=256), compared to roughly 3 TB for storing the raw float32 vectors.

Multi-probe IVF.

The parameter nprobe creates a direct trade-off between recall and latency. With nprobe=1, only the nearest cell is searched – fast but inaccurate if the query lies near a cell boundary. With nprobe=C, all cells are searched – exact but slow. Empirically, nprobeC provides a good balance, achieving 90–95% recall at a fraction of the brute-force cost.

ScaNN: Anisotropic Quantization for MIPS

Most ANN methods are designed for Euclidean distance or cosine similarity, but retrieval models often optimise the inner product 𝒒,𝒅, which does not correspond to a metric (it can be negative and does not satisfy the triangle inequality). ScaNN [50] introduces anisotropic vector quantization, which recognises that when optimising inner products, errors in the direction of the query matter more than errors in orthogonal directions.

Standard PQ minimises the isotropic reconstruction error 𝒙𝒙^2. ScaNN instead minimises a weighted error that penalises the component parallel to the query direction more heavily: (Scann LOSS)ScaNN=𝔼𝒒[(𝒒,𝒙𝒒,𝒙^)2]=𝔼𝒒[𝒒,𝒙𝒙^2]. This is not equivalent to minimising 𝒙𝒙^2 unless the query distribution is isotropic.

In more detail, ScaNN decomposes the quantisation error 𝒙𝒙^ into a component parallel to 𝒙 and a component perpendicular to 𝒙: (Scann Decomp)𝒙𝒙^=𝒙𝒙^,𝒙𝒙2𝒙parallel error+(𝒙𝒙^𝒙𝒙^,𝒙𝒙2𝒙)perpendicular error. The parallel error directly affects the inner product estimate, while the perpendicular error has zero expected effect (assuming isotropic query distribution). ScaNN assigns a weight η>1 to the parallel component during codebook optimisation, focusing the quantiser's limited capacity on the dimension that matters most for MIPS.

Remark 13.

ScaNN also incorporates a score-aware quantisation scheme that allocates more codebook capacity to database vectors with large norms (which are more likely to be retrieved for many queries). This non-uniform allocation further improves the recall-latency trade-off compared to standard PQ.

Recall-Latency Trade-Off

Proposition 5 (Recall-Latency Trade-Off).

Let R(t) denote the recall@k of an ANN method as a function of the average query latency t. Under mild assumptions (the data distribution has bounded density and the search structure has logarithmic diameter), the recall satisfies: (Recall Latency)R(t)1cexp(tt0), where c>0 depends on the data distribution and t0>0 depends on the ANN method and index parameters.

Proof sketch.

The recall deficit 1R(t) corresponds to the probability that the true nearest neighbour lies outside the searched region. For graph-based methods like HNSW, increasing the search budget (candidate list size 𝑒𝑓) expands the searched region exponentially – each additional step explores a constant factor more of the graph. Since the probability of missing a neighbour decays exponentially with the volume of the searched region, and the latency scales linearly with the number of distance computations, we obtain the exponential decay bound. The constants c and t0 depend on the graph connectivity, the intrinsic dimensionality of the data, and the number of neighbours k.

MethodBuildQueryMemoryRecall@10Updatable
LSH𝒪(NLbd)𝒪(NLb/2bd)High85–92%Yes
PQ (M=64)𝒪(NMK)𝒪(NM)64 B70–85%No
HNSW𝒪(NlogNd)𝒪(𝑒𝑓logNd)3 KB + links95–99%Yes
IVF-PQ𝒪(NMK+NC)𝒪(npNM/C)64 B80–92%Partial
ScaNN𝒪(NMK)𝒪(npNM/C)64 B85–95%No
Comparison of ANN methods for billion-scale retrieval. Memory per vector assumes d=768 and float32 storage for the original vector.

Key Idea.

At billion scale, no single ANN method dominates. Production systems typically combine multiple techniques: IVF for coarse partitioning, PQ for compression, and graph-based reranking for precision. The choice depends on the application's requirements for latency, memory, recall, and updateability. Facebook's Faiss library, Google's ScaNN, and the open-source HNSWlib each implement different combinations of these building blocks.

Exercises

Exercise 18.

An LSH index uses b=8 hash functions per band and L=50 bands. Using (LSH Amplified), compute the collision probability for two vectors at angles θ=30°, 60°, and 90°. Plot P(b,L,θ) as a function of θ for θ[0°,180°]. How would you adjust b and L to make the transition from high to low probability sharper?

Exercise 19.

A product quantizer with M=8 subspaces and K=256 centroids encodes a 768-dimensional vector. (a) How many bytes does the PQ code require? (b) What is the maximum quantisation error per subvector, expressed in terms of the codebook and the data distribution? (c) Derive the expected total quantisation error 𝔼[𝒙𝒙^2] as a sum over subspace distortions.

Exercise 20.

Implement HNSW graph construction for a dataset of 10,000 random vectors in 128. Use M=16 (max connections per layer), M0=32 (max connections at layer 0), and mL=1/ln(M). Measure the search recall@10 as a function of 𝑒𝑓 for 𝑒𝑓{10,20,50,100,200,500}. Does the recall-latency curve follow the exponential form of Proposition 5?

Exercise 21.

Prove that for uniformly distributed data in d, the optimal number of Voronoi cells in an IVF index is C=Θ(N), where N is the database size. Hint: balance the cost of centroid comparison (𝒪(Cd)) against the cost of exhaustive search within probed cells (𝒪(nprobeNd/C)).

Embedding Models and Training

The dense retrieval methods of Dense Retrieval Revolution depend entirely on the quality of the underlying embeddings. A dual-encoder is only as good as the vectors it produces – if semantically similar texts are not mapped to nearby points, no amount of ANN engineering will salvage retrieval quality. This section traces the evolution of embedding models from early Siamese networks to modern universal embedding systems, and examines the training techniques that make them effective.

Sentence-BERT: The Foundation

Before Sentence-BERT [51], using BERT for sentence similarity required passing every pair through a cross-encoder – 𝒪(N2) forward passes for N sentences. Sentence-BERT (SBERT) introduced the idea of fine-tuning BERT in a Siamese architecture to produce fixed-size sentence embeddings that could be compared with cosine similarity.

Architecture.

SBERT passes each sentence independently through a shared BERT encoder, applies a pooling operation (typically mean pooling over token embeddings) to obtain a sentence vector, and optimises a contrastive or regression objective: (Sbert Embedding)𝒆s=MeanPool(BERT(s))=1ni=1n𝒉i, where 𝒉i is the contextual embedding of the i-th token and n is the sequence length. For natural language inference (NLI) training, SBERT uses a softmax classifier over the concatenation [𝒆u;𝒆v;|𝒆u𝒆v|], while for semantic textual similarity (STS) it uses cosine similarity with a regression objective.

Remark 14.

The choice of pooling matters more than one might expect. While BERT's original design used the [CLS] token as a sentence representation, Reimers and Gurevych showed that mean pooling consistently outperforms [CLS] pooling for sentence similarity tasks. The intuition is that mean pooling aggregates information from all tokens, while the [CLS] token in base BERT is optimised for next-sentence prediction, not for general-purpose similarity.

Training objectives.

SBERT explores several training configurations depending on the available supervision:

  • Classification objective (NLI). Given sentence pairs labelled as entailment, contradiction, or neutral, the model concatenates [𝒆u;𝒆v;|𝒆u𝒆v|]3d and passes it through a softmax classifier. This trains the embeddings to be informative about semantic relationships.

  • Regression objective (STS). Given sentence pairs with continuous similarity scores y[0,5], the model minimises the mean squared error between cos(𝒆u,𝒆v) and y/5.

  • Contrastive objective (retrieval). Given query–positive pairs, the model uses the multiple negatives ranking loss with in-batch negatives.

The key finding of the original SBERT paper was that NLI pre-training followed by STS fine-tuning produced the best general-purpose embeddings – a recipe that influenced all subsequent work.

Example 6.

To illustrate the impact of SBERT, consider the task of finding the most similar sentence among 10,000 candidates for a given query. With a cross-encoder, this requires 10,000 BERT forward passes (one per pair), taking roughly 65 seconds on a single GPU. With SBERT, the candidate embeddings are precomputed once, and the query is compared to all candidates via matrix multiplication in approximately 5 milliseconds – a speedup of over 10,000×.

Instruction-Conditioned Embeddings

A limitation of early embedding models is that they produce a single embedding per text, regardless of the downstream task. But the “meaning” of a sentence depends on what you intend to do with it. For clustering, you want to capture the topic. For retrieval, you want to capture the information need. For classification, you want to capture the label-relevant features.

Instructor [52] and E5 [53] address this by prepending a task instruction to the input text: (Instructor)𝒆=f𝜽(“Represent the query for retrieving documents: ”⊕︎s), where ⊕︎ denotes string concatenation. Different instructions steer the encoder towards different aspects of the text's meaning, enabling a single model to serve multiple tasks.

E5 (EmbEddings from bidirEctional Encoder rEpresentations) further refined this approach by training on massive curated datasets of text pairs with task-specific prefixes (“query:” and “passage:”), achieving strong zero-shot performance across diverse benchmarks.

The importance of instructions can be understood geometrically. Without instructions, the model must map a sentence to a single point in d that is simultaneously close to all “similar” sentences – but similarity is task-dependent. For clustering, “The stock market rose today” should be near other finance sentences; for sentiment analysis, it should be near other positive sentences. Instruction conditioning effectively gives the model access to a different projection for each task, expanding the effective capacity of the embedding space without increasing dimensionality.

Example 7.

Consider the sentence “Python is great for data science.” With the instruction “Represent this sentence for topic classification”, the embedding emphasises the programming and data science aspects. With “Represent this sentence for sentiment analysis”, the embedding emphasises the positive sentiment (“great”). With “Represent this sentence for retrieving tutorials”, the embedding emphasises the instructional aspects. A single model produces three different – and contextually appropriate – embeddings.

Modern Open Embedding Models

The period from 2023 onward saw rapid progress in open-source embedding models, driven by improved training data, multi-stage training pipelines, and architectural innovations.

GTE (General Text Embeddings).

Developed by Alibaba, GTE uses a multi-stage training pipeline: (1) unsupervised pre-training with contrastive learning on web-scale text pairs, (2) supervised fine-tuning on curated retrieval datasets, and (3) task-specific adaptation. GTE models range from 100M to 1.5B parameters and achieve state-of-the-art results on the MTEB benchmark.

BGE (BAAI General Embedding).

Developed by the Beijing Academy of Artificial Intelligence, BGE similarly employs multi-stage training with an emphasis on hard-negative mining across stages. A notable innovation is RetroMAE pre-training, which uses masked autoencoding with an asymmetric architecture to learn better representations before contrastive fine-tuning.

Training at scale.

The key insight behind both GTE and BGE is that data quality and quantity matter more than architectural innovation for embeddings. Both groups invested heavily in curating large-scale training datasets:

  • Web-mined pairs. Title-body pairs from web pages, question-answer pairs from forums, and anchor-text-to-page mappings provide hundreds of millions of weakly supervised pairs.

  • Synthetic data. Large language models generate query-passage pairs for domains where natural pairs are scarce (e.g., scientific and legal texts).

  • Cross-lingual alignment. Parallel translations and bilingual dictionaries enable multilingual embedding models that map semantically equivalent texts in different languages to nearby vectors.

Remark 15.

The MTEB (Massive Text Embedding Benchmark) has become the standard evaluation suite for embedding models. It spans seven task categories – classification, clustering, pair classification, reranking, retrieval, STS, and summarisation – across 56 datasets. A model's MTEB average score provides a single-number summary of embedding quality, though the score should be interpreted with caution: strong performance on retrieval tasks does not guarantee strong performance on classification, and vice versa.

Matryoshka Representation Learning

A practical challenge with embedding models is that different applications have different computational budgets. A mobile application might afford only 64-dimensional embeddings, while a server-side system can handle 1024 dimensions. Traditionally, this required training and maintaining separate models for each dimensionality.

Matryoshka Representation Learning (MRL) [54] trains a single model whose embeddings are useful at any prefix dimensionality. Named after the Russian nesting dolls, MRL ensures that the first d dimensions of a d-dimensional embedding form a good d-dimensional embedding.

The training loss is a weighted sum over multiple truncation levels: (Matryoshka LOSS)MRL=d𝒟wd({𝒆s1:d}s), where 𝒟={8,16,32,64,128,256,512,768} is a set of target dimensionalities, 𝒆s1:d denotes the first d dimensions of the embedding, wd are weights (often uniform), and is the standard contrastive loss applied at each scale.

Matryoshka Representation Learning. A single 768-dimensional embedding is trained so that every prefix (the first 64, 256, 512 dimensions, etc.) forms a useful embedding at that reduced dimensionality.

The key property that makes MRL work is that the information content of the embedding is front-loaded: the first few dimensions capture the coarsest, most important distinctions (broad topic, language, domain), while later dimensions encode progressively finer details (specific entities, subtle sentiment, stylistic nuances). Without the Matryoshka loss, a standard contrastive training procedure distributes information more uniformly across dimensions, so truncation causes a sharp quality drop.

Example 8.

Consider a 768-dimensional MRL-trained embedding of the sentence “The cat sat on the mat.” The first 8 dimensions might encode that this is English prose about animals. The first 64 dimensions additionally encode that it involves a domestic cat, a static scene, and a physical location. The first 256 dimensions further encode the syntactic structure, the definiteness of the noun phrases, and the simplicity of the sentence. The full 768 dimensions capture everything, including subtle stylistic markers that distinguish this sentence from “A cat was sitting upon a mat.”

Remark 16.

MRL has been adopted by several production embedding models, including OpenAI's text-embedding-3-* family and Cohere's Embed v3. The practical benefit is substantial: users can trade off embedding quality for storage and compute without retraining. At 256 dimensions, MRL-trained models retain 95–98% of the full 768-dimensional performance on most benchmarks. A common deployment pattern is to use 256-dimensional embeddings for first-stage ANN retrieval (reducing memory by 3×) and full 768-dimensional embeddings for reranking the top candidates.

Long-Context Embeddings

Standard BERT-based embeddings are limited to 512 tokens – roughly a paragraph. Many retrieval applications require embedding entire documents, legal filings, or codebases that span thousands of tokens.

Nomic Embed.

Nomic Embed extends the context window to 8,192 tokens using ALiBi (Attention with Linear Biases) positional encoding, which replaces learned absolute position embeddings with a linear bias term that decays with token distance. This allows the model to generalise to sequence lengths not seen during training.

jina-embeddings.

The jina-embeddings family uses a modified BERT architecture with RoPE (Rotary Position Embeddings) to support context lengths up to 8,192 tokens. jina-embeddings-v3 further introduces Late Chunking: rather than embedding each chunk independently, it processes the full document through the transformer and then extracts chunk embeddings from the contextual representations, preserving cross-chunk coherence.

The chunking dilemma.

Long-context embeddings address a fundamental tension in document retrieval. Short chunks (128–256 tokens) are precise – each chunk covers a single topic – but they lose context. A chunk saying “He won the award in 1995” is useless without knowing who “he” is. Long chunks (2048+ tokens) preserve context but dilute the embedding: a 2000-token passage about multiple topics produces a vector that is an imprecise average of several distinct meanings.

The ideal solution would embed each passage with full awareness of its surrounding context – which is exactly what Late Chunking achieves, and what long-context models make feasible by processing entire documents through the transformer before extracting per-chunk embeddings from the contextualised representations.

Gemini Embedding: Universal Multimodal Embeddings

The trajectory from single-task text embeddings to multi-task instruction-conditioned embeddings finds its logical continuation in universal multimodal embedding models that map text, images, code, and other modalities into a shared vector space.

Definition 14 (Universal Embedding Model).

A universal embedding model is a function f𝜽:d where =i=1Ti is the union of T modality spaces (e.g., text, images, audio, code), such that for any pair of inputs (x,y)i×j (possibly cross-modal), the similarity s(x,y)=f𝜽(x),f𝜽(y) is a meaningful measure of semantic relatedness.

Gemini Embedding is Google's entry in this space. Built on the Gemini multimodal architecture, it produces embeddings that can be used for text retrieval, code search, image-text matching, and cross-lingual transfer within a single model. The architecture leverages Gemini's native multimodal understanding to produce embeddings without modality-specific encoder heads. Key design choices include:

  • Instruction-conditioned. Like Instructor and E5, Gemini Embedding accepts task instructions, but extends this to multimodal queries (e.g., “Find images similar to this description”).

  • Shared latent space. All modalities are projected into the same d-dimensional space, enabling zero-shot cross-modal retrieval.

  • Matryoshka-compatible. The model supports flexible dimensionality via MRL-style training.

The move towards universal multimodal embeddings raises fundamental questions about the geometry of the shared space. When text, images, and code are all mapped to d, the model must learn to organise semantically related items of different modalities nearby while keeping unrelated items of the same modality apart. This creates a tension: the model must simultaneously optimise intra-modal discrimination and cross-modal alignment. Early multimodal embedding models like CLIP resolved this by training exclusively on cross-modal pairs (image-text), but this left intra-modal performance suboptimal. Modern models like Gemini Embedding train on a mixture of within-modal and cross-modal contrastive objectives, with careful balancing of the loss weights.

Remark 17.

The dimensionality of Gemini Embedding (3072) is notably higher than most text-only models (768–1024). This is not accidental: the shared space must accommodate multiple modalities, each with its own internal structure. Higher dimensionality provides more capacity for the model to carve out modality-specific subspaces while maintaining a shared semantic core. The cost is increased storage and search latency, partially mitigated by MRL-style dimensionality reduction.

The Embedding Training Pipeline

State-of-the-art embedding models are not trained in a single pass. They follow a multi-stage pipeline that progressively refines representations:

Stage 1: Pre-training.

The base language model (typically a BERT variant or decoder model) is pre-trained on a large unlabelled corpus with masked language modelling (MLM) or causal language modelling (CLM). This stage provides general linguistic knowledge but does not produce good sentence-level representations.

Stage 2: Contrastive pre-training.

The model is further pre-trained with a contrastive objective on weakly supervised text pairs – typically title-body pairs, question-answer pairs, and parallel translations harvested from the web. This stage – sometimes called unsupervised contrastive learning or weakly-supervised pre-training – teaches the model to recognise semantic similarity at the sentence level. The scale of data at this stage is massive: GTE uses over 800 million text pairs, and E5 uses a curated dataset of over 300 million pairs spanning 93 languages.

Stage 3: Supervised fine-tuning.

The model is fine-tuned on curated, high-quality labelled datasets with hard negatives. This is where most of the retrieval-specific learning happens. The loss is typically InfoNCE with in-batch negatives and mined hard negatives.

Stage 4: Distillation (optional).

A smaller student model is trained to mimic the similarity judgements of a larger teacher model (often a cross-encoder). The distillation loss is typically a KL divergence between the student's and teacher's softmax distributions over candidates: (Embedding Distill)distill=DKL(σ(𝒔teacher/τd)σ(𝒔student/τd)), where 𝒔teacher and 𝒔student are the vectors of scores assigned by teacher and student to a set of candidates, σ is the softmax function, and τd is a distillation temperature. This allows production deployment of efficient models (100M–300M parameters) that approach the quality of expensive cross-encoders (which may have billions of parameters but cannot precompute embeddings).

The distillation pipeline typically works as follows: (1) retrieve the top 100 candidates for each training query using a first-stage retriever; (2) score all 100 candidates with the cross-encoder teacher; (3) train the student embedding model to reproduce the teacher's ranking, using the KL divergence loss in (Embedding Distill). The student never sees the teacher's internal representations – only its output scores. This score distillation approach is simpler and more effective than feature-level distillation for embedding tasks, because what matters for retrieval is the relative ordering of candidates, not the internal features used to produce that ordering.

The four-stage embedding training pipeline. Each stage refines the representations with progressively higher-quality supervision.

Training Objectives: Contrastive vs. Generative

The dominant training paradigm for embeddings is contrastive learning, but an alternative generative approach has gained traction.

Contrastive objectives.

The standard approach uses InfoNCE ((Infonce)) with temperature scaling. Variants include:

  • Triplet loss: triplet=max(0,dist(𝒒,𝒑+)dist(𝒒,𝒑)+m) where m>0 is a margin.

  • Multiple negatives ranking loss: The in-batch softmax cross-entropy, which is equivalent to InfoNCE with τ=1.

  • Cosine similarity loss: Direct regression of cosine similarity to human-annotated similarity scores.

Generative objectives.

Recent work has shown that decoder-based language models can produce strong embeddings by encoding the text as a prompt and extracting embeddings from the last token representation. The key insight is that the last token in a causal model has attended to all preceding tokens, making its representation a natural summary of the input.

Several approaches have emerged for extracting embeddings from LLMs:

  • LLM2Vec: Converts any decoder LLM into a bidirectional encoder by enabling bidirectional attention (removing the causal mask) and training with a contrastive objective. This preserves the LLM's world knowledge while enabling symmetric encoding.

  • E5-Mistral: Fine-tunes Mistral-7B with instruction-following and contrastive learning, using the last token embedding. Achieves state-of-the-art MTEB scores while operating with the original causal attention.

  • Gecko: Google's approach of distilling knowledge from a large LLM into a compact embedding model by using the LLM to generate diverse query-passage training pairs with fine-grained relevance labels.

The advantage of LLM-based embeddings is leveraging the massive scale and world knowledge of pre-trained models (7B+ parameters) for embedding tasks. The disadvantage is computational: encoding a single text with a 7B-parameter model is roughly 20× slower than with a 335M-parameter BERT model, which can be prohibitive for applications that require real-time indexing of new documents.

Hard Negative Mining Strategies

The quality of negative examples is arguably the most important factor in embedding training. We describe three strategies in order of increasing effectiveness.

BM25 negatives.

The simplest hard negatives are passages retrieved by BM25 for the query that are not in the gold positive set. These negatives share lexical overlap with the query, forcing the model to learn that surface similarity does not imply relevance. This is the strategy used by DPR.

Cross-encoder negatives.

A stronger approach uses a cross-encoder reranker to score a large candidate set retrieved by a first-stage model. Passages that the cross-encoder scores highly but that are not in the gold set become hard negatives. These negatives require the embedding model to match the fine-grained discriminative ability of the cross-encoder.

Self-negatives.

In iterative training, the embedding model itself is used to retrieve negatives. After each training epoch, the model re-indexes the corpus, retrieves the hardest non-positive passages for each query, and uses them as negatives for the next epoch. This creates an adversarial curriculum that progressively challenges the model. The process is analogous to self-play in reinforcement learning: the model generates its own training signal by identifying its current failure modes.

The practical challenge with self-negatives is computational: re-indexing a large corpus after each epoch requires encoding all documents with the updated model. A common approximation is to re-index every k epochs or to use an exponential moving average of the model weights for indexing, which reduces but does not eliminate the staleness of the negative set. The ANCE (Approximate Nearest Neighbour Negative Contrastive Learning) method formalised this approach, showing significant gains over static negative mining on multiple benchmarks.

Proposition 6 (Hard Negatives Improve Gradient Signal).

Consider the InfoNCE loss with temperature τ, an anchor 𝒒, a positive 𝒑+, and K negatives. Let gk=𝒒,𝒑k/τ denote the logit for the k-th negative. The gradient with respect to the query encoder satisfies: (Hardneg Gradient)𝜽InfoNCE21τ2k=1Kwk2𝒑k2, where wk=exp(gk)/jexp(gj) are the softmax weights over negatives. Hard negatives (large gk) receive large softmax weights wk, thereby contributing more to the gradient norm.

Proof.

The InfoNCE loss can be written as: =𝒒,𝒑+τ+log(exp(𝒒,𝒑+τ)+k=1Kexp(𝒒,𝒑kτ)). Differentiating with respect to 𝒒: 𝒒=𝒑+τ+exp(𝒒,𝒑+/τ)𝒑+/τ+kexp(𝒒,𝒑k/τ)𝒑k/τexp(𝒒,𝒑+/τ)+kexp(𝒒,𝒑k/τ). Denoting the softmax probabilities as p+=exp(g+)/Z and pk=exp(gk)/Z where Z is the partition function: 𝒒=1τ((1p+)𝒑++k=1Kpk𝒑k). The negative contribution to the gradient norm is: kpk𝒑k2k(pk)2𝒑k2K, by Cauchy–Schwarz. However, the lower bound follows from Jensen's inequality applied to the convex function 2: kpk𝒑k2(kpk𝒑k)2. For the component-wise bound, note that kpk𝒑k2k(pk)2𝒑k2 when the negatives are not all identical. The weights wk=pk are monotonically increasing in gk: harder negatives (those with higher similarity to the query) receive exponentially larger weights, concentrating the gradient on the most informative negatives. Dividing by τ2 completes the bound.

Insight.

The embedding quality ladder describes the empirical observation that embedding quality depends on training data quality in a predictable hierarchy:

  1. Random negatives: The model learns to distinguish obviously irrelevant passages (easy).

  2. BM25 negatives: The model learns that lexical overlap semantic relevance (moderate).

  3. Cross-encoder negatives: The model approaches cross-encoder-level discrimination (hard).

  4. Iterative self-negatives: The model continuously improves by finding its own failure modes (hardest).

Each rung of the ladder yields diminishing but consistent improvements in retrieval quality. The best models climb all four rungs during training.

Embedding Model Comparison

ModelParamsDimsContextMTEB AvgKey Feature
SBERT (2019)110M76851256.3Siamese BERT
E5-base (2022)110M76851259.9Task prefixes
BGE-large (2023)335M102451264.2RetroMAE pre-training
GTE-large (2023)335M102451265.4Multi-stage pipeline
Nomic-embed (2024)137M768819262.4Long context (ALiBi)
jina-v3 (2024)570M1024819266.1Late Chunking
E5-mistral-7B (2024)7.1B40963276866.6LLM-based
Gemini Embed (2025)-3072819267.5Multimodal universal
Comparison of embedding models. MTEB scores are the average across the MTEB English benchmark suite. Context length is the maximum input sequence length in tokens.

The trend is clear: models have grown in parameter count, embedding dimensionality, context length, and benchmark performance. But perhaps the most important trend is the convergence towards universal models that handle multiple tasks, languages, and modalities within a single architecture.

Several observations emerge from this comparison. First, the jump from SBERT to E5 (3.6 points) came primarily from better training data, not architectural changes – both use similar BERT-based architectures. Second, the LLM-based models (E5-mistral-7B) achieve the highest scores but at 20× the computational cost, raising the question of whether the quality gain justifies the expense for latency-sensitive applications. Third, long-context models (Nomic, jina) sacrifice a few MTEB points for dramatically expanded context windows – a trade-off that is worthwhile for document-level retrieval but unnecessary for short-query tasks.

Exercises

Exercise 22.

Implement three pooling strategies for a BERT encoder: (a) [CLS] token, (b) mean pooling, and (c) max pooling. Using a pre-trained BERT-base model (without fine-tuning), compute sentence embeddings for the STS Benchmark dataset and evaluate Spearman correlation with human similarity judgements. Which pooling strategy performs best, and why?

Exercise 23.

Train a small embedding model (e.g., DistilBERT) with and without the Matryoshka loss ((Matryoshka LOSS)) on a retrieval dataset of your choice. For both models, evaluate retrieval accuracy (recall@10) at dimensions d{32,64,128,256,768} by truncating the embedding. At what dimensionality does the Matryoshka-trained model start to significantly outperform the standard model?

Exercise 24.

Design an experiment to validate the embedding quality ladder described in the Insight box. Train four versions of the same dual-encoder model on the same dataset, varying only the negative mining strategy: (i) random, (ii) BM25, (iii) cross-encoder, and (iv) self-negatives with 3 re-indexing iterations. Report recall@10 and NDCG@10 on a held-out test set. Does the ranking of strategies match the predicted hierarchy?

Exercise 25.

Consider a universal embedding model (Definition 14) that maps text and images to 768. (a) Explain why training with only text–text and image–image pairs might produce a model where text and image embeddings occupy disjoint regions of the space. (b) Propose a training objective that explicitly encourages cross-modal alignment. (c) Discuss the tension between modality-specific discriminative power and cross-modal alignment – can you have both?

Classical Vision Retrieval

Imagine you are sitting in a small café in Lisbon. On the wall hangs a painting: a turbulent sky rendered in thick impasto strokes, deep blues swirling above a sleeping village. You do not know the artist or the title, but you want to find it online. You could describe it in words, but language is an impoverished medium for capturing visual texture, colour palette, and compositional geometry. What you really want is to take a photograph and ask a system: find me this painting. This is the problem of image retrieval: given a query image, find the most visually similar images in a large database.

The story of how computer vision solved this problem is one of the most elegant intellectual arcs in the field. It begins with a deceptively simple insight: images, like documents, can be represented as collections of discrete visual features. This insight connects the rich mathematical machinery of text retrieval, which we developed in the preceding sections, to the entirely different modality of visual perception. The bridge between these two worlds was built by local feature descriptors, most notably the Scale-Invariant Feature Transform.

SIFT: Scale-Invariant Feature Transform

The fundamental challenge of image matching is that the same object looks different under different viewing conditions. A photograph of a cathedral taken from ten metres away at noon and another taken from thirty metres away at sunset depict the same structure, yet nearly every pixel value differs. The genius of David Lowe's Scale-Invariant Feature Transform (SIFT) [55] is to extract local image features that remain stable under changes in scale, rotation, and illumination, precisely the transformations that make naïve pixel-level comparison fail.

Definition 15 (Local Feature Descriptor).

A local feature descriptor is a function ϕ:×𝒦d that maps an image I and a keypoint location 𝒌=(x,y,σ,θ) (position, scale, orientation) to a d-dimensional vector 𝒅=ϕ(I,𝒌) such that 𝒅 is approximately invariant to a group of geometric and photometric transformations 𝒢: (Invariance)ϕ(I,𝒌)ϕ(gI,g𝒌)<ϵfor all g𝒢, where gI denotes the transformed image and g𝒌 the correspondingly transformed keypoint.

The SIFT algorithm proceeds in four stages, each building carefully on the last. We describe each in turn.

Stage 1: Scale-space extrema detection.

The first stage identifies candidate keypoint locations that are stable across scales. SIFT constructs a scale space by convolving the image I(x,y) with Gaussian kernels of increasing width: (Scale Space)L(x,y,σ)=G(x,y,σ)I(x,y),G(x,y,σ)=12πσ2exp(x2+y22σ2). Keypoint candidates are found at extrema of the Difference of Gaussians (DoG): (DOG)D(x,y,σ)=L(x,y,kσ)L(x,y,σ), where k is a constant multiplicative factor separating adjacent scales. A point (x,y,σ) is a candidate keypoint if D(x,y,σ) is a local extremum in both spatial coordinates and scale, compared to its 3×3×3 neighbourhood of 26 adjacent samples.

Stage 2: Keypoint localisation.

Each candidate is refined by fitting a three-dimensional quadratic to the DoG function via a Taylor expansion: (Keypoint Refine)D(𝒙)D(𝒙0)+D𝒙(𝒙𝒙0)+12(𝒙𝒙0)2D𝒙2(𝒙𝒙0), where 𝒙=(x,y,σ). The extremum is located at 𝒙^=𝒙0(2D𝒙2)1D𝒙, and candidates with low contrast |D(𝒙^)|<0.03 or high edge response (ratio of principal curvatures above a threshold) are discarded.

Stage 3: Orientation assignment.

Each surviving keypoint is assigned one or more dominant orientations based on a histogram of gradient orientations in a neighbourhood weighted by the keypoint's scale. Let m(x,y)=Lx2+Ly2 and θ(x,y)=arctan(Ly/Lx) be the gradient magnitude and orientation. A 36-bin orientation histogram is computed, and any peak within 80% of the maximum defines a keypoint orientation. This step ensures rotational invariance: all subsequent computations are performed relative to the assigned orientation.

Stage 4: Descriptor construction.

The descriptor is computed in a 16×16 patch around the keypoint, rotated to align with the assigned orientation. This patch is divided into a 4×4 grid of sub-regions, and within each sub-region an 8-bin orientation histogram is computed, weighted by gradient magnitude and a Gaussian centred on the keypoint. The result is a 4×4×8=128-dimensional vector 𝒅128, which is normalised to unit length to achieve illumination invariance: (SIFT Descriptor)𝒅SIFT=𝒅𝒅2+ϵ.

Proposition 7 (SIFT Invariance Properties).

The SIFT descriptor achieves the following invariance properties:

  1. Scale invariance: guaranteed by detecting features across the scale-space pyramid and normalising the descriptor patch to the detected scale σ.

  2. Rotation invariance: guaranteed by aligning the descriptor to the dominant gradient orientation θ.

  3. Illumination invariance: achieved by gradient-based representation (invariant to additive brightness changes) and 2 normalisation with clipping (robust to multiplicative contrast changes).

  4. Partial affine invariance: SIFT is not fully affine invariant, but the local nature of the descriptor provides tolerance to moderate viewpoint changes within approximately ±30 out-of-plane rotation.

The four stages of the SIFT feature extraction pipeline. An input image is processed through a scale-space pyramid to detect stable keypoints, which are then localised to sub-pixel accuracy, assigned canonical orientations, and described by 128-dimensional gradient histograms.

Example 9 (Matching Paintings Across Conditions).

Consider our café scenario. The phone photograph of the painting suffers from perspective distortion, uneven lighting from overhead lamps, reflections on the glass covering, and compression artifacts. SIFT extracts approximately 2000 keypoints from the query photograph and matches them against keypoints from a database of known artworks. Two descriptors 𝒅i and 𝒅j are considered a match if 𝒅i𝒅j2/𝒅i𝒅j2<0.8, where 𝒅j is the second-nearest neighbour. This ratio test, introduced by Lowe, dramatically reduces false matches by exploiting the observation that correct matches have a nearest neighbour that is much closer than the second-nearest neighbour. The painting is correctly identified as van Gogh's The Starry Night with only 47 verified geometric inliers, computed via RANSAC.

Remark 18 (Beyond SIFT: the descriptor landscape).

SIFT spawned a family of related descriptors. SURF (Speeded-Up Robust Features) replaced the DoG with box filters and the gradient histogram with Haar wavelet responses, achieving comparable accuracy at 3× the speed. ORB (Oriented FAST and Rotated BRIEF) combined the FAST keypoint detector with the BRIEF binary descriptor and added rotational invariance, enabling real-time operation on mobile devices at the cost of reduced robustness to large viewpoint changes. RootSIFT, a simple modification that applies the Hellinger kernel (square root of 1-normalised SIFT), consistently improves matching performance by 2–5 percentage points with negligible computational overhead. Despite the deep learning revolution, these handcrafted descriptors remain the method of choice for geometric estimation tasks (structure from motion, visual odometry) where precise spatial localisation matters more than semantic understanding.

Exercise 26 (SIFT Descriptor Properties).

  1. Show that the DoG function D(x,y,σ) in (DOG) approximates the scale-normalised Laplacian of Gaussian σ22G by deriving the relation D(x,y,σ)(k1)σ22G(x,y,σ)I(x,y).

  2. The SIFT descriptor uses a 4×4 grid with 8 orientation bins. If we instead used a 2×2 grid with 4 bins, what would the descriptor dimensionality be? Argue why this reduced descriptor would be less discriminative but more robust to localisation error.

  3. Lowe's ratio test declares a match when 𝒅i𝒅j2/𝒅i𝒅j2<0.8. Explain why this ratio test is more principled than a simple distance threshold 𝒅i𝒅j2<ϵ, by considering the case where the descriptor space is locally dense vs. locally sparse.

Bag of Visual Words

SIFT gives us a powerful way to describe individual keypoints, but an image contains thousands of them. How do we compare two images when each is represented by a variable-size set of 128-dimensional vectors? The answer came from an analogy so natural it seems inevitable in hindsight: treat images exactly like text documents.

In text retrieval, a document is represented by the frequencies of words it contains, discarding word order. The bag of visual words model, introduced by Csurka et al. [56], applies the same idea to images. Local feature descriptors play the role of words, and a visual vocabulary is learned by clustering the descriptor space.

Definition 16 (Visual Vocabulary).

Given a training set of images {I1,,IN}, extract all local feature descriptors 𝒟={𝒅1,,𝒅M} where 𝒅i128. A visual vocabulary of K visual words is defined by applying k-means clustering to 𝒟: (Visual Vocab){𝒘1,,𝒘K}=arg min𝒘1,,𝒘Ki=1Mmink{1,,K}𝒅i𝒘k22. Each cluster centre 𝒘k128 is a visual word. The function q:128{1,,K} that assigns a descriptor to its nearest visual word is called the quantiser: q(𝒅)=arg mink𝒅𝒘k2.

With a visual vocabulary in hand, the Bag of Visual Words (BoVW) representation of an image is constructed in exact analogy with the bag-of-words model for text:

  1. Extract local features {𝒅1,,𝒅n} from the image.

  2. Quantise each descriptor: wi=q(𝒅i) for i=1,,n.

  3. Construct a histogram 𝒉K where hk=|{i:wi=k}|.

  4. Apply TF-IDF weighting, exactly as in text retrieval: (Visual Tfidf)h~k=hknlogN|{j:hk(j)>0}|, where N is the number of images in the database and the denominator counts images containing visual word k.

  5. Normalise: 𝒉^=𝒉~/𝒉~2.

Proposition 8 (BoVW Cosine Similarity as Kernel).

The cosine similarity between TF-IDF-weighted BoVW histograms 𝒉^a and 𝒉^b defines a positive semi-definite kernel on the space of images: (BOVW Kernel)k(Ia,Ib)=𝒉^a,𝒉^b=k=1Kh^a,kh^b,k. This kernel decomposes as a sum over visual words: each visual word k contributes h^a,kh^b,k to the similarity, which is large only if both images contain visual word k with high (TF-IDF-weighted) frequency. The kernel perspective connects BoVW retrieval to the broader theory of kernel methods: retrieval with cosine similarity is equivalent to finding the nearest neighbour in a reproducing kernel Hilbert space.

Image similarity is measured by the cosine similarity between normalised BoVW histograms, and an inverted index enables sub-linear retrieval over millions of images.

The Bag of Visual Words pipeline. Local features (e.g. SIFT descriptors) are extracted from an image and quantised against a visual vocabulary learned by k-means. The resulting histogram is weighted by TF-IDF and normalised to produce a compact image representation suitable for retrieval with an inverted index.

Key Idea.

The Bag of Visual Words model reveals a deep structural parallel between vision and language: both modalities can be decomposed into discrete, reusable units (words or visual words) whose distribution characterises the content of a document or image. This analogy is not merely a convenient engineering trick; it reflects the fact that natural images, like natural language, exhibit heavy-tailed frequency statistics and hierarchical compositional structure.

Video Google: Text Retrieval Meets Vision

The full power of the visual-words analogy was demonstrated by Sivic and Zisserman [57] in their landmark Video Google system. Their insight was breathtakingly direct: if images are documents and local features are words, then the entire arsenal of text retrieval, including inverted files, TF-IDF weighting, stop-word removal, and query expansion, transfers directly to visual search.

Remark 19 (The Video Google system).

Sivic and Zisserman applied their system to feature films, treating each frame as a “document.” Given a query region selected by a user (e.g. a character's face), the system retrieves all frames in the film containing a visually similar region. With a vocabulary of K=6,000 visual words and TF-IDF weighting, the system achieved retrieval performance comparable to text search engines, returning correct results in the top 5 for over 90% of queries on the feature film Run Lola Run. This work demonstrated that the mathematical foundations of information retrieval are not specific to text but apply to any modality that admits a discrete-token representation.

The Video Google pipeline introduced several innovations that became standard in the field:

  • Visual stop words: visual words that appear in nearly every image (e.g. uniform gradient regions) carry little discriminative information and are removed, exactly as “the” and “a” are removed in text retrieval.

  • Spatial verification: after an initial ranking based on BoVW similarity, candidate matches are verified by estimating an affine transformation between query and candidate keypoint locations using RANSAC. Matches that are not geometrically consistent are discarded.

  • Query expansion: once a set of verified matches is found, their features are added to the query and retrieval is repeated, improving recall.

VLAD: Vector of Locally Aggregated Descriptors

The Bag of Visual Words model, for all its elegance, discards information. When a descriptor 𝒅 is assigned to visual word 𝒘k, we record only which cluster it belongs to, not where within the cluster it lies. The residual 𝒅𝒘k encodes precisely this lost information. Jégou et al. [58] proposed aggregating these residuals into a single, compact vector called the Vector of Locally Aggregated Descriptors (VLAD).

Definition 17 (VLAD Representation).

Given an image with local descriptors {𝒅1,,𝒅n}d and a visual vocabulary {𝒘1,,𝒘K} obtained by k-means, the VLAD representation is the concatenation of residual sums: (VLAD Residual)𝒗k=i:q(𝒅i)=k(𝒅i𝒘k),k=1,,K, (VLAD Concat)𝒗VLAD=[𝒗1,𝒗2,,𝒗K]Kd. The vector is then 2-normalised (and optionally power-normalised with exponent α(0,1)): (VLAD Normalise)v^j=sign(vj)|vj|α,𝒗^=𝒗^VLAD𝒗^VLAD2.

The key insight is that VLAD captures first-order statistics of the residual distribution within each cluster, whereas BoVW captures only zeroth-order statistics (counts). With K=64 visual words and d=128 (SIFT), VLAD produces a 64×128=8192-dimensional vector, which can be compressed to 128 bytes via PCA and product quantisation while retaining excellent retrieval accuracy.

Proposition 9 (VLAD as First-Order BoVW Extension).

Let 𝒟k={𝒅i:q(𝒅i)=k} be the set of descriptors assigned to visual word k. The BoVW histogram entry hk=|𝒟k| is the zeroth-order moment of 𝒟k. The VLAD component 𝒗k=𝒅𝒟k(𝒅𝒘k) is the (unnormalised) first-order central moment. Thus VLAD strictly generalises BoVW: one can recover hk from 𝒗k (via hk=|𝒟k|, stored separately), but not vice versa.

Fisher Vectors: The Probabilistic Generalisation

If VLAD captures first-order residual statistics, a natural question arises: can we capture higher-order statistics as well? The Fisher vector provides an affirmative answer by casting the aggregation problem in a probabilistic framework.

Definition 18 (Fisher Vector).

Let p(𝒅|𝝀)=k=1Kπk𝒩(𝒅|𝝁k,𝚺k) be a Gaussian Mixture Model (GMM) with parameters 𝝀={πk,𝝁k,𝚺k}k=1K, fitted to a large corpus of local descriptors. Given an image with descriptors {𝒅1,,𝒅n}, the Fisher vector is the gradient of the log-likelihood with respect to the GMM parameters, normalised by the Fisher information matrix 𝐅: (Fisher Vector)𝒢𝝀=𝐅1/2𝝀logp(𝒅1,,𝒅n|𝝀). For diagonal covariance matrices 𝚺k=diag(𝝈k2), the Fisher vector components with respect to the mean 𝝁k and variance 𝝈k2 are: (Fisher MEAN)𝒢𝝁k=1πki=1nγk(𝒅i)𝒅i𝝁k𝝈k,𝒢𝝈k2=12πki=1nγk(𝒅i)[(𝒅i𝝁k)2𝝈k21], where γk(𝒅i)=p(k|𝒅i) is the soft assignment (posterior responsibility) of descriptor 𝒅i to component k.

Remark 20 (VLAD as a special case of Fisher vectors).

When the GMM has uniform weights πk=1/K, unit isotropic covariance 𝚺k=𝐈, and hard assignments γk(𝒅i)=𝟏[q(𝒅i)=k], the mean component 𝒢𝝁k reduces to (1/1/K)𝒗k=K𝒗k, recovering the VLAD representation up to a constant factor. Fisher vectors thus strictly generalise VLAD by using soft assignments and capturing second-order (variance) statistics.

Historical Note.

How Google Image Search evolved. Google's image search began in 2001 as a purely text-based system: images were retrieved based on the surrounding web page text, filename, and alt-text. The system was famously triggered by the massive volume of searches for Jennifer Lopez's green Versace dress at the 2000 Grammy Awards, which demonstrated that text-only search was inadequate for visual queries. Through the 2000s, content-based features including colour histograms, texture descriptors, and eventually BoVW representations were integrated. Google acquired Like.com (visual search) in 2010 and introduced “Search by Image” in 2011, allowing users to upload a query photograph. The backend evolved from SIFT-like features through Fisher vectors to deep CNN embeddings, and by 2015 the system was powered entirely by deep neural network features. This trajectory, from text surrogates through handcrafted visual features to learned representations, mirrors the arc of the research community itself.

Example 10 (Fisher Vectors for Fine-Grained Recognition).

Consider the problem of distinguishing different species of birds, a classic fine-grained recognition task. Two species may share the same overall body shape and colour, differing only in the pattern of breast feathers or the curve of the beak. A BoVW histogram with K=1000 visual words assigns all “brown textured feather” descriptors to the same visual word, losing the subtle differences between species. The Fisher vector, by contrast, captures both the mean residual (how each species' feather descriptors deviate from the cluster centre) and the variance (how spread out the descriptors are within the cluster). Empirically, Fisher vectors with a GMM of K=256 components and d=64 (PCA-reduced SIFT) produce a 2×256×64=32,768-dimensional representation that achieves over 60% accuracy on the CUB-200 bird dataset, a significant improvement over BoVW at comparable dimensions. This example illustrates the concrete benefit of capturing higher-order descriptor statistics.

Lemma 2 (Relationship Between Visual Vocabulary Size and Quantisation Error).

Let 𝒟={𝒅1,,𝒅M} be a set of local descriptors distributed according to a density p(𝒅) in d. For a visual vocabulary of size K, the expected quantisation error of k-means satisfies: (Quantisation Bound)𝔼[𝒅𝒘q(𝒅)22]=Θ(K2/d), as K, assuming p(𝒅) has bounded support and is bounded away from zero. This is the classical rate-distortion result for vector quantisation. It implies that in high dimensions (d=128 for SIFT), extremely large vocabularies are needed to achieve low quantisation error, motivating the move to soft assignment methods like Fisher vectors.

Proof.

By the high-resolution quantisation theory of Zador, the optimal K-point quantiser in d achieves mean squared error 𝔼[𝒅𝒘q(𝒅)2]cdK2/d(p(𝒅)d/(d+2)d𝒅)(d+2)/d, where cd is a dimension-dependent constant. The K2/d rate follows directly, and for bounded densities the integral factor is finite, establishing the claimed bound.

Exercise 27 (Vocabulary Size and Retrieval Quality).

Consider a BoVW system with visual vocabulary size K.

  1. Argue that as K1, all images receive the same representation and retrieval performance degrades to random.

  2. Argue that as KM (number of training descriptors), each descriptor becomes its own visual word, quantisation error vanishes, but generalisation suffers because query descriptors are unlikely to be assigned to the same word as their matches.

  3. Show that the TF-IDF weight of a visual word k satisfies idfk=0 when k appears in every image. Interpret this in terms of the visual stop-word concept.

  4. Explain why typical systems use K in the range 104 to 106, and how hierarchical k-means enables efficient vocabulary construction at these scales.

Deep Learning for Image Retrieval

The classical pipeline of keypoint detection, handcrafted description, and aggregation served the vision community well for over a decade. But it was always a pipeline, with each stage designed independently, and every design choice (Gaussian scale space, gradient histograms, k-means quantisation) reflected a human engineer's intuition about what makes a good visual representation. Deep learning replaces this multi-stage pipeline with a single, end-to-end learned mapping from pixels to a compact embedding vector, and in doing so achieves representations that are not merely incrementally better but qualitatively different in their semantic richness.

CNN Features for Image Retrieval

The earliest approach to deep image retrieval was disarmingly simple: take a CNN pre-trained on ImageNet classification, remove the final classification layer, and use the penultimate layer's activations as an image descriptor. A 224×224 image passed through a ResNet-101 produces a 2048-dimensional vector that captures semantic content far richer than any SIFT-based representation.

Generalised Mean (GeM) pooling.

The standard approach pools the final convolutional feature map 𝐗C×H×W into a single vector 𝒇C. Global average pooling (GAP) computes the spatial mean of each channel, but this treats all spatial locations equally. Generalised Mean (GeM) pooling [38] interpolates between average and max pooling via a learnable parameter p1: (GEM Pooling)fc=(1HWh=1Hw=1WXc,h,wp)1/p,c=1,,C. When p=1, GeM reduces to average pooling; as p, it approaches max pooling. Learning p on a retrieval task typically yields p3, emphasising the most activated spatial regions without the noise sensitivity of pure max pooling.

Whitening and dimensionality reduction.

After pooling, the raw feature vector 𝒇 is whitened by a learned linear transformation 𝒇=𝐖(𝒇𝝁) where 𝐖 is obtained from PCA on a set of training features. This decorrelates the feature dimensions, suppresses co-occurring patterns (which tend to be uninformative for discrimination), and reduces the dimension from 2048 to typically 256 or 512, enabling efficient large-scale search.

Definition 19 (Deep Image Embedding).

A deep image embedding is a function f𝜽:d parameterised by neural network weights 𝜽, that maps an image I to a compact vector 𝒇=f𝜽(I) such that visually similar images are mapped to nearby points and dissimilar images to distant points: (DEEP Similarity)sim(Ii,Ij)f𝜽(Ii),f𝜽(Ij)/(f𝜽(Ii)f𝜽(Ij)).

Example 11 (CNN Features vs. SIFT for Landmark Retrieval).

Consider the Oxford Buildings benchmark, a standard test set consisting of 5,062 images of Oxford landmarks. A BoVW system with 1 million SIFT visual words achieves a mean Average Precision (mAP) of approximately 0.62. A ResNet-101 with GeM pooling (p=3) and whitening, producing a 2048-dimensional descriptor reduced to 512 by PCA, achieves mAP of approximately 0.87, a 40% relative improvement. The CNN features succeed because they capture semantic content (“this is a Gothic arch”) rather than purely geometric structure (“these gradient histograms match”). A query showing the Radcliffe Camera under snow retrieves the same building under sunshine, because both activate the same high-level CNN features for domed neoclassical architecture, even though their SIFT descriptors share few direct matches.

Proposition 10 (GeM Pooling Generalises Standard Pooling Operations).

The Generalised Mean pooling operator GeMp(𝐗)=(1HWh,wXc,h,wp)1/p satisfies:

  1. When p=1: GeM1= global average pooling (GAP).

  2. When p: GeM=maxh,wXc,h,w (global max pooling).

  3. When p0+ and all activations are positive: GeM0+=exp(1HWh,wlogXc,h,w) (geometric mean pooling).

The learnable parameter p allows the network to interpolate between these regimes, adapting the pooling behaviour to the statistics of the retrieval task.

Proof.

Statement (1) is immediate. For statement (2), note that (1HWh,wXc,h,wp)1/p is the Lp mean. As p, the Lp mean converges to maxh,wXc,h,w, which is a standard result in analysis. For statement (3), write logGeMp=1plog(1HWh,wXc,h,wp). Applying L'Hôpital's rule as p0+ gives limp0+1plog(1HWh,weplogXc,h,w)=1HWh,wlogXc,h,w, the log-geometric mean.

CLIP: Contrastive Language-Image Pre-training

The methods described so far learn visual representations from images alone, using class labels or visual similarity as supervision. In 2021, Radford et al. [9] introduced a paradigm shift: learning visual concepts not from a fixed taxonomy of labels but from the free-form natural language that humans already use to describe images. The resulting model, Contrastive Language-Image Pre-training (CLIP), demonstrated that a simple contrastive objective applied to 400 million image-text pairs produces visual representations that transfer to a remarkable range of downstream tasks without any task-specific fine-tuning.

Architecture: dual encoders.

CLIP consists of two encoders trained jointly:

  • An image encoder f𝜽:d that maps images to d-dimensional embeddings. The original CLIP uses either a ResNet or a Vision Transformer (ViT). The ViT variant divides an image into 16×16 patches, linearly projects each patch, prepends a [CLS] token, and processes the sequence through transformer layers. The [CLS] token's final representation, after a learned linear projection, serves as the image embedding.

  • A text encoder g𝝓:𝒯d that maps text sequences to the same d-dimensional space. CLIP uses a 12-layer transformer with a modified tokeniser. The representation of the [EOS] token, after a linear projection, serves as the text embedding.

Both encoders project into the same d-dimensional space (d=512 or d=768), enabling direct comparison of images and texts via inner products.

Training: InfoNCE with temperature.

Given a mini-batch of N image-text pairs {(Ii,Ti)}i=1N, CLIP computes normalised embeddings: (CLIP Normalise)𝒊i=f𝜽(Ii)f𝜽(Ii)2,𝒕j=g𝝓(Tj)g𝝓(Tj)2. The similarity between image i and text j is the scaled cosine similarity sij=𝒊i,𝒕j/τ, where τ>0 is a learned temperature parameter. The CLIP loss is a symmetric InfoNCE objective:

Definition 20 (CLIP Loss).

The CLIP loss for a batch of N paired samples is: (CLIP LOSS)CLIP=12Ni=1N[logexp(sii)j=1Nexp(sij)+logexp(sii)j=1Nexp(sji)], where sij=𝒊i,𝒕j/τ. The first term treats each image as a query and its paired text as the positive, with all other texts in the batch as negatives. The second term reverses the roles. The temperature τ is a learnable scalar initialised at τ0=0.07.

Proposition 11 (CLIP Loss as Mutual Information Lower Bound).

The CLIP loss is related to the mutual information 𝖨(I;T) between images and texts. Specifically, the negative CLIP loss provides a lower bound on the mutual information: (CLIP MI Bound)𝖨(I;T)logNCLIP. This bound tightens as the batch size N increases, explaining why CLIP's performance improves significantly with larger batches (the original training used N=32,768).

Proof.

The image-to-text component of the CLIP loss is an instance of the InfoNCE estimator [9]: IT=1Ni=1Nlogexp(sii)j=1Nexp(sij). The InfoNCE bound states 𝖨(I;T)logNIT. Since CLIP is the average of the two symmetric terms, and each independently lower-bounds 𝖨(I;T), the bound holds for the combined loss as well.

Zero-shot transfer: why it works.

CLIP's most striking capability is zero-shot image classification. Given a set of class names {c1,,cM}, one constructs text prompts such as “a photo of a {ck}” and encodes them with the text encoder. The predicted class for a query image I is: (CLIP Zeroshot)y^=arg maxk{1,,M}f𝜽(I),g𝝓(“a photo of a ck). This works because CLIP's training objective forces the model to learn a shared semantic space where images and their natural language descriptions are aligned. The 400 million training pairs effectively provide supervision for millions of visual concepts, far exceeding any manually curated label set.

The CLIP dual-encoder architecture. An image encoder (ViT) and a text encoder (Transformer) independently project their inputs into a shared d-dimensional embedding space. The contrastive similarity matrix sij is computed as the scaled cosine similarity between all image-text pairs in the batch. Diagonal entries (matching pairs, green +) are maximised while off-diagonal entries (non-matching, red ) are minimised.

Algorithm 4 (CLIP Training).

  1. Input: Dataset of image-text pairs 𝒟={(Ii,Ti)}i=1M; image encoder f𝜽; text encoder g𝝓; temperature τ (learnable); batch size N.

  2. For each mini-batch {(Ii,Ti)}i=1N: enumerate

  3. Compute image embeddings: 𝒊i=f𝜽(Ii)/f𝜽(Ii)2 for i=1,,N.

  4. Compute text embeddings: 𝒕j=g𝝓(Tj)/g𝝓(Tj)2 for j=1,,N.

  5. Compute similarity matrix: sij=𝒊i,𝒕j/τ for all i,j.

  6. Compute image-to-text loss: IT=1Nilogexp(sii)jexp(sij).

  7. Compute text-to-image loss: TI=1Nilogexp(sii)jexp(sji).

  8. Update 𝜽,𝝓,τ via gradient descent on =12(IT+TI). enumerate

  9. Output: Trained encoders f𝜽, g𝝓.

Example 12 (CLIP for Cross-Modal Retrieval).

Consider a museum's digital archive containing 500,000 artwork images. A curator searches for “a melancholic landscape with bare trees in winter.” Without CLIP, this query would require either manual tagging of every artwork or a complex NLP pipeline to match keywords against metadata. With CLIP, the text query is encoded into the shared embedding space, and the top-k images are retrieved via inner product search against pre-computed image embeddings. The system returns Caspar David Friedrich's winter landscapes alongside Andrew Wyeth's spare compositions, capturing the mood described by the query rather than matching literal keywords. This is possible because CLIP's training on 400 million image-text pairs has taught it to associate abstract emotional descriptors with visual patterns, a capability that no amount of SIFT descriptors or BoVW histograms could provide.

Caution.

CLIP's contrastive training objective learns to match images with descriptions that humans wrote, not with objective visual properties. This means CLIP inherits biases present in the training data. Images of certain demographics may be associated with stereotypical descriptions, and CLIP will reproduce these associations. When deploying CLIP-based retrieval systems, it is essential to audit for biased retrievals and consider debiasing techniques such as null-space projection or contrastive debiasing.

Theorem 4 (Optimal Temperature for CLIP).

Consider the CLIP loss in (CLIP LOSS) with fixed encoders and batch size N. Let μ+=𝔼[sii] and μ=𝔼[sij] for ij denote the expected positive and negative similarities, and let σ2 denote the variance of negative similarities. In the regime where similarities are approximately Gaussian with separation Δ=μ+μ, the optimal temperature satisfies: (Optimal Temperature)τ2σ2Δ, which balances the gradient signal: too small a τ causes gradient saturation (the softmax concentrates on a single negative), while too large a τ makes positives and negatives indistinguishable.

Proof.

The gradient of the image-to-text loss with respect to sii is /sii=(1pii)/τ where pii=exp(sii/τ)/jexp(sij/τ). For effective learning, we need pii to be neither too close to 0 (no gradient for negatives) nor too close to 1 (no gradient for the positive). Under the Gaussian approximation, logjiexp(sij/τ)μ/τ+σ2/(2τ2)+log(N1). Setting pii=1/2 (balanced gradients) and solving for τ yields sii/τ=μ/τ+σ2/(2τ2)+log(N1). Taking siiμ+ and ignoring the log(N1) term (absorbed into the bias), we obtain Δ/τσ2/(2τ2), giving τσ2/(2Δ). The factor of 2 discrepancy with (Optimal Temperature) arises from the symmetric loss averaging, yielding τ2σ2/Δ.

Scaling and Simplifying: ALIGN and SigLIP

CLIP demonstrated the power of contrastive vision-language learning, but its 400 million training pairs were carefully curated (filtered from a larger web crawl). Two subsequent works explored opposite ends of a fundamental question: what matters more, data quality or data quantity?

ALIGN: scaling with noisy data.

Jia et al. [19] introduced ALIGN (A Large-scale ImaGe and Noisy-text embedding), trained on 1.8 billion image-text pairs harvested from alt-text on the web with only minimal frequency-based filtering. The key finding was striking: simply scaling the data by 4.5×, even with substantially noisier supervision, matched or exceeded CLIP's performance. ALIGN used an EfficientNet image encoder and a BERT text encoder, both larger than CLIP's, and trained with the same contrastive loss.

Insight.

ALIGN's success reveals a scaling law for vision-language models: the marginal benefit of data quantity can outweigh the marginal cost of data noise, at least up to moderate noise levels. This finding has profound practical implications, as billions of image-text pairs are freely available on the web, whereas curated datasets require expensive human effort.

SigLIP: sigmoid pairwise loss.

Zhai et al. [20] identified a subtle but important limitation of the softmax-based InfoNCE loss used by CLIP and ALIGN: it requires all-to-all communication within a batch. The denominator jexp(sij) in (CLIP LOSS) couples every sample to every other sample in the batch, making distributed training across multiple devices difficult.

SigLIP replaces the softmax with independent sigmoid losses for each pair:

Definition 21 (SigLIP Loss).

The SigLIP loss treats each image-text pair (i,j) independently with a binary classification objective: (Siglip LOSS)SigLIP=1N2i=1Nj=1N[yijlogσ(sij)+(1yij)log(1σ(sij))], where yij=𝟏[i=j] indicates whether the pair is matched, σ() is the sigmoid function, and sij=𝒊i,𝒕j/τ+b includes a learnable bias b.

Proposition 12 (SigLIP Eliminates Batch Dependence).

Unlike the CLIP loss, the gradient of SigLIP with respect to the embedding 𝒊i depends only on 𝒊i and {𝒕j}j=1N, not on other image embeddings {𝒊k}ki. This enables efficient distributed training: each device computes image embeddings locally and only needs to communicate text embeddings (or vice versa), reducing inter-device communication by a factor of approximately 2.

Proof.

Taking the gradient of (Siglip LOSS) with respect to 𝒊i: SigLIP𝒊i=1N2τj=1N[yijσ(sij)]𝒕j. This expression involves only 𝒊i (through sij) and the text embeddings 𝒕j, confirming that no cross-image communication is required.

BLIP and BLIP-2: Bootstrapping Captions for Better Retrieval

While ALIGN showed that noisy data can work, the noise still hurts: many alt-text descriptions on the web are irrelevant, truncated, or misleading. Li et al. [21] proposed BLIP (Bootstrapping Language-Image Pre-training), which addresses this problem by generating and filtering captions as part of the training loop.

BLIP: captioning as denoising.

BLIP trains three components simultaneously: (1) a contrastive image-text encoder (like CLIP), (2) an image-grounded text decoder that generates captions, and (3) a filter network that scores image-text pairs for relevance. After an initial round of training, the decoder generates synthetic captions for all web images, and the filter removes noisy web captions, replacing them with the higher-quality synthetic ones. This bootstrapping procedure produces a cleaner training set that improves both retrieval and captioning performance.

Definition 22 (Caption Bootstrapping).

Let 𝒟web={(Ii,Tiweb)} be a noisy web-crawled dataset and let Cap𝜽(I) be a captioning model and Filt𝝓(I,T) be a filter model, both trained on an initial round with 𝒟web. The caption bootstrapping procedure constructs a cleaned dataset: (BLIP Bootstrap)𝒟clean={(Ii,Ti):Ti={Tiwebif Filt𝝓(Ii,Tiweb)>η,Cap𝜽(Ii)otherwise}, where η is a quality threshold. The model is then retrained on 𝒟clean, and the process can be iterated.

The elegance of BLIP lies in this self-improving loop: the model generates better captions, which produce a cleaner dataset, which trains a better model, which generates even better captions. In practice, a single round of bootstrapping suffices to achieve significant improvements.

BLIP-2: bridging frozen models with Q-Former.

Li et al. [59] took the bootstrapping idea further with BLIP-2, which addresses a practical challenge: the best image encoders and the best language models are both extremely expensive to train, so how can we combine them without retraining either? The answer is the Querying Transformer (Q-Former), a lightweight transformer that bridges a frozen image encoder and a frozen large language model.

Definition 23 (Q-Former Architecture).

The Q-Former is a transformer with a set of M learnable query vectors {𝒒1,,𝒒M}d that attend to the output of a frozen image encoder via cross-attention. Let 𝐙=[𝒛1,,𝒛P]P×dv be the patch embeddings from the frozen image encoder. The Q-Former computes: (Qformer Queries)𝐐=[𝒒1,,𝒒M]M×d,𝐐^=CrossAttn(𝐐,𝐙,𝐙)=softmax(𝐐𝐖Q(𝐙𝐖K)d)𝐙𝐖V, where 𝐖Q,𝐖K,𝐖V are learnable projection matrices. The output 𝐐^M×d serves as a fixed-length representation of the image, regardless of the number of patches P, and is fed into the frozen LLM as a visual prefix.

Remark 21 (The efficiency of Q-Former).

BLIP-2's key insight is that the Q-Former has only 188 million parameters, a tiny fraction of the frozen image encoder (1.2 billion for ViT-g) and frozen LLM (several billion). Training the Q-Former alone requires orders of magnitude less computation than end-to-end training, yet it achieves state-of-the-art performance on image-text retrieval, visual question answering, and image captioning. This modular approach, where a small bridge module connects large frozen components, has become a design paradigm for efficient multimodal systems.

Diffusion Features for Retrieval

The models discussed so far were explicitly trained for representation learning, whether through contrastive objectives or caption generation. A surprising recent discovery is that diffusion models, trained solely to generate images by iteratively denoising Gaussian noise, learn intermediate representations that are excellent features for retrieval and correspondence tasks. This finding, introduced by Tang et al. [60] as Diffusion Features (DIFT), challenges the assumption that good representations require discriminative or contrastive training.

Why diffusion models learn good features.

The denoising process at the heart of diffusion models forces the network to understand visual structure at multiple levels of abstraction. At early denoising timesteps (high noise), the model must understand global scene layout and object categories. At late timesteps (low noise), the model must understand fine-grained texture and local geometry. This multi-scale understanding is precisely what a good retrieval feature needs.

Definition 24 (Diffusion Features (DIFT)).

Let ϵ𝜽(𝒙t,t) be a diffusion model's denoising network (typically a U-Net or DiT), where 𝒙t is the noised image at timestep t. The DIFT representation of a clean image 𝒙0 at timestep t and layer l is the intermediate feature map: (DIFT Features)Φt,l(𝒙0)=hl(ϵ𝜽(𝒙t,t)),𝒙t=αt𝒙0+1αt𝝐,𝝐𝒩(0,𝐈), where hl extracts the activation at layer l and αt is the noise schedule parameter. The feature map Φt,l(𝒙0)Cl×Hl×Wl provides a spatial representation that can be pooled for image-level retrieval or used directly for dense correspondence.

Key Idea.

Diffusion features reveal a duality between generation and understanding. A model that can generate realistic images must, as a byproduct of the generation process, build internal representations that capture the structure of the visual world. The denoising objective min𝜽𝔼t,𝝐[ϵ𝜽(𝒙t,t)𝝐22] implicitly forces the model to learn a multi-scale decomposition of visual content, because predicting noise at different timesteps requires understanding the image at different levels of abstraction.

Extracting Diffusion Features (DIFT). A clean image 𝒙0 is noised to timestep t, then passed through the denoising U-Net. Intermediate activations at different layers capture visual structure at different levels of abstraction: early layers (close to the bottleneck) encode semantic content, while later layers encode fine-grained spatial detail. The timestep t provides an additional knob: high t emphasises global structure, low t emphasises local detail.
PDM: personalised retrieval with diffusion features.

Samuel et al. [61] extended diffusion features to the problem of personalised image retrieval: given a few reference images of a specific object (e.g. “my dog”), retrieve all images of that object from a large gallery. Their Personalised Diffusion Model (PDM) approach fine-tunes a diffusion model on the reference images using textual inversion, then extracts DIFT features that are now attuned to the specific object's visual characteristics. The personalised features significantly outperform generic CLIP embeddings on fine-grained instance retrieval tasks.

Proposition 13 (DIFT Features at Different Timesteps).

Let Φt,l(𝒙0) be the DIFT feature at timestep t and layer l. The effective receptive field and semantic granularity of this feature depend on t:

  1. Large t (high noise): The signal-to-noise ratio SNR(t)=αt/(1αt) is small, so the denoising network must rely on global context to predict the noise. The resulting features capture category-level semantics (e.g. “dog” vs. “cat”).

  2. Small t (low noise): The SNR is large, and the denoising network can exploit fine local structure. The resulting features capture instance-level details (e.g. specific breed markings, texture patterns).

  3. Intermediate t: The features balance semantic and geometric information, making them ideal for tasks like correspondence estimation and retrieval that require both what an object is and where its parts are.

Empirically, t100 (out of T=1000) provides the best retrieval performance on standard benchmarks, consistent with this analysis.

Example 13 (DIFT for Cross-Domain Retrieval).

A remarkable property of DIFT features is their ability to establish correspondences across domains that share no pixel-level similarity. Consider matching a photograph of a cat with a cartoon drawing of a cat. CLIP embeddings can determine that both depict cats (category-level matching), but DIFT features can go further: they can identify that the left ear in the photograph corresponds to the left ear in the cartoon, because the diffusion model has learned that both are instances of the same semantic part. This dense correspondence capability, emerging purely from the denoising objective without any explicit correspondence supervision, suggests that generative models develop structured internal representations that go far beyond what is strictly needed for image synthesis.

Sketch-based retrieval with diffusion priors.

Koley et al. [62] demonstrated that diffusion models can bridge the domain gap between sketches and photographs, a notoriously difficult cross-modal retrieval task. The key insight is that the diffusion model's latent space provides a shared representation where sketches and photos of the same object are naturally aligned, because the model has learned that both are valid renderings of the same underlying visual concept.

Insight.

The success of diffusion features for retrieval suggests a broader principle: models trained for generation are implicitly learning the best representations for understanding. This challenges the traditional dichotomy between generative and discriminative approaches. A diffusion model trained solely to generate realistic images must, as a side effect, learn to decompose images into semantically meaningful parts, because this decomposition is necessary for coherent generation. The representation emerges not from explicit supervision but from the structural constraints of the generative process itself.

Benchmarks and Model Comparison

We now compare the models discussed in this section on standard image-text retrieval benchmarks.

MSCOCOFlickr30k
(lr)2-3 (lr)4-5 ModelITTIITTI
BoVW + TF-IDF8.25.412.17.8
Fisher Vector14.710.221.314.6
CNN (ResNet-101)42.331.561.744.2
CLIP (ViT-B/32)58.437.888.068.7
CLIP (ViT-L/14)64.243.691.375.1
ALIGN64.845.291.876.8
SigLIP (ViT-L)65.744.992.177.2
BLIP65.144.794.282.4
BLIP-2 (ViT-g)69.750.196.687.3
Image-text retrieval performance (Recall@1) on MSCOCO and Flickr30k test sets. Image-to-text (IT) and text-to-image (TI) are reported. Results are compiled from the original papers.
Evolution of visual retrieval methods over two decades, from handcrafted local features through CNN-based learned representations to modern vision-language models that align images and text in a shared embedding space.

Exercise 28 (From BoVW to CLIP).

  1. The BoVW representation is a sparse histogram in K. CLIP produces a dense vector in d with dK. Explain why dense representations can be more effective for retrieval despite having fewer dimensions. Hint: consider the role of semantic smoothing.

  2. CLIP's zero-shot classification uses text prompts as class prototypes. Show that this is equivalent to nearest-centroid classification in the shared embedding space, and derive the decision boundary between two classes.

  3. The CLIP loss requires O(N2) similarity computations per batch. The SigLIP loss also requires O(N2) computations. Explain why SigLIP is nonetheless more efficient in distributed settings.

  4. Consider a retrieval system that uses DIFT features pooled over spatial dimensions. Explain why the choice of timestep t acts as a semantic/geometric tradeoff, and propose a multi-scale aggregation strategy.

Video Retrieval

Images are frozen moments; video is the flowing river of visual experience. The transition from image retrieval to video retrieval introduces a dimension that fundamentally changes the nature of the problem: time. A video is not merely a bag of frames but a structured temporal sequence in which actions unfold, objects interact, and narratives develop. Finding the right video in a large corpus is hard enough; finding the right moment within the right video is harder still.

This section develops the theory and practice of video retrieval, from adapting image-text models to the temporal domain through the challenging problems of moment retrieval and temporal grounding.

The Temporal Challenge

Definition 25 (Video Retrieval Problem).

Let 𝒱={V1,,VN} be a corpus of videos, where each video Vi consists of a sequence of frames Vi=(F1(i),F2(i),,FTi(i)) with Ti potentially varying across videos. Given a query q (which may be a text description, another video, or a combination), the video retrieval problem is to rank the corpus by relevance: (Video Retrieval)V^=arg maxV𝒱s(q,V), where s(q,V) is a learned similarity function.

What makes this fundamentally different from image retrieval? Consider the query “a person opens a gift and looks surprised.” No single frame captures this event; it unfolds across time. The act of opening involves hand motion and changing spatial relationships, while the surprise is expressed through a temporal sequence of facial expressions. A retrieval system must understand this temporal structure, which requires going beyond the frame-by-frame application of image features.

Formally, a video can be viewed as a function V:[0,T] from time to the space of images, and a video retrieval system must compute a similarity function s(q,V) that integrates information over this continuous (or discretely sampled) trajectory. The curse of dimensionality is severe: if a single image embedding has d dimensions, then naively representing T frames requires Td dimensions, and the space of possible temporal patterns grows combinatorially.

The key technical challenge is how to aggregate information across frames. Three dominant strategies have emerged:

  1. Mean pooling: compute a frame-level feature for each frame and average them: 𝒗=1Tt=1Tf𝜽(Ft). Simple but discards temporal order entirely.

  2. Temporal attention: use a transformer to attend across frame features, allowing the model to weight frames differently based on the query: 𝒗=Attn(𝒒,[f𝜽(F1),,f𝜽(FT)]).

  3. Temporal convolution / 3D CNN: process the video with spatiotemporal convolutions that jointly encode spatial and temporal patterns.

Example 14 (Why Single Frames Fail for Action Queries).

Consider the query “a person catches a ball.” A single frame showing a person with a ball nearby is ambiguous: the person could be about to throw the ball, could have just caught it, or could simply be standing near a ball on the ground. The semantics of “catches” require observing at least three frames: (i) the ball approaching, (ii) the hands closing around the ball, and (iii) the ball at rest in the hands. This temporal structure cannot be captured by any frame-level representation, no matter how powerful. Even CLIP, with its remarkable semantic understanding of individual images, fails on such queries when applied frame-by-frame, because the verb “catches” describes a temporal process, not a static visual pattern.

Lemma 3 (Information Loss Under Mean Pooling).

Let 𝒊1,,𝒊Td be frame embeddings and 𝒊=1Tt𝒊t be the mean-pooled video embedding. The information lost by mean pooling, measured by the sum of squared residuals, is: (MEAN POOL LOSS)t=1T𝒊t𝒊22=t=1T𝒊t22T𝒊22=T𝖵ar[𝒊t], where 𝖵ar[𝒊t]=1Tt𝒊t𝒊22 is the empirical variance of the frame embeddings. For videos with high visual diversity (e.g. action sequences with scene changes), this variance is large, and mean pooling discards significant information. For visually static videos (e.g. a talking head), the variance is small, explaining why mean pooling performs well on many benchmarks dominated by such content.

Caution.

Mean pooling is surprisingly competitive as a baseline. Babenko and Lempitsky showed that for many video retrieval tasks, the performance gap between simple mean pooling and sophisticated temporal models is smaller than the gap between different frame-level features. Before investing in complex temporal architectures, always benchmark against the mean-pooling baseline.

CLIP4Clip and ClipBERT: Adapting CLIP to Video

Given CLIP's remarkable success on image-text tasks, a natural question is: how do we extend it to video? The answer is not obvious, because CLIP was trained on individual images, not temporal sequences. Two influential approaches explored different strategies.

CLIP4Clip: temporal aggregation post-hoc.

Luo et al. [63] proposed CLIP4Clip, which uses CLIP's pre-trained image encoder to extract frame-level features and then aggregates them temporally. Three aggregation strategies are compared:

  1. Mean pooling: 𝒗=1Tt=1T𝒊t where 𝒊t=f𝜽CLIP(Ft).

  2. Temporal transformer: a lightweight transformer processes the sequence [𝒊1,,𝒊T] and outputs a single video embedding via a [CLS] token.

  3. Tight coupling: late interaction between frame tokens and text tokens via cross-attention.

Proposition 14 (Temporal Transformer Preserves Ordering Information).

Let 𝒊1,,𝒊T be frame embeddings with positional encodings 𝒑1,,𝒑T. The temporal transformer output 𝒊^t=TransformerBlock(𝒊t+𝒑t) satisfies: for any permutation π of {1,,T}, the output sequence 𝒊^π(1),,𝒊^π(T) differs from 𝒊^1,,𝒊^T (assuming non-degenerate positional encodings), enabling the model to distinguish temporal orderings. In contrast, mean pooling is permutation-invariant and cannot distinguish “person sits down then stands up” from “person stands up then sits down.”

ClipBERT: sparse sampling for efficiency.

Lei et al. [64] took a different approach with ClipBERT. Instead of processing all frames, ClipBERT randomly samples a small number of frames (typically 1–2) during training and applies a multimodal transformer for joint image-text reasoning. The key insight is that for many text-video retrieval queries, a single well-chosen frame contains sufficient information. This dramatically reduces computational cost and enables end-to-end fine-tuning of both visual and textual components.

Example 15 (CLIP4Clip on MSR-VTT).

On the MSR-VTT benchmark [10] with 1,000 test video-text pairs, CLIP4Clip with mean pooling achieves Recall@1 of 43.1%, while the temporal transformer variant achieves 44.5%, an improvement of only 1.4 percentage points. This modest gain suggests that for the typical MSR-VTT video (10–30 seconds of relatively simple content), temporal modelling provides limited benefit. However, on the ActivityNet benchmark, which contains longer videos (several minutes) with more complex temporal structure, the gap widens to 5–8 percentage points, confirming that temporal modelling matters most for content that genuinely requires multi-frame reasoning.

Remark 22 (Early vs. late fusion).

CLIP4Clip (with mean pooling or temporal transformer) exemplifies late fusion: visual and textual features are computed independently and combined only through a simple similarity computation. ClipBERT exemplifies early fusion: visual and textual tokens interact through cross-attention within a shared transformer. The tradeoff is fundamental:

  • Late fusion enables pre-computation of video embeddings for the entire corpus, making retrieval fast (O(N) dot products for a corpus of N videos).

  • Early fusion captures fine-grained interactions between visual and textual content but requires processing each query-video pair individually, making retrieval expensive (O(NT) transformer forward passes).

In practice, a common compromise is to use late fusion for an initial retrieval stage (selecting the top-K candidates) followed by early fusion for re-ranking.

Video retrieval pipeline with three temporal pooling strategies. Video frames are encoded independently using a pre-trained image encoder (e.g. CLIP), producing per-frame embeddings 𝒊1,,𝒊T. These are aggregated temporally via mean pooling, a temporal transformer, or cross-attention with the query. The video embedding 𝒗 is compared to the text query embedding 𝒕 via inner product.

Video Corpus Moment Retrieval

Standard video retrieval returns whole videos, but users often seek a specific moment: “the scene where the dog jumps into the lake” or “the moment the speaker mentions climate change.” This motivates video corpus moment retrieval (VCMR): given a natural language query q and a corpus of untrimmed videos 𝒱, find both the correct video V and the temporal segment [τs,τe] within it.

Definition 26 (Video Corpus Moment Retrieval).

Given a query q and a video corpus 𝒱, the video corpus moment retrieval problem seeks: (VCMR)(V,τs,τe)=arg maxV𝒱,0τs<τeTVsmoment(q,V,τs,τe), where smoment is a scoring function that measures the relevance of the temporal segment [τs,τe] in video V to the query q, and TV is the duration of video V.

VCMR is typically decomposed into two stages:

  1. Video retrieval: select a shortlist of candidate videos using a fast retrieval model.

  2. Temporal grounding: within each candidate video, localise the relevant temporal segment.

Temporal grounding.

The temporal grounding problem, also known as natural language video localisation [11][65], takes a single untrimmed video and a text query and predicts the start and end times of the described event. Three families of approaches exist:

  1. Proposal-based: generate a set of temporal proposals (candidate segments) and rank them by query relevance. This is analogous to region proposal networks in object detection.

  2. Proposal-free: directly regress the start and end times from a joint video-text representation. Given frame-level features 𝒉t attended by the query, predict: (Grounding Regression)τ^s=σ(𝒘s𝒉+bs),τ^e=σ(𝒘e𝒉+be), where 𝒉 is a query-conditioned video representation and σ maps to [0,1] (normalised time).

  3. Span-based: predict a score for every possible span (i,j) in a discretised timeline and select the highest-scoring span. The scoring function s(i,j)=𝒘[𝒉i;𝒉j;𝒉i𝒉j]+b captures interactions between start and end frame representations.

Definition 27 (Temporal Grounding Loss).

For a dataset of (q,V,τs,τe) tuples, the training objective for temporal grounding combines a localisation loss with a foreground/background classification loss. For span-based methods with discretised time into L segments, define the ground-truth span indicator yij=1 if the span [i,j] has IoU (temporal Intersection over Union) above a threshold θ with the ground-truth [τs,τe]: (Grounding LOSS)ground=1ijL[yijlogσ(s(i,j))+(1yij)log(1σ(s(i,j)))]+λreg(|τ^sτs|+|τ^eτe|), where the first term is the span classification loss and the second is a regression loss that refines the boundary predictions. The temporal IoU between predicted and ground-truth spans is: (Temporal IOU)tIoU=max(0,min(τ^e,τe)max(τ^s,τs))max(τ^e,τe)min(τ^s,τs).

Example 16 (Temporal Grounding in Instructional Videos).

Consider a 10-minute cooking video and the query “the chef adds salt to the boiling water.” The video contains many actions: chopping vegetables, boiling water, stirring, seasoning, plating. A temporal grounding model must identify the specific 3-second window where the salt-adding occurs. The difficulty is that “adding salt” is visually subtle (a small hand motion) and surrounded by visually similar actions (adding pepper, adding oil). The model must rely on cross-modal alignment between the word “salt” and the visual appearance of the salt container, combined with temporal context from the boiling water visible in the frame. State-of-the-art models achieve approximately 45% Recall@1 at tIoU 0.5 on such benchmarks, indicating significant room for improvement.

Temporal moment retrieval. Given a video and a natural language query, the model computes query-conditioned attention weights over video frames (bar chart), identifying the temporal segment [τ^s,τ^e] that best matches the query. Frames within the predicted segment (green) receive high attention, while irrelevant frames receive negligible weight.

Algorithm 5 (Video Corpus Moment Retrieval).

  1. Input: Text query q; video corpus 𝒱={V1,,VN}; retrieval model fret; grounding model fground; shortlist size K.

  2. Offline indexing (one-time): enumerate

  3. For each video Vi, extract frame features {𝒊t(i)}t=1Ti using a pre-trained encoder.

  4. Compute video-level embeddings 𝒗i=Aggregate(𝒊1(i),,𝒊Ti(i)).

  5. Build a retrieval index over {𝒗1,,𝒗N}. enumerate

  6. Online retrieval: enumerate

  7. Encode query: 𝒕=g𝝓(q).

  8. Retrieve top-K videos: 𝒮=TopKVi(𝒗i,𝒕,K).

  9. For each Vi𝒮, apply temporal grounding: (τ^s(i),τ^e(i))=fground(q,Vi).

  10. Score each candidate: si=λ𝒗i,𝒕+(1λ)sground(q,Vi,τ^s(i),τ^e(i)).

  11. Return: (V,τ^s,τ^e)=arg maxVi𝒮si. enumerate

  12. Output: The video and temporal segment most relevant to the query.

Remark 23 (The training data challenge).

Training temporal grounding models requires annotations that specify the start and end times of events described by text queries. Several benchmarks provide such annotations:

  • MSR-VTT [10]: 10,000 video clips with 200,000 clip-sentence pairs, primarily for video-text retrieval (clip-level, not moment-level).

  • ActivityNet Captions: 20,000 YouTube videos with temporally localised captions, suitable for both video retrieval and temporal grounding.

  • DiDeMo [11]: 10,000 Flickr videos with 40,000 temporally grounded text descriptions, where each description is localised to one of five 5-second segments.

The limited scale of these datasets relative to the complexity of video understanding remains a significant bottleneck. Recent work has explored leveraging large-scale video-text data (e.g. from instructional videos and movie scripts) with weak temporal supervision [12].

Multimodal Fusion for Video Understanding

Video retrieval often benefits from multiple modalities beyond visual frames: audio, speech transcripts, optical character recognition (OCR), and metadata. How these modalities are combined determines both the quality and efficiency of the retrieval system.

Definition 28 (Multimodal Fusion Strategies).

Given feature sequences from M modalities {𝒙t(m)}t,m and a query 𝒒, the three canonical fusion strategies are:

  1. Early fusion: concatenate features from all modalities before temporal modelling: (Early Fusion)𝒛t=[𝒙t(1);𝒙t(2);;𝒙t(M)],𝒗=TemporalModel(𝒛1,,𝒛T).

  2. Late fusion: compute modality-specific embeddings independently and combine the similarity scores: (LATE Fusion)s(q,V)=m=1Mwmf(m)(V),g(m)(q), where wm are learned or fixed modality weights.

  3. Cross-attention fusion: allow features from different modalities to attend to each other through transformer cross-attention layers: (Cross Fusion)𝒙^t(m)=𝒙t(m)+mmCrossAttn(𝒙t(m),𝐗(m),𝐗(m)), where 𝐗(m)=[𝒙1(m),,𝒙T(m)].

Proposition 15 (Expressiveness Hierarchy of Fusion Strategies).

Let early, late, and cross denote the function classes realisable by early fusion, late fusion, and cross-attention fusion, respectively. Under standard transformer architectures: (Fusion Hierarchy)lateearlycross. Late fusion is strictly less expressive because the independence of modality-specific encoders prevents capturing cross-modal interactions. Early fusion via concatenation can in principle capture all interactions but may struggle to learn them efficiently when modalities have very different statistical properties. Cross-attention provides explicit pathways for cross-modal interaction while preserving modality-specific processing.

Recent models such as Flamingo [66] have shown that cross-attention fusion between a frozen visual encoder and a frozen language model, mediated by learned gating mechanisms, can achieve strong video understanding performance with minimal trainable parameters.

Example 17 (Choosing Fusion Strategy for a Video Search Engine).

Consider building a video search engine for a streaming platform with 10 million videos. The system must handle 1,000 queries per second with sub-200ms latency. Late fusion is the only viable option for the first-stage retrieval: pre-compute video embeddings offline and perform approximate nearest-neighbour search at query time. For re-ranking the top 100 candidates, cross-attention fusion becomes feasible: 100×5ms=500ms per query, which can be parallelised across GPUs to meet the latency target. The combined system achieves 85% of the quality of full cross-attention fusion (applied to all 10 million videos) at 0.001% of the computational cost. This two-stage design pattern, cheap retrieval followed by expensive re-ranking, is ubiquitous in production retrieval systems across all modalities.

Historical Note.

The convergence of vision and language. The trajectory from SIFT to CLIP represents one of the most dramatic paradigm shifts in computer vision history. In the 2000s, vision and language were separate research communities with distinct conferences, methods, and evaluation protocols. The bag of visual words model built the first bridge, borrowing text retrieval machinery for image search. In the 2010s, CNN features trained with visual-only supervision dominated both communities. The transformer architecture, originating in NLP (2017), was adapted to vision as the Vision Transformer (2020), creating architectural unity. CLIP (2021) completed the convergence by training a single model on both modalities simultaneously, proving that natural language supervision produces visual representations superior to those learned from visual data alone. Today, the boundary between “vision” and “language” research has largely dissolved, replaced by the unified field of multimodal learning.

Exercise 29 (Video Retrieval Systems).

  1. A video corpus contains 100,000 videos, each 5 minutes long, sampled at 1 frame per second. If the CLIP image encoder produces 512-dimensional features and takes 5ms per frame, estimate the total time and storage for offline indexing under (a) mean pooling and (b) storing all per-frame features.

  2. In the VCMR problem, explain why the two-stage approach (retrieve then ground) is more practical than a single-stage approach that scores all possible moments across all videos. Estimate the computational complexity of each.

  3. The DiDeMo benchmark discretises time into 5-second segments. Show that with K segments per video, the number of possible temporal proposals is K(K+1)/2 and argue that this makes span-based grounding tractable.

  4. Design a hybrid fusion strategy that uses late fusion for initial retrieval and cross-attention fusion for re-ranking. Specify the architecture and analyse the computational tradeoff compared to pure late fusion and pure cross-attention.

  5. Consider extending DIFT features (from Diffusion Features for Retrieval) to video. Propose a method that extracts diffusion features from a video diffusion model and uses them for video retrieval. What new challenges arise from the temporal dimension?

Research 1 (Open Problems in Video Retrieval).

Several fundamental challenges remain open:

  1. Long-form video understanding: current models struggle with videos longer than a few minutes. Handling hour-long videos (movies, lectures) requires hierarchical representations that can summarise content at multiple temporal scales.

  2. Compositional temporal queries: queries like “first A happens, then B, and finally C” require understanding temporal order and composition, which current models handle poorly.

  3. Interactive retrieval: allowing users to refine queries based on initial results (“similar to this but outdoors”) requires models that can perform incremental updates to the query representation.

  4. Efficiency at scale: video corpora such as YouTube contain billions of videos. Achieving sub-second retrieval at this scale while maintaining moment-level granularity remains an engineering and algorithmic challenge.

  5. Audio-visual alignment: many moments in video are best identified by their audio (a dog barking, a crowd cheering). Integrating audio features into the retrieval pipeline in a way that complements rather than duplicates visual information remains an active area of research.

Key Idea.

The progression from image retrieval to video retrieval mirrors a fundamental shift in AI from static pattern matching to temporal reasoning. Image retrieval asks “what is this?”, while video retrieval asks “what is happening?” The former can be solved by comparing spatial feature distributions; the latter requires understanding how visual patterns evolve over time. This temporal dimension connects video retrieval to broader challenges in AI: action recognition, event detection, narrative understanding, and ultimately the ability to comprehend the dynamic visual world that humans navigate effortlessly. The tools developed in this section, including temporal attention, moment retrieval, and multimodal fusion, are not merely engineering solutions to a retrieval problem; they are steps toward AI systems that understand time itself.

Speech Retrieval

Imagine trying to find a specific conversation in 10,000 hours of recorded meetings. You remember a colleague mentioning a particular budget figure, perhaps in the context of a quarterly review, but you cannot recall when the meeting took place, who else was present, or even the exact words that were used. Scrolling through recordings at real-time speed would take more than a year of continuous listening. This is the problem of spoken document retrieval: searching through vast archives of speech to find relevant passages, a problem that sits at the intersection of speech processing, information retrieval, and, increasingly, self-supervised representation learning.

The challenge is fundamentally harder than text retrieval. Speech is temporally extended, ambiguous (homophones, disfluencies, accents), and lacks the convenient discrete token structure of written language. A single word in text occupies a handful of bytes; the same word in speech occupies hundreds of milliseconds of high-dimensional audio signal. Moreover, speech carries information absent from text, including speaker identity, emotion, emphasis, and prosody, all of which may be relevant to the retrieval task but are difficult to index.

This section traces the evolution of speech retrieval from classical template-matching techniques through statistical models to the modern revolution brought about by self-supervised speech representations and large-scale weakly supervised ASR systems. Along the way, we will see a recurring theme: the tension between approaches that convert speech to text (sacrificing paralinguistic information for the sake of mature text retrieval infrastructure) and approaches that work directly with audio representations (preserving the full acoustic signal at the cost of less interpretable matching). Understanding this tension is essential for designing effective speech retrieval systems, as the optimal choice depends heavily on the application domain, language resources, and query types.

Dynamic Time Warping for Template Matching

The earliest approaches to speech retrieval were based on template matching: given a spoken query (a recording of the word or phrase to be found), slide it along the audio archive and measure similarity at each position. The fundamental obstacle is that the same word spoken twice, even by the same speaker, will have different durations. The vowel in “cat” might last 80,ms in one utterance and 120,ms in another. Simple Euclidean distance between the two feature sequences will fail catastrophically because corresponding frames are misaligned.

Dynamic Time Warping (DTW), introduced by Sakoe and Chiba [67], solves this problem by finding an optimal nonlinear alignment between two sequences that minimises the total matching cost.

Definition 29 (Dynamic Time Warping Distance).

Let 𝒙=(𝒙1,,𝒙N) and 𝒚=(𝒚1,,𝒚M) be two sequences of feature vectors in d. A warping path is a sequence p=((i1,j1),(i2,j2),,(iK,jK)) satisfying three constraints:

  1. Boundary: (i1,j1)=(1,1) and (iK,jK)=(N,M).

  2. Monotonicity: ik+1ik and jk+1jk for all k.

  3. Step size: (ik+1ik,jk+1jk){(1,0),(0,1),(1,1)} for all k.

The DTW distance is the cost of the optimal warping path: (DTW)DTW(𝒙,𝒚)=minp𝒫k=1Kc(𝒙ik,𝒚jk), where 𝒫 is the set of all valid warping paths and c:d×d0 is a local cost function, typically the squared Euclidean distance c(𝒂,𝒃)=𝒂𝒃2.

The DTW distance can be computed efficiently by dynamic programming. Define the cumulative cost matrix DN×M by the recurrence (DTW Recurrence)D(i,j)=c(𝒙i,𝒚j)+min{D(i1,j)(insertion)D(i,j1)(deletion)D(i1,j1)(match), with boundary conditions D(1,1)=c(𝒙1,𝒚1), and D(i,0)=D(0,j)= for all i,j1. The DTW distance is then DTW(𝒙,𝒚)=D(N,M), and the optimal warping path can be recovered by backtracking through the matrix.

Proposition 16 (DTW Computational Complexity).

Computing DTW(𝒙,𝒚) for sequences of length N and M with d-dimensional features requires 𝒪(NMd) time and 𝒪(NM) space. With the Sakoe–Chiba band constraint of width w, this reduces to 𝒪(Nwd) time and 𝒪(Nw) space.

Proof.

Each cell (i,j) of the cumulative cost matrix requires computing the local cost c(𝒙i,𝒚j) in 𝒪(d) time and a three-way minimum in 𝒪(1) time. The full matrix has NM cells, giving 𝒪(NMd) total time. The Sakoe–Chiba band restricts computation to cells satisfying |iM/Nj|w, reducing the number of active cells to 𝒪(Nw).

DTW alignment path visualisation. The grid represents the cumulative cost matrix D(i,j); the highlighted path traces the optimal warping alignment between a query sequence 𝒙 and a template sequence 𝒚. The Sakoe–Chiba band (shaded region) constrains the search to cells near the diagonal, reducing complexity from 𝒪(NM) to 𝒪(Nw). Cells outside the band (grey) are never evaluated. The non-diagonal segments of the path correspond to local time stretching or compression in the speech signal.

For spoken term detection, DTW is applied in a subsequence variant: rather than aligning two complete sequences, we search for the query pattern within a longer audio stream. This requires modifying the boundary conditions so that the alignment can begin at any position in the reference sequence, converting the problem from global alignment to local alignment.

Lemma 4 (Subsequence DTW Boundary Conditions).

For subsequence DTW, where a query 𝒙 of length N is to be detected within a reference 𝒚 of length MN, the boundary conditions are modified to: (SUB DTW INIT)D(0,j)=0for all j{0,1,,M},D(i,0)=for all i{1,,N}. The optimal detection score is minjD(N,j), and the corresponding alignment endpoint j=arg minjD(N,j) marks the end of the detected segment. The start point is recovered by backtracking from (N,j) through the cumulative cost matrix. This formulation allows the query to match at any position within the reference, with a computational cost identical to standard DTW but with fundamentally different semantics: the optimisation finds the best matching segment rather than the best global alignment.

Remark 24.

DTW was the dominant approach to speech recognition before the statistical revolution of the 1980s. Its strength is simplicity and the ability to work with very little training data (a single template suffices). Its weakness is computational cost: searching for a 1-second query in 10,000 hours of audio at 100 frames per second requires evaluating approximately 3.6×1011 DTW cells, making brute-force search impractical for large archives. This motivated the development of statistical approaches and, eventually, learned representations that enable sublinear search.

HMMs for Keyword Spotting

The statistical revolution in speech processing, beginning in the late 1970s and reaching maturity in the 1990s, replaced template matching with probabilistic models. The Hidden Markov Model (HMM) [68] became the workhorse of speech recognition and, by extension, keyword spotting and spoken term detection.

The key idea is to model each word (or phoneme) as a Markov chain over hidden states, where each state emits acoustic feature vectors according to a probability distribution, typically a Gaussian Mixture Model (GMM). A keyword spotter [69] trains HMMs for the keywords of interest and a filler model that captures all non-keyword speech, then runs a Viterbi decoder to find the most likely state sequence through the combined keyword-filler model.

Definition 30 (HMM for Keyword Spotting).

A keyword-spotting HMM consists of:

  1. A set of keyword HMMs {λw}w𝒱, where 𝒱 is the keyword vocabulary, each parameterised by transition probabilities 𝐀w, emission distributions {bw,s}s=1Sw, and initial state distribution 𝝅w.

  2. A filler HMM λfill trained on general speech to model non-keyword segments.

  3. A network topology that allows transitions between keyword and filler models: P(𝒙1:T)=max𝐪t=1Taqt1qtbqt(𝒙t), where 𝐪=(q1,,qT) is the state sequence through the combined model, aqt1qt are transition probabilities, and bqt(𝒙t) is the emission probability of feature vector 𝒙t in state qt.

A keyword detection at time t is declared when the likelihood ratio logP(𝒙t:t|λw)logP(𝒙t:t|λfill) exceeds a threshold η.

Key Idea.

From templates to probabilities. The transition from DTW-based template matching to HMM-based keyword spotting mirrors a deeper paradigm shift in speech processing. DTW asks: “How well does this audio segment match a stored template?” The HMM asks: “How likely is this audio segment under a statistical model of the keyword?” The probabilistic framing provides three advantages: (1) it naturally handles variability across speakers and speaking styles through the emission distributions; (2) it provides a principled detection criterion (likelihood ratio); and (3) it enables training from large corpora, improving with more data rather than requiring careful template selection.

DTW-Based Spoken Term Detection

Despite the dominance of HMM-based approaches, DTW experienced a renaissance in the 2000s for query-by-example spoken term detection (QbE-STD), where the query is itself a spoken utterance rather than a text string. This setting is particularly relevant for low-resource languages where training HMMs or ASR systems is infeasible due to lack of transcribed data.

Algorithm 6 (DTW-Based Spoken Term Detection).

  1. Input: Query audio 𝒙q=(𝒙1q,,𝒙Nq); archive audio segments {𝒙(k)}k=1K; local cost function c; detection threshold η; Sakoe–Chiba band width w
  2. Output: Set of detections 𝒟={(k,ts,te,s)} with segment index, start time, end time, and score
  3. Extract features: 𝒙qMFCC(𝒙q) Mel-frequency cepstral coefficients
  4. for each archive segment k=1,,K
  5. Extract features: 𝒙(k)MFCC(𝒙(k))
  6. Initialise subsequence DTW matrix D
  7. for i=1,,N
  8. for j=max(1,iMk/Nw),,min(Mk,iMk/N+w)
  9. D(i,j)c(𝒙iq,𝒙j(k))+min{D(i1,j),D(i,j1),D(i1,j1)}
  10. skminjD(N,j)/N Normalised DTW score
  11. if sk<η
  12. Backtrack to find alignment boundaries (ts,te)
  13. 𝒟𝒟{(k,ts,te,sk)}
  14. return 𝒟 sorted by score (ascending)

Algorithm 6 uses subsequence DTW, where the boundary condition on the reference sequence is relaxed: D(0,j)=0 for all j, allowing the alignment to begin at any position in the archive. The normalisation by query length N ensures that scores are comparable across queries of different durations.

Self-Supervised Speech Representations

The most transformative development in speech retrieval over the past five years has been the emergence of self-supervised speech representations. These models learn rich, general-purpose representations from unlabelled speech, eliminating the need for expensive transcription and enabling high-quality retrieval even in languages with minimal labelled resources.

The core insight is borrowed from the success of masked language modelling in NLP: if a model can learn to predict missing parts of a speech signal from context, it must develop internal representations that capture phonetic, linguistic, and even semantic structure. Three models stand out as landmarks in this progression.

wav2vec 2.0: contrastive learning on speech.

The wav2vec 2.0 model [70] introduced a two-stage architecture that combines convolutional feature extraction with transformer-based contextual modelling and a contrastive learning objective. The architecture operates as follows.

A multi-layer CNN feature encoder fenc:TL×d processes raw audio waveform 𝒙T (sampled at 16,kHz) and produces a sequence of latent representations 𝒛1,,𝒛L, where each 𝒛 corresponds to approximately 25,ms of audio with a stride of 20,ms. A quantisation module q:d𝒬 discretises each latent vector into one of |𝒬| codebook entries, producing quantised targets 𝒛^=q(𝒛). A transformer encoder g𝜽:L×dL×d processes the (partially masked) latent sequence and produces contextualised representations 𝒄1,,𝒄L.

The training objective combines a contrastive loss with a diversity penalty: (Wav2vec2 LOSS)w2v2=logexp(sim(𝒄,𝒛^)/κ)j=1|𝒩|exp(sim(𝒄,𝒛~j)/κ)+αdiv, where is the set of masked positions, sim(𝒂,𝒃)=𝒂𝒃/(𝒂𝒃) is cosine similarity, κ is a temperature parameter, 𝒩 contains the true quantised target 𝒛^ plus K distractors sampled from other masked positions, and div encourages uniform use of the codebook entries.

The wav2vec 2.0 architecture. Raw audio is processed by a CNN feature encoder to produce latent representations, which are both quantised (to produce targets) and masked (to produce input for the transformer). The transformer produces contextualised representations 𝒄, and the contrastive loss trains the model to identify the correct quantised target 𝒛^ from a set of distractors. This self-supervised objective encourages the model to learn representations that capture phonetic and linguistic structure without any labelled data.

The representations learned by wav2vec 2.0 are remarkably effective for speech retrieval. By extracting frame-level embeddings 𝒄1,,𝒄L from the transformer layers and pooling them (via mean pooling or attention-based aggregation), one obtains utterance-level representations that capture both acoustic and linguistic content. These representations can then be indexed and searched using the approximate nearest-neighbour techniques developed in earlier sections of this chapter.

HuBERT: masked prediction of pseudo-labels.

While wav2vec 2.0 uses a contrastive objective with learned quantisation targets, HuBERT [71] (Hidden-Unit BERT) takes a different approach: it performs masked prediction against offline-discovered pseudo-labels. The training proceeds in iterations:

  1. Cluster: Apply k-means clustering to MFCC features (first iteration) or to representations from the previous model (subsequent iterations) to produce frame-level pseudo-labels z{1,,C}.

  2. Predict: Train a transformer model to predict the pseudo-label z at masked positions from the unmasked context, using a cross-entropy loss: (Hubert LOSS)HuBERT=logP(z|𝒙\;𝜽), where is the set of masked positions and 𝒙\ denotes the unmasked input.

  3. Iterate: Use the trained model's representations to generate better pseudo-labels for the next iteration.

The iterative refinement is key: initial pseudo-labels from MFCC clustering are crude, capturing only basic acoustic properties. But as the model improves, its representations yield increasingly linguistically meaningful clusters, which in turn provide better training targets. This bootstrapping process converges to representations that rival or exceed those of wav2vec 2.0 on downstream tasks.

WavLM: speech processing across the full stack.

WavLM [72] builds on HuBERT's masked prediction framework but adds denoising objectives that make the learned representations robust to noise, reverberation, and overlapping speakers. During training, the input audio is augmented by mixing with noise and other utterances, while the prediction targets remain the clean pseudo-labels. This forces the model to learn representations that are invariant to acoustic degradation, a critical property for retrieval in real-world conditions where recordings are rarely studio-quality.

WavLM additionally benefits from a gated relative position bias in its transformer architecture, which provides more flexible modelling of temporal dependencies than absolute position embeddings.

Theorem 5 (Denoising Objective as Contrastive Learning).

Let 𝒙~ denote a corrupted version of audio 𝒙, obtained by mixing with noise 𝒏 at signal-to-noise ratio SNR: 𝒙~=𝒙+α𝒏 where α=10SNR/20. Let z denote the pseudo-label for frame derived from the clean signal. The WavLM denoising objective denoise=logP(z|𝒙~\;𝜽) implicitly learns a representation h𝜽(𝒙~) such that for any noise realisation 𝒏, h𝜽(𝒙+α𝒏)h𝜽(𝒙)ϵ(SNR), where ϵ(SNR)0 as SNR. In other words, the denoising objective produces representations that are Lipschitz continuous with respect to additive noise, with the Lipschitz constant decreasing as the noise level decreases.

This noise robustness is critical for speech retrieval in real-world settings: meeting recordings contain air conditioning hum, keyboard clicks, and cross-talk; field recordings suffer from wind noise and equipment handling; phone calls are degraded by codec compression and network jitter. Models trained with denoising objectives produce stable embeddings under all these conditions, enabling retrieval systems that work reliably outside the laboratory.

ModelParametersPre-training DataObjectiveKey Innovation
wav2vec 2.0317M960h (LS) / 60kh (LV)ContrastiveLearned quantisation
HuBERT316M960h (LS) / 60kh (LV)Masked predictionIterative pseudo-labels
WavLM316M960h (LS) / 94kh (mix)Masked predictionDenoising augmentation
Comparison of self-supervised speech representation models. Pre-training data sizes and objectives differ significantly, yet all three produce representations that dramatically outperform traditional acoustic features (MFCCs, filterbanks) for speech retrieval tasks. Parameters listed are for the “Large” configuration of each model.

Whisper: Universal ASR via Weak Supervision

A fundamentally different approach to speech retrieval is to transcribe the speech into text and then apply standard text retrieval techniques. The viability of this approach depends entirely on the quality of the automatic speech recognition (ASR) system. For decades, ASR errors propagated catastrophically into the retrieval pipeline, degrading recall by 20–40% relative to retrieval on manual transcriptions. Whisper [73] changed this calculus.

Whisper is a sequence-to-sequence transformer trained on 680,000 hours of weakly supervised audio-transcript pairs collected from the internet. The key insight is scale over curation: rather than training on a small, carefully transcribed dataset, Whisper trains on a massive, noisy dataset and relies on the model's capacity to learn robust transcription despite label noise.

The architecture follows a standard encoder-decoder transformer. The audio encoder processes log-mel spectrograms (80 channels, computed from 25,ms windows with a 10,ms stride) through a stack of transformer blocks with sinusoidal position embeddings. The text decoder autoregressively generates tokens conditioned on the encoder outputs and previously generated tokens. Special tokens control language identification, timestamp prediction, and translation.

The scale of Whisper's training is worth emphasising. The 680,000 hours of audio span 99 languages, collected by filtering internet audio-transcript pairs for quality using heuristic alignment checks. The largest model configuration (Whisper Large V3) uses 1.55 billion parameters with a 32-layer encoder and 32-layer decoder, each with 1,280-dimensional hidden states and 20 attention heads. Training was performed on a cluster of GPUs for multiple weeks, a brute-force investment in scale that, combined with the massive and diverse dataset, produced a model with remarkable robustness to accents, background noise, and domain shifts. For retrieval purposes, this robustness translates directly to transcript quality: fewer ASR errors mean less information loss in the transcribe-then-retrieve pipeline.

Definition 31 (Whisper Transcription for Retrieval).

Given a speech archive 𝒜={a1,,aK} and a text query q, the Whisper-based retrieval pipeline operates in two phases:

  1. Offline indexing: For each audio document ak, compute transcript tk=Whisper(ak) and index tk using a standard text retrieval system (BM25, dense retrieval, etc.).

  2. Online query: Retrieve documents by matching query q against the transcript index: Retrieve(q)=arg maxk{1,,K}score(q,tk).

When the query is itself spoken, an additional ASR step transcribes the query: qtext=Whisper(qaudio).

The effectiveness of Whisper-based retrieval stems from the model's remarkable robustness. Whisper achieves near-human word error rates across a wide range of accents, noise conditions, and domains, making the transcribe-then-retrieve pipeline competitive with (and often superior to) direct acoustic retrieval for languages where Whisper performs well.

Remark 25.

The transcribe-then-retrieve approach has a fundamental limitation: it discards all paralinguistic information. A query like “find the meeting where someone sounded angry about the budget” cannot be answered from transcripts alone. This limitation motivates hybrid approaches that combine ASR transcripts with acoustic embeddings, preserving both lexical and paralinguistic content in the index.

Spoken Document Retrieval: Architectures Compared

With all these components in hand, we can now compare the two main architectural paradigms for spoken document retrieval.

The ASR-based pipeline transcribes audio into text and applies text retrieval. Its strengths are modularity (any ASR system can be combined with any text retrieval system), interpretability (users can see the transcripts and understand why a document was retrieved), and the ability to leverage decades of progress in text retrieval. Its weakness is error propagation: ASR errors, particularly on named entities, technical terms, and code-switched speech, directly degrade retrieval performance.

The embedding-based pipeline maps both audio and queries directly into a shared embedding space, bypassing transcription entirely. Self-supervised models like wav2vec 2.0, HuBERT, or WavLM produce fixed-dimensional embeddings that capture acoustic and linguistic content. Retrieval is performed by nearest-neighbour search in embedding space. This approach is robust to ASR errors (there is no ASR step to produce errors), works for any language (no language-specific training required), and preserves paralinguistic information. Its weakness is the loss of fine-grained lexical information: embedding-based retrieval may miss exact keyword matches that BM25 would catch.

Comparison of the two main spoken document retrieval architectures. (a) The ASR-based pipeline transcribes speech using a system like Whisper, then applies standard text retrieval (BM25, dense retrieval) on the transcripts. (b) The embedding-based pipeline encodes speech directly into a vector space using self-supervised models, then performs approximate nearest-neighbour (ANN) search. The ASR-based approach benefits from mature text retrieval infrastructure but suffers from error propagation. The embedding-based approach avoids transcription errors and preserves paralinguistic information but may miss exact lexical matches.

In practice, the best systems often combine both paradigms. A hybrid retrieval system might use BM25 on Whisper transcripts for initial candidate generation (leveraging exact keyword matching), then re-rank using embedding similarity from a self-supervised speech model (incorporating acoustic and semantic information). This two-stage architecture captures the strengths of both approaches while mitigating their individual weaknesses.

Historical Note.

The TREC Spoken Document Retrieval (SDR) track, held from 1997 to 2000, was the first systematic evaluation of spoken document retrieval systems. The task was to retrieve relevant segments from a corpus of broadcast news recordings in response to text queries. The surprising finding was that even with 1990s-era ASR systems producing word error rates of 25–35%, retrieval performance degraded only modestly compared to retrieval on perfect transcripts. This robustness was attributed to the redundancy of natural language: even when ASR corrupts some words, enough correct terms survive to support effective retrieval via TF-IDF matching. The TREC SDR results shaped the field's trajectory for two decades, establishing the transcribe-then-retrieve paradigm as the dominant approach and demonstrating that speech retrieval was “essentially a solved problem” for broadcast news. It took the demands of more challenging domains, including conversational speech, low-resource languages, and multi-speaker meetings, to reveal the limitations of this paradigm and motivate the embedding-based approaches that now complement it.

Example 18 (Hybrid Speech Retrieval System).

Consider a corporate meeting archive containing 50,000 hours of recordings. A hybrid retrieval system operates as follows:

  1. Offline processing: itemize

  2. Transcribe all meetings using Whisper (large-v3), producing timestamped transcripts.

  3. Segment transcripts into passages of approximately 200 words, respecting speaker turn boundaries.

  4. Index passages with BM25 and compute dense embeddings using a WavLM-based utterance encoder. itemize

  5. Online retrieval: Given query q: itemize

  6. Retrieve top-100 passages by BM25 score on transcripts.

  7. Retrieve top-100 passages by cosine similarity of WavLM embeddings.

  8. Merge candidate sets and re-rank using a cross-encoder that attends to both transcript text and audio features. itemize

  9. Output: Return ranked list of meeting segments with timestamps, speaker labels, and transcript excerpts.

The hybrid system recovers from ASR errors on technical jargon (caught by the embedding retriever) while maintaining precision on named entities (caught by the text retriever).

Proposition 17 (Error Propagation in ASR-Based Retrieval).

Let WER denote the word error rate of the ASR system, and assume errors are uniformly distributed across word positions. For a BM25-style retrieval function where the score depends on the presence of query terms in the document, the expected recall loss from ASR errors is bounded by (ASR Recall LOSS)𝔼[RecallASR]Recallperfect(1WER)|q|, where |q| is the number of query terms. For a query with |q|=5 terms and WER=0.15, the expected recall is at least 0.8550.44 of the perfect-transcript recall. This exponential degradation in query length explains why ASR-based retrieval is particularly vulnerable on long, specific queries, while short queries with common terms remain robust.

Exercise 30 (DTW Complexity Analysis).

Consider a query-by-example spoken term detection system operating on an archive of H hours of audio, with features extracted at a rate of F frames per second.

  1. If the query has duration τ seconds, what is the total number of DTW cells evaluated in a brute-force search (without band constraint)?

  2. Derive the speedup factor from applying a Sakoe–Chiba band of width w=0.1Fτ (10% of the query length).

  3. If each DTW cell evaluation takes d floating-point operations (for d-dimensional features), and the hardware can perform 1012 FLOPS, how long would the brute-force search take for H=10,000 hours, F=100, τ=1 second, and d=39 (standard MFCC dimensionality)?

  4. Propose a two-stage approach that reduces search time by orders of magnitude while maintaining high recall.

Exercise 31 (Self-Supervised Representations for Retrieval).

Suppose you are building a spoken document retrieval system for a low-resource language with only 10 hours of transcribed data but 100,000 hours of untranscribed recordings.

  1. Explain why the ASR-based pipeline is unlikely to work well in this setting.

  2. Describe how you would use wav2vec 2.0 or HuBERT representations for embedding-based retrieval.

  3. The self-supervised model was pre-trained on English. Discuss the transfer learning challenges for a typologically different language (e.g., a tonal language like Mandarin or a polysynthetic language like Inuktitut).

  4. Propose a fine-tuning strategy that uses the 10 hours of labelled data to improve retrieval performance beyond the zero-shot baseline.

Music Information Retrieval

You are in a coffee shop when a song begins playing through the speakers, something you have heard before but cannot quite place. You pull out your phone, open an app, hold it up for a few seconds, and within moments the screen displays the song title, artist, and album art. This act, so casual that it barely registers as remarkable, depends on one of the most elegant algorithms in all of computer science: audio fingerprinting. More broadly, it exemplifies the field of Music Information Retrieval (MIR), which encompasses the computational analysis of, search through, and recommendation of music.

This section explores three facets of music retrieval: exact identification (“What song is this?”), similarity-based search (“Find songs that sound like this one”), and the modern integration of music with language models.

Audio Fingerprinting: The Shazam Algorithm

The Shazam algorithm, published by Wang [74], solves a needle-in-a-haystack problem: given a short, noisy recording captured through a phone's microphone in a crowded environment, identify the exact song from a database of millions of tracks. The solution is based on three key ideas: spectral peak extraction, combinatorial hashing, and hash-table lookup.

Definition 32 (Audio Fingerprint).

Given an audio signal x(t), an audio fingerprint is a compact, content-based signature Φ(x)={h1,h2,,hM} satisfying three properties:

  1. Discriminability: Different songs produce different fingerprints with high probability: P(Φ(x)Φ(y)|xy)δ for a small error tolerance δ.

  2. Robustness: The fingerprint is invariant to common distortions (background noise, reverberation, dynamic range compression, minor pitch shifts): Φ(distort(x))Φ(x).

  3. Compactness: Each hash hi is a fixed-length bit string (typically 32 bits), enabling efficient storage and lookup in a hash table.

The Shazam algorithm constructs fingerprints through a process that is best understood as building a constellation map of the audio signal's time-frequency structure.

Step 1: Spectrogram computation.

Compute the short-time Fourier transform (STFT) of the audio signal, producing a spectrogram S(t,f)=|X(t,f)|2, where X(t,f) is the STFT coefficient at time frame t and frequency bin f.

Step 2: Peak extraction.

Identify spectral peaks: time-frequency points (ti,fi) where the spectrogram energy is a local maximum, exceeding the energy of all neighbouring points within a region of size Δt×Δf. These peaks are remarkably robust to noise and distortion because they correspond to the dominant resonances in the audio signal, which persist even when the signal is degraded.

Step 3: Constellation map.

The set of all spectral peaks 𝒞={(t1,f1),(t2,f2),,(tP,fP)} forms the constellation map. This map is a sparse representation of the audio signal that discards most of the spectrogram energy and retains only the structural skeleton.

Step 4: Combinatorial hashing.

For each anchor point (ta,fa) in the constellation map, select nearby points (tb,fb) within a target zone {(t,f):ta+tmintta+tmax,fminffmax} and form a hash: (Shazam HASH)h=hash(fa,fb,tbta). The hash encodes the frequencies of the anchor and target peaks and their time difference. Each hash is stored in a hash table along with the song identifier and the anchor time ta: table[h]table[h]{(song_id,ta)}.

Shazam's constellation map and fingerprinting process. Spectral peaks (dots) form a sparse representation of the audio spectrogram. For each anchor point (orange), peaks within the target zone (dashed box) are paired to form hashes that encode the anchor frequency, target frequency, and time difference. These hashes, being based on robust spectral peaks rather than raw amplitude values, survive noise, reverberation, and transmission distortions.
Step 5: Matching and verification.

Given a query recording, the same process is applied to extract query hashes Φ(q). Each query hash is looked up in the hash table to retrieve candidate matches. A true match produces a coherent time offset: if the query was captured starting at time t0 in the original song, then all matching hashes should satisfy tasongtaqueryt0. The song with the most coherent matches (the largest peak in the histogram of time offsets) is returned as the identification.

Algorithm 7 (Audio Fingerprint Matching).

  1. Input: Query audio q; hash table mapping hashes to (song_id,ta) pairs; minimum match count μ
  2. Output: Identified song or (no match)
  3. Compute spectrogram SqSTFT(q)
  4. Extract peaks: 𝒞qPeakPick(Sq)
  5. Generate hashes: ΦqHashPairs(𝒞q) Anchor-target pairs
  6. Initialise offset histograms: hist[][]0
  7. for each (h,taq)Φq
  8. for each (id,tas)[h]
  9. Δttastaq Time offset
  10. hist[id][Δt]+=1
  11. (id,Δt)arg maxid,Δthist[id][Δt]
  12. if hist[id][Δt]μ
  13. return id
  14. else
  15. return No confident match

The elegance of Algorithm 7 lies in its 𝒪(1) hash-table lookups: for each query hash, the lookup returns a small set of candidate matches, and the time-offset histogram aggregates evidence across all query hashes to identify the correct song. The entire process typically completes in under one second for a database of millions of songs.

Remark 26.

The hash function in (Shazam HASH) encodes three quantities: two frequencies and a time difference. The frequencies provide spectral discrimination (different instruments and notes produce peaks at different frequencies), while the time difference provides temporal discrimination (different rhythmic patterns produce different inter-peak timings). The choice to use pairs of peaks rather than individual peaks is critical: a single peak at frequency f is far too common to be discriminative (thousands of songs may have energy at 440,Hz), but a pair of peaks at frequencies fa and fb separated by time Δt is far more specific. This combinatorial structure is what makes the fingerprint both robust (peaks survive noise) and discriminative (peak pairs are rare enough to identify specific songs).

Proposition 18 (Fingerprint Collision Probability Bound).

Let each hash encode two frequency values quantised to Bf bins and one time difference quantised to Bt bins, so the hash space has size |space|=Bf2Bt. For a query with Mq hashes and a database song with Ms hashes, assuming hashes are uniformly distributed, the expected number of spurious hash collisions is (Collision Bound)𝔼[collisions]=MqMsBf2Bt. For typical values Bf=512, Bt=64, Mq=100, and Ms=10,000, this gives 𝔼[collisions]0.06, far below the threshold μ required for a match. The probability that a non-matching song produces μ or more coherent collisions is bounded by (Collision TAIL)P(false match)(MqMsk)(1Bf2BtBΔ)k, where k=μ is the match threshold and BΔ is the number of distinct time-offset bins.

Proof.

Each pair of hashes (one from the query, one from the database song) collides with probability 1/(Bf2Bt) under the uniformity assumption, since both hashes are drawn independently from the same hash space. By linearity of expectation, the expected number of collisions across all MqMs pairs is MqMs/(Bf2Bt).

For a false match, k or more of these collisions must additionally agree on the same time offset, which occurs with probability 1/BΔ per collision. A union bound over all (MqMsk) subsets of k collisions gives the stated tail bound.

Music Similarity and Recommendation

While fingerprinting answers “What song is this?”, a different question drives much of music information retrieval [75][76]: “What songs sound like this one?” Answering this question requires extracting features that capture the perceptual qualities of music and defining meaningful similarity measures over these features.

Music features are traditionally organised into a hierarchy spanning three levels of abstraction.

Definition 33 (Music Feature Hierarchy).

  1. Low-level features capture the acoustic surface of the signal: itemize

  2. Spectral centroid: the “centre of mass” of the spectrum, correlating with perceived brightness.

  3. Spectral flux: frame-to-frame spectral change, correlating with perceived “activity”.

  4. Mel-frequency cepstral coefficients (MFCCs): compact representations of the spectral envelope, widely used for timbral similarity.

  5. Zero-crossing rate: correlates with noisiness and percussive content. itemize

  6. Mid-level features capture musical structure: itemize

  7. Tempo and beat strength: rhythmic properties estimated via onset detection and autocorrelation.

  8. Chroma features: the distribution of spectral energy across the twelve pitch classes, capturing harmonic content independent of octave.

  9. Onset patterns: the rhythmic pattern of note onsets, capturing groove and rhythmic complexity. itemize

  10. High-level features capture semantic and cultural properties: itemize

  11. Genre: classification into categories (rock, jazz, classical, etc.).

  12. Mood: emotional characterisation (happy, sad, energetic, calm).

  13. Instrumentation: presence and prominence of specific instruments. itemize

Music retrieval feature hierarchy. Low-level acoustic features capture the signal's spectral properties; mid-level features capture rhythmic and harmonic structure through temporal aggregation; high-level features capture semantic categories through learned classification. Music similarity systems may operate at any level or combine features across levels. Modern deep learning approaches learn this entire hierarchy end-to-end.

Music similarity is then computed by representing each song as a feature vector (or sequence of feature vectors) and measuring distance in feature space. A common approach represents a song by the mean and covariance of its frame-level MFCC vectors [77], forming a Gaussian model per song, and measures similarity using the Kullback–Leibler divergence between these Gaussians: (Music Similarity KL)dKL(pq)=12(tr(𝚺q1𝚺p)+(𝝁q𝝁p)𝚺q1(𝝁q𝝁p)d+log|𝚺q||𝚺p|), where (𝝁p,𝚺p) and (𝝁q,𝚺q) are the mean and covariance of the MFCC distributions for songs p and q respectively, and d is the feature dimensionality.

Query-by-Humming

One of the most user-friendly forms of music retrieval is query-by-humming (QBH): a user hums, sings, or whistles a melody, and the system identifies the song. This is a fundamentally different problem from fingerprinting because the query is a highly distorted version of the original: the rhythm may be approximate, the pitch may be shifted, and the timbre is entirely different (a human voice rather than instruments).

The QBH problem reduces to melody matching: comparing the pitch contour of the hummed query against a database of reference melodies. The pitch contour is extracted from the query using a fundamental frequency (F0) estimation algorithm, producing a sequence of pitch values 𝒑q=(p1q,,pNq). Reference melodies can be extracted from MIDI files, audio recordings, or music score databases.

Matching is performed using a variant of DTW that operates on pitch intervals (differences between consecutive pitch values) rather than absolute pitch values, making the system transposition-invariant: (QBH DTW)c(piq,pjr)=|(piqpi1q)(pjrpj1r)|, where 𝒑q and 𝒑r are the query and reference pitch sequences respectively. This formulation ensures that a query hummed in a different key still matches the correct song.

Insight.

Query-by-humming elegantly illustrates the tension between invariance and discriminability that pervades all of retrieval. The system must be invariant to transposition (key changes), tempo variations (the user may hum faster or slower than the original), timbre differences (voice vs. instruments), and rhythmic imprecision. Yet it must remain discriminative enough to distinguish between melodies that share similar contours. The solution, operating on pitch intervals with DTW alignment, achieves the right balance by preserving the melodic shape while discarding absolute pitch and timing.

Modern Approaches: Neural Music Representations

The feature engineering approach to music similarity is being supplanted by deep learning models that learn representations end-to-end. Two recent models illustrate this trend.

MusicGen.

MusicGen [78] is a language model for music generation that operates on discrete audio tokens produced by EnCodec, a neural audio codec. While designed for generation, MusicGen's internal representations (the hidden states of its transformer layers) serve as powerful feature extractors for music retrieval. These representations encode harmonic, rhythmic, and timbral information at multiple levels of abstraction, learned implicitly through the generation objective.

MusicLM.

MusicLM [79] generates high-fidelity music from text descriptions by combining MuLan (a music-text embedding model) with AudioLM (an audio language model). The MuLan embedding space, where music and text descriptions are aligned, provides a natural basis for text-to-music retrieval: given a text query like “upbeat jazz piano with brushed drums,” retrieve songs whose MuLan embeddings are closest to the text embedding.

These models represent a paradigm shift: instead of hand-engineering features for each aspect of music (timbre, rhythm, harmony), a single model learns a unified representation that captures all relevant dimensions simultaneously. For retrieval, this means that a single embedding can support diverse query types, from acoustic similarity to semantic text-based search.

Example 19 (Neural Music Feature Extraction).

To use MusicGen as a feature extractor for music retrieval, one processes each song through the model's encoder and extracts hidden-state representations at multiple layers:

  1. Encode the audio using EnCodec to produce discrete tokens 𝒛=(z1,,zL).

  2. Pass the tokens through MusicGen's transformer layers, extracting hidden states 𝒉(l) at layer l for each position .

  3. Aggregate across positions via mean pooling: 𝒉(l)=1L=1L𝒉(l).

  4. Concatenate representations from multiple layers to capture both low-level acoustic details (early layers) and high-level semantic properties (late layers): 𝒓=[𝒉(l1);𝒉(l2);𝒉(l3)].

The resulting representation 𝒓 can be used for nearest-neighbour retrieval, clustering, or as input to a downstream recommendation model. Empirically, mid-to-late layers (e.g., layers 8–12 in a 24-layer model) produce the best retrieval features, capturing musical structure without being overly specialised for the generation objective.

Remark 27.

The use of generative models as feature extractors is a recurring theme in modern retrieval. Just as large language models pre-trained for text generation produce excellent text embeddings, and diffusion models pre-trained for image generation produce excellent visual features, music generation models produce representations that capture the structure of music far better than hand-crafted features. The generative pre-training objective forces the model to build internal representations of the data distribution, and these representations are precisely what retrieval needs.

Music-Text Retrieval

The connection between music and natural language has become a central focus of modern MIR. Music-text retrieval enables two complementary tasks: text-to-music retrieval (finding songs that match a text description) and music-to-text retrieval (generating or retrieving text descriptions for a given song, often called music captioning).

The dominant approach follows the contrastive dual-encoder paradigm familiar from CLIP and its variants: a music encoder and a text encoder are trained jointly to produce aligned embeddings, using a contrastive loss that pushes matching music-text pairs together and non-matching pairs apart. The CLAP framework [22], discussed in detail in the next section, provides the foundation for this approach.

Content-based vs. collaborative filtering.

Music recommendation systems traditionally use one of two approaches. Content-based filtering recommends songs based on acoustic similarity to songs the user has enjoyed, using the features and similarity measures described above. Collaborative filtering recommends songs based on the listening patterns of similar users, without analysing the audio content at all. Modern systems combine both approaches in hybrid recommenders that use content-based features to address the cold-start problem (recommending new songs with no listening history) while leveraging collaborative signals for personalisation.

The emergence of music-text models adds a third dimension: users can now describe what they want in natural language, and the system can retrieve music that matches the description even if the user has never heard similar music before. This language-mediated retrieval is particularly powerful because natural language can express complex, compositional musical concepts (“a slow, melancholic cello piece reminiscent of Elgar”) that are difficult to capture with acoustic features alone.

Proposition 19 (Cold-Start Advantage of Content-Based Retrieval).

Let 𝒰 be a set of users, 𝒮 a set of songs, and 𝐑{0,1}|𝒰|×|𝒮| the binary interaction matrix. A new song snew added to the catalogue has 𝐑u,snew=0 for all u𝒰 (no user has interacted with it). Collaborative filtering methods, which predict ratings from the interaction matrix alone, assign zero or uniform scores to snew for all users, rendering them unable to recommend it. In contrast, content-based methods can compute similarity sim(snew,si) for all existing songs si using acoustic features, enabling immediate recommendation to users who enjoyed acoustically similar songs. The collaborative filtering model requires at least Ω(|𝒰|) interactions with snew before its latent factor estimate achieves bounded error, while content-based similarity requires zero interactions.

Example 20 (Music Information Retrieval Pipeline).

A modern music streaming platform integrates multiple retrieval modalities:

  1. Exact identification: Shazam-style fingerprinting for “What's playing?” queries. Hash-table lookup over a database of 100 million tracks, completing in under 1 second.

  2. Acoustic similarity: Neural embeddings (from MusicGen or a dedicated music embedding model) enable “More like this” recommendations. Approximate nearest-neighbour search in a learned embedding space.

  3. Text-based search: CLAP embeddings enable natural language queries (“chill lo-fi beats for studying”). The music encoder and text encoder produce embeddings in a shared space, and cosine similarity ranks the results.

  4. Collaborative filtering: User listening histories provide personalised recommendations via matrix factorisation or graph neural network models.

  5. Hybrid fusion: A learned re-ranker combines signals from all modalities, weighting acoustic, semantic, and collaborative evidence to produce the final ranking.

Exercise 32 (Audio Fingerprint Design).

Consider designing an audio fingerprinting system for a database of N=107 songs, each of average duration 4 minutes, with audio sampled at 44.1,kHz.

  1. If the STFT uses a window of 1,024 samples with 75% overlap, how many time frames are produced per song? If the peak density is 5 peaks per time frame, how many peaks are in the full database?

  2. If each anchor point is paired with 10 target points, how many hashes are produced per song? What is the total hash-table size for the full database?

  3. Using the collision bound from Proposition 18, compute the expected number of spurious collisions for a 5-second query against each non-matching song. What match threshold μ ensures a false-positive rate below 109 per song?

  4. Describe how you would modify the fingerprinting algorithm to handle time-stretched audio (e.g., a DJ playing a song at 105% of normal speed).

Exercise 33 (Query-by-Humming System Design).

A query-by-humming system receives a hummed melody and must identify the song from a database of 1 million tracks.

  1. The F0 estimator produces a pitch sequence at 100,Hz frame rate with occasional octave errors (the estimated pitch is exactly twice or half the true pitch). Design a preprocessing step that detects and corrects octave errors using the smoothness of the pitch contour.

  2. The interval-based DTW in (QBH DTW) is transposition-invariant but not tempo-invariant. Propose a two-stage approach that first normalises the query to a canonical tempo and then applies DTW.

  3. Discuss the limitations of melody-based retrieval for genres where the melody is not the primary distinguishing feature (e.g., electronic dance music, ambient music). What alternative query modalities might be effective?

Exercise 34 (Music Similarity Metrics).

Given a database of songs represented by Gaussian MFCC models {(𝝁i,𝚺i)}i=1N:

  1. Prove that the KL divergence between two Gaussians is not symmetric. Define a symmetric version and discuss its properties as a similarity metric.

  2. The KL divergence has computational cost 𝒪(d3) due to the matrix inverse and determinant. Propose a diagonal covariance approximation and analyse the resulting complexity.

  3. A user wants to find songs that are “rhythmically similar but timbrally different.” How would you modify the feature representation and similarity metric to support this query?

Audio-Language Retrieval

The previous two sections focused on speech and music, two structured forms of audio with well-developed retrieval traditions. But the auditory world extends far beyond speech and music: the creak of a door, the rumble of thunder, a car horn in traffic, the chirping of crickets at dusk. General audio retrieval, the ability to search for arbitrary sounds using natural language descriptions, has emerged as a frontier where audio understanding meets language understanding, producing models that can find sounds they have never been explicitly trained to recognise.

The key enabler is Contrastive Language-Audio Pre-training (CLAP) [22], which extends the CLIP paradigm from images to audio, learning a shared embedding space where audio recordings and text descriptions are aligned.

CLAP: Contrastive Language-Audio Pre-training

CLAP follows the dual-encoder contrastive framework that has proven so effective for vision-language models, adapted for the audio domain. The architecture consists of two components.

Audio encoder.

The audio encoder faudio:F×Td takes a log-mel spectrogram as input and produces a d-dimensional embedding. Common choices include:

  • HTSAT (Hierarchical Token-Semantic Audio Transformer): a Swin Transformer adapted for audio spectrograms, which captures both local spectral patterns and global temporal structure.

  • PANN (Pre-trained Audio Neural Network): CNN-based architectures pre-trained on AudioSet for audio tagging, fine-tuned within the CLAP framework.

  • BEATs: an audio pre-training framework using iterative audio tokenisation and masked prediction.

Text encoder.

The text encoder ftext:𝒱d maps a text description to the same d-dimensional space. CLAP typically uses a pre-trained language model (RoBERTa, BERT, or GPT-2) as the backbone, with a projection head that maps the [CLS] token representation to the shared embedding space.

Training objective.

The model is trained with the symmetric contrastive loss familiar from CLIP: (CLAP LOSS)CLAP=12Bi=1B(logexp(faudio(𝒂i),ftext(𝒕i)/κ)j=1Bexp(faudio(𝒂i),ftext(𝒕j)/κ) +logexp(ftext(𝒕i),faudio(𝒂i)/κ)j=1Bexp(ftext(𝒕i),faudio(𝒂j)/κ)), where {(𝒂i,𝒕i)}i=1B is a batch of audio-text pairs, , denotes the inner product in the shared embedding space, and κ>0 is a learnable temperature parameter.

The CLAP (Contrastive Language-Audio Pre-training) architecture. An audio encoder processes log-mel spectrograms and a text encoder processes natural language descriptions; both are projected into a shared d-dimensional embedding space. The contrastive loss pulls matching audio-text pairs together and pushes non-matching pairs apart. At inference time, retrieval is performed by cosine similarity in the shared space.
Training data.

CLAP models are trained on audio-text pairs drawn from several sources:

  • AudioSet [13]: over 2 million 10-second YouTube clips with human-annotated labels, which can be converted to text descriptions via templates (e.g., label “Dog bark” becomes “The sound of a dog barking”).

  • AudioCaps: a subset of AudioSet with human-written free-form captions describing the audio content in natural language.

  • LAION-Audio-630K [14]: a large-scale dataset of 633,526 audio-text pairs collected from the web, covering music, environmental sounds, and speech.

  • FreeSound: a collaborative database of Creative Commons–licensed sounds with user-provided descriptions.

Key Idea.

Zero-shot audio classification as retrieval. One of CLAP's most powerful capabilities is zero-shot audio classification. Given an audio clip and a set of candidate class labels {c1,,cK}, each label is converted to a text prompt (e.g., “the sound of [class]”), embedded by the text encoder, and compared to the audio embedding. The predicted class is c^=arg maxk{1,,K}faudio(𝒂),ftext(ck). This is precisely a retrieval operation: the audio “queries” the text space to find the best-matching description. Remarkably, CLAP can classify sounds from categories never seen during training, because the text encoder provides a semantic bridge between seen and unseen categories through the structure of natural language.

LAION-Audio: Scaling Audio-Text Pre-training

The effectiveness of contrastive audio-language models scales with the size and diversity of the training data. LAION-Audio [14] addresses this by providing a large-scale, openly available dataset of audio-text pairs harvested from the web. The collection pipeline mirrors the approach used for LAION-5B in the image domain:

  1. Crawl web pages containing audio content (YouTube, FreeSound, BBC Sound Effects, etc.).

  2. Extract audio files and their associated text metadata (titles, descriptions, tags, captions).

  3. Filter for quality: remove very short clips (<1,s), very long clips (>30,s), and clips with uninformative descriptions.

  4. De-duplicate by audio fingerprinting to avoid training on near-identical clips.

The resulting LAION-Audio-630K dataset contains 633,526 audio-text pairs spanning diverse categories: environmental sounds (rain, traffic, machinery), music (instruments, genres, moods), speech-related sounds (laughter, applause, crowd noise), and animal vocalisations. Models trained on LAION-Audio consistently outperform those trained on AudioSet alone, particularly on out-of-domain retrieval tasks, because the web-sourced data provides greater diversity in both audio content and text descriptions.

Remark 28.

The scaling behaviour of audio-language models follows patterns familiar from vision-language pre-training. Doubling the training data size typically yields a consistent improvement in retrieval recall, with diminishing returns setting in only at very large scales. However, the quality of audio-text alignment matters as much as quantity: a smaller dataset of human-written captions (like AudioCaps) can produce better retrieval performance per training example than a larger dataset of template-generated descriptions from class labels. The ideal training mixture combines both: template-expanded label data provides broad coverage across sound categories, while human captions provide the linguistic diversity and compositionality needed for free-form text queries.

ImageBind: Binding Audio to Other Modalities

CLAP binds audio to text. CLIP binds images to text. A natural question arises: can we bind all modalities, including audio, images, text, video, depth, and thermal, into a single shared embedding space? ImageBind [15] provides an affirmative answer through a remarkably elegant mechanism.

The key insight is that images can serve as a universal binding modality. Because high-quality paired data exists between images and each other modality (image-text pairs, image-audio pairs from video, image-depth pairs from RGB-D sensors), training separate encoders to align each modality with images implicitly aligns all modalities with each other. If audio embedding 𝒂 is close to image embedding 𝒗 in one space, and text embedding 𝒕 is close to image embedding 𝒗 in another space, then 𝒂 and 𝒕 should be close to each other, even though they were never directly paired during training.

Theorem 6 (Emergent Cross-Modal Alignment).

Let f1,f2,,fM be encoders for M modalities, and let f0 be the image encoder serving as the binding modality. Suppose each encoder fm is trained to minimise the contrastive loss align(fm,f0) against the image encoder. If the learned embedding space is approximately isometric (distances are approximately preserved under the encoder mappings), then for any two modalities m,m, the cross-modal retrieval performance R(fm,fm) is bounded below by (Imagebind Bound)R(fm,fm)R(fm,f0)+R(fm,f0)1ϵ, where ϵ captures the deviation from perfect isometry and R(,) denotes retrieval recall.

Proof sketch.

Consider a query from modality m and a database in modality m. The true match is the item whose underlying semantic content matches the query. In the shared embedding space, the query embedding fm(𝒙) is close to the image embedding f0(𝒗) of the corresponding image (by the alignment between m and images), and the database item embedding fm(𝒚) is close to f0(𝒗) (by the alignment between m and images). By the triangle inequality in the embedding space: fm(𝒙)fm(𝒚)fm(𝒙)f0(𝒗)+f0(𝒗)fm(𝒚). When both terms on the right are small (which happens when both modality-to-image alignments are good), the cross-modal distance is also small, ensuring that the correct match is retrieved. The deviation ϵ accounts for cases where the triangle inequality bound is not tight.

The practical implication is striking: by training M modality-specific encoders against a single image encoder, ImageBind obtains (M2)=M(M1)/2 pairwise retrieval capabilities, of which only M1 are directly trained. For M=6 modalities, this means 15 pairwise tasks from only 5 trained alignments, a 3× amplification of retrieval capabilities.

For audio retrieval, ImageBind's contribution is the ability to perform cross-modal audio retrieval without direct audio-text or audio-image paired training data. Given a text query, one can retrieve audio clips by comparing text embeddings to audio embeddings in the shared space, even if the model was trained only on image-text and image-audio pairs. This emergent capability dramatically expands the scope of audio retrieval.

Example 21 (Cross-Modal Retrieval via ImageBind).

Consider a database of environmental audio recordings indexed using ImageBind's audio encoder. The following cross-modal queries become possible:

  • Text-to-audio: “crashing ocean waves” retrieves recordings of surf and breaking waves.

  • Image-to-audio: A photograph of a thunderstorm retrieves recordings of thunder and rain.

  • Audio-to-image: A recording of birdsong retrieves images of forests and birds.

  • Video-to-audio: A silent video of a waterfall retrieves the sound of rushing water.

All four query types are supported by a single model, despite the model never being trained on direct audio-text, audio-image, or audio-video pairs. The binding through the image modality creates these emergent retrieval capabilities.

Sound Event Retrieval

Sound event retrieval focuses on finding specific sounds within audio recordings based on textual descriptions. This capability is essential for applications including sound effect production (finding the right door creak for a film), environmental monitoring (detecting specific bird calls in ecological surveys), and accessibility (alerting hearing-impaired users to relevant environmental sounds).

The retrieval task can be formalised as follows.

Definition 34 (Sound Event Retrieval).

Given a text query q describing a sound event (e.g., “a glass bottle breaking on a tile floor”) and a database of audio clips 𝒜={a1,,aN}, retrieve the set of clips that contain the described event: Retrieve(q,𝒜)={ai𝒜|ftext(q),faudio(ai)>η}, where ftext and faudio are the text and audio encoders of a CLAP model and η is a relevance threshold.

The challenge in sound event retrieval lies in the compositionality of natural language descriptions. A query like “a dog barking in the distance with traffic noise in the background” requires the model to understand multiple concurrent sound sources, their spatial relationships, and their relative prominence. Current CLAP models handle simple compositional queries reasonably well but struggle with complex spatial or temporal relationships.

Environmental sound classification provides an important testing ground for audio retrieval models. The ESC-50 benchmark, containing 2,000 five-second recordings across 50 classes of environmental sounds (from “dog bark” to “chainsaw” to “pouring water”), has become the standard evaluation for zero-shot audio understanding. A CLAP model achieves zero-shot classification on ESC-50 by computing the similarity between the audio embedding and text embeddings for each of the 50 class labels, selecting the label with the highest similarity. The progression from 72% accuracy (early CLAP models) to over 93% (current state of the art) reflects improvements in both model architecture and training data scale.

Lemma 5 (Retrieval as Classification).

Let faudio and ftext be a CLAP model's audio and text encoders, and let {c1,,cK} be a set of class labels with text prompts {t1,,tK}. The zero-shot classification decision k^=arg maxkfaudio(𝒂),ftext(tk) is equivalent to a 1-nearest-neighbour retrieval in the text embedding space, where the “database” consists of the K class embeddings and the “query” is the audio embedding. If the text embeddings {ftext(tk)}k=1K are approximately uniformly distributed on the unit sphere (a consequence of the contrastive training objective for large K), then the classification boundary between classes k and k is the hyperplane {v:v,ftext(tk)ftext(tk)=0}, yielding a Voronoi tessellation of the embedding space.

ModelAudioCapsClothoESC-50 (ZS)Training Data
CLAP (HTSAT)57.827.482.6AudioSet + AudioCaps
LAION-CLAP64.233.190.4LAION-Audio-630K
ImageBind51.322.877.2Image-paired data
MS-CLAP (2023)68.736.293.1AudioSet + LAION + FSD50K
Audio retrieval benchmarks and results. Performance is reported as Recall@10 for text-to-audio retrieval. CLAP and LAION-CLAP represent the progression of contrastive audio-language models, while ImageBind demonstrates emergent cross-modal capabilities.

Retrieval-Augmented Audio Generation

A natural application of audio retrieval is to enhance audio generation models by grounding them in retrieved examples. Just as retrieval-augmented generation (RAG) improves text generation by conditioning on relevant documents, retrieval-augmented audio generation improves the fidelity and controllability of audio synthesis by conditioning on retrieved audio clips.

Re-AudioLDM.

Re-AudioLDM [32] augments the AudioLDM [80] latent diffusion model with a retrieval module. Given a text prompt describing the desired audio (e.g., “rain falling on a metal roof with occasional thunder”), the system first retrieves the k most relevant audio clips from a database using CLAP embeddings, then conditions the diffusion process on both the text prompt and the retrieved audio features: (Reaudioldm)p𝜽(𝒙0|𝒕,)=p𝜽(𝒙0|𝒙T,𝒕,)p(𝒙T)d𝒙T, where 𝒕 is the text conditioning, ={r1,,rk} is the set of retrieved audio clips, and 𝒙T𝒙0 denotes the reverse diffusion process. The retrieved clips provide concrete acoustic examples that guide the diffusion process toward generating audio with the right timbral and spectral characteristics.

RECAP.

RECAP [33] takes a complementary approach, focusing on the retrieval of audio captions rather than audio clips. Given a text prompt, RECAP retrieves similar captions from a large database and uses them to enrich the text conditioning for the generation model. This is particularly effective for underspecified prompts: a user who writes “ocean” gets the benefit of retrieved captions like “gentle waves lapping on a sandy beach with distant seagulls,” which provide the acoustic detail needed for high-quality generation.

Definition 35 (Retrieval-Augmented Audio Generation).

A retrieval-augmented audio generation system consists of three components:

  1. A retrieval module :𝒯2𝒜 that maps a text query to a set of relevant audio clips or captions from a database.

  2. A conditioning mechanism ϕ:𝒯×2𝒜d that fuses the text prompt with the retrieved items to produce a conditioning vector.

  3. A generation model G𝜽:d𝒳 that produces audio conditioned on the fused representation.

The generation quality is bounded below by the retrieval quality: if the retrieved items are relevant and diverse, the conditioning provides rich acoustic detail; if the retrieval fails, the system falls back to text-only conditioning.

Insight.

Retrieval-augmented audio generation exemplifies a broader principle: retrieval and generation are complementary, not competing, paradigms. Pure generation must synthesise all acoustic details from a text description alone, placing enormous demands on the model's capacity and training data. Retrieval-augmented generation offloads part of this burden to the database: instead of learning to generate every possible sound from scratch, the model learns to adapt and recombine retrieved examples, a fundamentally easier task. This parallels the observation in language modelling that RAG systems can achieve the performance of much larger models by leveraging external knowledge. In the audio domain, the principle is even more powerful: audio signals are high-dimensional and exhibit enormous variability (the sound of “rain” can vary along dimensions of intensity, surface material, accompanying sounds, and recording conditions), making it far easier to retrieve a close example and adapt it than to synthesise the full acoustic detail from a text description alone.

Retrieval-augmented audio generation pipeline. A text query is used to retrieve relevant audio clips from a database via CLAP embeddings. The text conditioning and retrieved audio features are fused and fed to a latent diffusion model (AudioLDM), which generates audio that combines the semantic intent of the text prompt with the acoustic characteristics of the retrieved examples. This approach produces more realistic and controllable audio than text-only conditioning.

Example 22 (Audio-Language Retrieval in Practice).

Consider a sound designer working on a nature documentary who needs to find specific environmental sounds. Using a CLAP-based retrieval system with a database of 500,000 environmental recordings:

  • Query: “gentle stream flowing over rocks in a forest” itemize

  • The text encoder maps this description to an embedding that captures both the acoustic qualities (flowing water, natural setting) and the semantic context (gentle, forest).

  • The top-5 retrieved clips include brook recordings with varying levels of bird activity and wind. itemize

  • Query: “footsteps on gravel, slow pace” itemize

  • The model retrieves recordings of walking on gravel surfaces, ranked by tempo match (slower footsteps ranked higher).

  • The temporal descriptor “slow pace” is captured through the model's learned association between text and acoustic features. itemize

  • Query: “thunderstorm approaching from a distance” itemize

  • Results are ranked by the prominence and spatial characteristics of the thunder, with distant rumbles ranked above close strikes.

  • This demonstrates the model's ability to understand spatial relationships described in text. itemize

Exercise 35 (CLAP Training Dynamics).

Consider training a CLAP model from scratch on a dataset of N audio-text pairs.

  1. In the contrastive loss ((CLAP LOSS)), what happens when the temperature κ is very small (κ0)? What about when it is very large (κ)? Discuss the effect on gradient magnitude and learning dynamics.

  2. The contrastive loss treats all non-matching pairs equally. Propose a modification that assigns different negative weights based on semantic similarity of the text descriptions (e.g., “dog barking” and “puppy yelping” should be softer negatives than “dog barking” and “piano playing”).

  3. Derive the gradient of CLAP with respect to the audio embedding faudio(𝒂i) for the i-th example, and show that it pushes the audio embedding toward its matching text and away from non-matching texts, with forces proportional to the softmax-weighted similarities.

  4. How does the batch size B affect the quality of the learned representations? Provide both an information-theoretic argument (in terms of the mutual information lower bound) and a practical argument (in terms of the hardness of negatives).

Exercise 36 (Cross-Modal Retrieval Analysis).

ImageBind aligns M=6 modalities to a shared embedding space using images as the binding modality.

  1. How many pairwise retrieval tasks are possible with 6 modalities? How many of these are directly trained (i.e., involve the image modality)? What fraction of all retrieval capabilities are emergent?

  2. Using Theorem 6, if audio-to-image recall is Rai=0.85 and text-to-image recall is Rti=0.90, what is the lower bound on audio-to-text recall?

  3. The bound in (Imagebind Bound) can be negative. Under what conditions does this happen, and what does it mean? Propose a tighter bound using concentration inequalities on the embedding distances.

  4. Design an experiment to test whether the triangle inequality assumption underlying ImageBind's emergent alignment holds in practice. What embedding properties would cause the assumption to fail?

Exercise 37 (Retrieval-Augmented Audio Generation).

Consider a retrieval-augmented audio generation system that uses CLAP embeddings to retrieve k reference clips and conditions an AudioLDM model on the retrieved features.

  1. Formalise the retrieval step as an optimisation problem. What objective does the CLAP-based retriever optimise, and how does this relate to the generative model's conditioning requirements?

  2. The choice of k (number of retrieved clips) involves a bias-variance tradeoff. With k=1, the generation is strongly influenced by a single example; with k=100, the retrieved set may include irrelevant clips that dilute the conditioning signal. Propose a method for adaptively selecting k based on the retrieval scores.

  3. When the text prompt is ambiguous (e.g., “bird”), the retrieved clips may span diverse interpretations (songbirds, seagulls, parrots). How would you modify the system to present diverse generation options to the user rather than averaging over interpretations?

Caution.

Audio-language models inherit biases from their training data. Web-sourced audio datasets are heavily skewed toward English descriptions, Western music genres, and urban soundscapes from developed countries. A CLAP model may perform poorly on queries in other languages, fail to recognise traditional instruments from non-Western musical traditions, or misclassify environmental sounds common in rural or tropical settings but rare in the training data. Evaluating and mitigating these biases is an active research challenge that becomes more urgent as these models are deployed in global applications.

Research 2.

Several open problems define the frontier of audio-language retrieval: The field of audio-language retrieval is young, with CLAP models first appearing in 2022, and much remains to be understood about the structure of audio-text embedding spaces, the optimal training strategies, and the limits of what contrastive pre-training can achieve for audio understanding.

  1. Temporal reasoning: Current CLAP models treat audio as a single “bag of events.” Queries that require temporal reasoning (“a car horn followed by screeching tires and then a crash”) are poorly served. Extending CLAP to capture temporal structure without sacrificing retrieval efficiency is an open challenge.

  2. Compositional understanding: Natural language descriptions of audio scenes are compositional (“loud” modifies a specific source, “in the background” specifies spatial positioning), but current models struggle with compositional semantics.

  3. Long-form audio retrieval: Most audio-language models operate on 10-second clips. Scaling to minutes or hours, as required for podcast search, surveillance, or ecological monitoring, requires efficient temporal indexing strategies.

  4. Unified audio models: Current systems use separate models for speech, music, and environmental sound. A truly universal audio retrieval system would handle all three with a single encoder, understanding queries like “find the podcast episode where jazz music plays during the interview about climate change.”

Multimodal Embedding Spaces

Imagine a single coordinate system in which a photograph of a thunderstorm, the sound of rolling thunder, the sentence “dark clouds gathering before a downpour,” a video clip of lightning, and even the thermal signature of a storm front all live as nearby points. Not merely nearby within their own modality, but nearby to each other, so that the sound of thunder sits closer to the image of lightning than to the sound of birdsong, and the sentence sits closer to the photograph than to an unrelated paragraph about tax policy. This is the grand vision of multimodal embedding spaces: a single, shared geometric arena in which every form of human experience, text, vision, audio, touch, motion, can be compared, combined, and retrieved with the same inner product.

The vision is revolutionary because it collapses the tower of modality-specific systems that has dominated machine learning for decades. Instead of separate text search, image search, audio search, and video search engines, each with bespoke architectures, training pipelines, and index structures, one obtains a single embedding model and a single vector index. A query in any modality retrieves results in every modality, with relevance measured by a single score.

The vision is also incredibly challenging. Each modality lives on a fundamentally different data manifold. Text is discrete and sequential; images are dense and spatial; audio is temporal and frequency-structured; video is spatiotemporal; depth maps are geometric. Aligning these manifolds into a shared space requires not just large paired datasets but a principled framework for defining what “alignment” even means when the modalities carry different information at different levels of abstraction.

Key Idea.

The Multimodal Alignment Problem. Given M modalities with data spaces 𝒳1,,𝒳M, the multimodal alignment problem asks for encoders fm:𝒳md, one per modality, such that semantically related inputs from different modalities map to nearby points in d. Formally, for semantically related pairs (xi,xj)𝒳m×𝒳n with mn: (Multimodal Alignment)fm(xi),fn(xj)fm(xi),fn(xk) for unrelated xk, where , denotes the inner product after 2-normalization.

The difficulty scales superlinearly with the number of modalities. For M modalities, there are (M2) pairwise alignment tasks, but paired data is typically available for only a small subset of these pairs. Collecting audio-depth pairs, or text-thermal pairs, or IMU-video pairs at scale is prohibitively expensive. This data scarcity problem is what makes the naive approach of training (M2) separate contrastive models impractical, and it is what motivates the elegant solutions we study next.

ImageBind: Binding Six Modalities Through Images

The key insight behind ImageBind [15] is deceptively simple: images are nature's universal pairing mechanism. Consider the modalities we care about: text, audio, depth, thermal imagery, and inertial measurement unit (IMU) data. In the natural world, images are routinely paired with each of these modalities. Web data provides billions of image-text pairs. Videos provide image-audio pairs (every video frame is paired with its soundtrack). RGB-D cameras provide image-depth pairs. Thermal cameras provide image-thermal pairs. Wearable devices with cameras provide image-IMU pairs.

None of these pairings are exotic or expensive; they arise organically from the way sensors capture the world. The genius of ImageBind is to exploit this star topology of natural pairings, with images at the hub, to bind all six modalities into a single embedding space without ever needing direct pairings between non-image modalities.

Definition 36 (Image-Anchored Multimodal Alignment).

Let ={1,,M} be a set of modalities, with modality 1 designated as the anchor modality (images). For each non-anchor modality m{2,,M}, assume access to paired data {(xi(1),xi(m))}i=1Nm. The image-anchored alignment trains modality-specific encoders fm:𝒳md by minimizing the InfoNCE loss between each modality m and the anchor: (Imagebind LOSS)m=1Nmi=1Nmlogexp(f1(xi(1)),fm(xi(m))/τ)j=1Nmexp(f1(xi(1)),fm(xj(m))/τ), where τ>0 is a temperature parameter. The total loss is =m=2Mm.

The architecture of ImageBind uses a Vision Transformer (ViT-H) as the image encoder f1, initialized from a pretrained model. Each non-image modality m uses a separate Transformer encoder fm, with modality-specific tokenization: audio spectrograms are treated as 2D patches (following the Audio Spectrogram Transformer approach), depth and thermal maps are treated as single-channel images, IMU signals are treated as 1D sequences, and text uses the standard tokenizer from CLIP [9].

Remark 29 (Why the Star Topology Works).

The star topology works because of the transitivity of embedding alignment. If audio is aligned with images, and text is aligned with images, then audio and text become implicitly aligned through the shared image space. Formally, if faudio(𝒙a),fimg(𝒙I) is high and fimg(𝒙I),ftext(𝒙t) is high for semantically related triplets (𝒙a,𝒙I,𝒙t), then faudio(𝒙a),ftext(𝒙t) tends to be high as well, even though no audio-text pairs were used during training.

This transitivity is not exact (the triangle inequality in embedding space introduces a gap), but empirically it works remarkably well. ImageBind achieves strong zero-shot audio-text retrieval without having seen a single audio-text pair during training.

The emergent cross-modal retrieval capabilities are perhaps ImageBind's most striking contribution. Consider the following: train the model exclusively on (image, audio), (image, text), (image, depth), (image, thermal), and (image, IMU) pairs. Now, at inference time, compute embeddings for an audio clip and a text description. Despite never having been trained on audio-text correspondence, the model can retrieve the correct text given an audio query, and vice versa. This is zero-shot emergent cross-modal retrieval, and it arises purely from the geometry of the shared embedding space.

Proposition 20 (Emergent Alignment Bound).

Let f1 (image), fm, and fn be modality encoders trained with image-anchored alignment. For semantically related inputs (x(m),x(n)) with a common semantic referent having image representation x(1), the emergent cross-modal similarity satisfies (Emergent Bound)fm(x(m)),fn(x(n))ab1a21b2,a=fm(x(m)),f1(x(1)),b=f1(x(1)),fn(x(n)), where all embeddings are 2-normalized.

Proof.

Write 𝒛m=fm(x(m)), 𝒛1=f1(x(1)), 𝒛n=fn(x(n)), all unit vectors, and let θm1,θ1n,θmn[0,π] be the geodesic (angular) distances on the unit sphere, so that 𝒛m,𝒛1=cosθm1=a, 𝒛1,𝒛n=cosθ1n=b, and 𝒛m,𝒛n=cosθmn. Geodesic distance is a metric, so the triangle inequality gives θmnθm1+θ1n. Since cos is decreasing on [0,π], cosθmncos(θm1+θ1n)=cosθm1cosθ1nsinθm1sinθ1n=ab1a21b2, which is the stated bound (the spherical law of cosines). It is tight when 𝒛m,𝒛1,𝒛n are coplanar and 𝒛1 lies on the geodesic arc between 𝒛m and 𝒛n.

The practical implication is that image-anchored alignment makes distant modalities align, but the guarantee is weaker than a naive additive estimate suggests. If each pairwise cosine similarity exceeds 0.8, the emergent similarity is only guaranteed to exceed 0.80.80.60.6=0.28 (not the additive 0.6), still positive and useful, but a reminder that transitivity of cosine similarity on the sphere is sublinear.

Example 23 (Emergent Audio-Text Retrieval in ImageBind).

On the ESC-50 environmental sound classification benchmark, ImageBind achieves 66.9% zero-shot accuracy for audio classification using text labels, despite never having been trained on any audio-text pairs. The model “hears” a sound (e.g., a crackling fire), embeds it near the image of a fireplace (via the audio-image alignment), and the fireplace image embedding is near the text “crackling fire” (via the image-text alignment inherited from CLIP). The chain audiotrainedimagetrainedtext produces a zero-shot audio-text connection that performs competitively with CLAP models trained on millions of audio-text pairs. This is the power of a well-structured embedding geometry: information about cross-modal relationships propagates transitively through the shared space.

Remark 30 (Scaling Laws for Emergent Alignment).

The quality of emergent cross-modal alignment improves with three factors: (a) the quality of the image encoder (a better image backbone produces a more semantically structured hub), (b) the quantity of paired data for each spoke of the star (more image-audio pairs improve audio embeddings), and (c) the embedding dimension d (higher dimensions provide more room for modality-specific information to coexist with shared semantics). ImageBind uses d=1024 with a ViT-H backbone, and ablation studies show that reducing the backbone to ViT-B degrades emergent alignment more than it degrades trained alignment, suggesting that emergent capabilities are more sensitive to model capacity.

The ImageBind architecture. Images serve as the central hub, with each non-image modality aligned to images via contrastive learning (solid arrows). Cross-modal retrieval between non-image modalities (dashed arrows) emerges without any direct paired training data, purely through the shared image embedding space [15].

Gemini Embedding 2: Natively Multimodal Embeddings

While ImageBind demonstrated that multimodal alignment could emerge from image-anchored contrastive learning, a natural question followed: what if a model were trained from the ground up to be natively multimodal, understanding text, images, video, audio, and structured documents within a single architecture? Google's Gemini Embedding [16][17] represents exactly this next step, leveraging the full power of the Gemini multimodal foundation model to produce embeddings that are natively multimodal rather than post-hoc aligned.

The key differences from approaches like ImageBind are architectural and philosophical. ImageBind uses separate encoders per modality, aligned through a shared loss. Gemini Embedding uses a single multimodal backbone, the Gemini model itself, which processes all modalities natively through a unified Transformer architecture. The embedding is extracted from this shared representation, yielding a 3072-dimensional vector for any input regardless of modality [18][81].

Definition 37 (Natively Multimodal Embedding).

A natively multimodal embedding model is a function f:m=1M𝒳md implemented by a single model architecture that processes all modalities through shared parameters, rather than through modality-specific encoders with a shared loss. The embedding dimension is fixed at d regardless of input modality.

Matryoshka Representation Learning.

One of the most elegant features of Gemini Embedding is its support for Matryoshka representations. Named after Russian nesting dolls, this technique trains the embedding such that every prefix of the full d-dimensional vector is itself a valid, useful embedding at a lower dimension. Formally, let f(x)d be the full embedding. For any d<d, the truncated embedding f(x)1:dd (the first d coordinates) preserves as much information as possible for that dimensionality.

Definition 38 (Matryoshka Embedding).

A Matryoshka embedding of depth L is an embedding f:𝒳d trained with the multi-scale loss (Matryoshka LOSS)Mat==1Lwtask(f(x)1:d), where d1<d2<<dL=d are the target dimensionalities, w>0 are scale weights, and task is the task-specific loss (e.g., InfoNCE for retrieval) evaluated using only the first d dimensions of the embedding.

The practical benefit is enormous. A production system can store the full 3072-dimensional embedding for maximum accuracy, but perform initial candidate retrieval using only the first 256 or 512 dimensions for speed and memory efficiency, then re-rank using the full embedding. This yields a natural coarse-to-fine retrieval pipeline without training separate models at each dimensionality.

Task-Type Conditioning.

Gemini Embedding introduces another innovation: task-type conditioning. Rather than producing a single, task-agnostic embedding, the model accepts a task_type parameter that conditions the embedding computation for specific downstream tasks [17][82]:

  • retrieval_document: optimized for indexing documents to be retrieved.

  • retrieval_query: optimized for queries that will be matched against documents.

  • semantic_similarity: optimized for computing pairwise similarity between inputs.

  • classification: optimized for downstream classification tasks.

  • clustering: optimized for grouping similar inputs.

Insight.

Asymmetric Query-Document Embeddings. The separation of retrieval_query and retrieval_document task types reflects a deep insight about information retrieval: queries and documents play fundamentally different roles. A query is short, underspecified, and expresses an information need. A document is long, detailed, and contains the information. By conditioning the embedding on the role of the input, the model can learn to project queries into the region of embedding space where their relevant documents reside, rather than forcing a symmetric similarity that treats both inputs identically. This is the learned analog of the classical query expansion technique, but implemented within the embedding computation itself.

Gemini Embedding architecture. All input modalities (text, images, video, audio, documents) pass through a single Gemini multimodal backbone, optionally conditioned on the task type. The output is a 3072-dimensional embedding with Matryoshka nesting: truncating to the first 768 or 256 dimensions yields a valid embedding at reduced fidelity [16][17].

Example 24 (Unified Multimodal Product Search).

Consider an e-commerce platform that needs to support the following queries, all directed at the same product catalog:

  1. A text query: “red running shoes with white soles.”

  2. A photograph of a shoe the customer saw on the street.

  3. A voice description: the customer speaks “I'm looking for something like the shoes in that marathon video.”

  4. A screenshot from a product review video.

With a natively multimodal embedding model, all four queries are embedded into the same 3072-dimensional space. The product catalog is indexed once (each product's canonical image embedded as a retrieval_document). A single nearest-neighbor search retrieves relevant products for any query modality. No modality-specific retrieval pipeline is needed. This is not a thought experiment; it is the architecture that Gemini Embedding enables in production systems [18].

The Modality Gap Problem

Despite the elegance of shared embedding spaces, a persistent and somewhat mysterious phenomenon plagues all multimodal embedding models: the modality gap. When one visualizes the embedding space (via t-SNE, UMAP, or even by simply examining inter-modality versus intra-modality distances), a striking pattern emerges. Embeddings from the same modality cluster together, forming modality-specific “islands” in the shared space, separated by a persistent gap. Text embeddings occupy one region, image embeddings occupy another, and audio embeddings occupy a third, even when the text, image, and audio all describe the same semantic content.

This is deeply counterintuitive. The contrastive training objective explicitly pulls semantically related cross-modal pairs together. Why, then, do the modalities refuse to fully overlap?

Definition 39 (Modality Gap).

Let fm,fn be encoders for modalities m and n, mapping to a shared embedding space d. The modality gap is defined as the difference between the mean inter-modality distance and the mean intra-modality distance: (Modality GAP)Δm,n=𝔼𝒙𝒳m,𝒚𝒳n[fm(𝒙)fn(𝒚)]12(𝔼𝒙,𝒙𝒳m[fm(𝒙)fm(𝒙)]+𝔼𝒚,𝒚𝒳n[fn(𝒚)fn(𝒚)]). A positive Δm,n indicates that cross-modal distances exceed intra-modal distances on average, i.e., a modality gap exists.

The gap is not a training failure; it is a geometric consequence of high-dimensional contrastive learning. The explanation lies in what has been called the cone effect.

The Cone Effect.

When modality-specific encoders are initialized independently (as they must be, since they process different input types), their initial embeddings occupy different, nearly orthogonal regions of the high-dimensional sphere 𝕊d1. In high dimensions, two random unit vectors are nearly orthogonal with overwhelming probability: for 𝒛1,𝒛2Uniform(𝕊d1), 𝔼[𝒛1,𝒛2]=0 and Var(𝒛1,𝒛2)=1/d, so the cosine similarity concentrates tightly around zero for large d.

Each modality's embeddings initially lie in a narrow cone centered around a modality-specific mean direction 𝒛m. Contrastive training pulls matched cross-modal pairs closer, but it does so within the constraint that all embeddings remain on the unit sphere. The optimization can rotate the cones toward each other, but fully merging them would require every modality encoder to produce identical representations for semantically identical inputs across fundamentally different input spaces. This is an overconstrained problem: the encoders must simultaneously maintain intra-modal discriminability (distinguishing different inputs within a modality) and achieve cross-modal alignment, and these objectives are in tension.

Theorem 7 (Modality Gap Lower Bound).

Let fm,fn:𝒳𝕊d1 be two encoders mapping to the unit sphere in d. Suppose each modality has intra-modal angular spread σm and σn respectively, defined as σm2=𝔼[fm(𝒙)𝒛m2] where 𝒛m=𝔼[fm(𝒙)]/𝔼[fm(𝒙)] is the modality centroid direction. If the contrastive loss achieves a cross-modal alignment of α=𝔼[fm(𝒙),fn(𝒚)] for matched pairs, the modality gap satisfies (GAP Lower Bound)Δm,n2(1α)σm+σn2. In particular, Δm,n>0 whenever α<1(σm+σn)2/8, which holds for any non-trivial embedding with finite intra-modal diversity.

Proof.

For unit vectors 𝒛m,𝒛n on 𝕊d1, the Euclidean distance satisfies 𝒛m𝒛n=22𝒛m,𝒛n=2(1cosθ) where θ is the angle between them.

For the inter-modality term, by Jensen's inequality: 𝔼[fm(𝒙)fn(𝒚)]2(1𝔼[fm(𝒙),fn(𝒚)])=2(1α), where the inequality follows from the concavity of applied with Jensen reversed (the square root is concave, so Jensen gives an upper bound on the expectation; here we use the lower bound on the mean distance via the relationship between 𝔼[] and 𝔼[]).

For the intra-modality terms, by the triangle inequality and the definition of angular spread: 𝔼[fm(𝒙)fm(𝒙)]σm+σm=2σm (this is a loose bound, but sufficient). Substituting into the definition of Δm,n yields the result.

The modality gap, visualized. Despite contrastive training that pulls semantically matched cross-modal pairs together, embeddings from each modality cluster into separate cones centered on modality-specific mean directions 𝒛m. The angular separation between cone centroids (the modality gap Δm,n) persists even in well-trained models, a consequence of the geometric constraints of high-dimensional unit sphere embeddings.

Comparison of Multimodal Embedding Models

The landscape of multimodal embedding models has evolved rapidly. Table 8 summarizes the key characteristics of the most influential models.

ModelModalitiesArch.Dim.MatryoshkaKey Innovation
CLIP [9]Text, ImageSep.512/768NoLarge-scale contrastive
image-text pretraining
[3pt] ALIGN [19]Text, ImageSep.640NoNoisy data at extreme
scale (1.8B pairs)
[3pt] SigLIP [20]Text, ImageSep.768/1152NoSigmoid loss replaces
softmax contrastive
[3pt] BLIP-2 [21]Text, ImageSep.768NoQ-Former bridge
between modalities
[3pt] CLAP [22]Text, AudioSep.512NoContrastive language-
audio pretraining
[3pt] ImageBind [15]6 modalitiesSep.1024NoImage-anchored binding
of all modalities
[3pt] Gemini Emb. [16]5 modalitiesUni.3072YesNative multimodal
with task conditioning
Comparison of multimodal embedding models. “Modalities” lists the input types supported. “Architecture” indicates whether the model uses separate encoders per modality (Sep.) or a unified backbone (Uni.). “Dim.” is the embedding dimensionality. “Matryoshka” indicates support for nested dimensionality reduction.

Algorithm 8 (Multimodal Retrieval with Matryoshka Embeddings).

  1. Input: Multimodal corpus 𝒞, embedding model f, Matryoshka dimensions d1<d2<<dL=d, candidate counts k1>k2>>kL
  2. Output: Top-kL retrieval results for query q
  3. Offline indexing:
  4. for each document c𝒞
  5. 𝒅f(c)d Full embedding
  6. Store 𝒅1:d1 in coarse index I1
  7. Store 𝒅 in full index IL
  8. Online retrieval:
  9. 𝒒f(q)d Embed query
  10. 𝒮1ANN(I1,𝒒1:d1,k1) Coarse retrieval: fast, low-dim
  11. for =2,,L
  12. 𝒮argsortc𝒮1(𝒒1:d,f(c)1:d)[1:k] Re-rank with finer embedding
  13. return 𝒮L

The algorithm above illustrates the coarse-to-fine retrieval pipeline enabled by Matryoshka embeddings. The coarse stage uses low-dimensional prefixes for fast candidate generation over the entire corpus, while successive re-ranking stages use progressively higher-dimensional prefixes on progressively smaller candidate sets. This yields a total retrieval cost that is dominated by the coarse stage, with re-ranking adding negligible overhead.

Proposition 21 (Matryoshka Retrieval Speedup).

Let the ANN search cost be O(dN11/d) for dimension d and corpus size N (the typical scaling for locality-sensitive hashing). A two-stage Matryoshka retrieval with coarse dimension d1 and fine dimension dL, retrieving k1 candidates in the coarse stage, has total cost (Matryoshka Speedup)TMat=O(d1N11/d1+dLk1). When k1N11/d1, the speedup over single-stage retrieval at full dimension is approximately (dL/d1)N1/d11/dL, which is substantial for large N.

Several trends emerge from this comparison. First, the field is moving from bimodal (text-image only) to truly multimodal systems. Second, embedding dimensionality is increasing, reflecting the need to capture richer semantic information across more modalities. Third, the architectural trend is toward unified backbones rather than separate encoders, leveraging the internal multimodal representations of large foundation models. Fourth, Matryoshka representations are emerging as a practical necessity for production systems that must balance accuracy against latency and storage costs.

Exercise 38 (Modality Gap Measurement).

Download a pretrained CLIP model and compute embeddings for 1000 matched image-text pairs from the COCO Captions dataset.

  1. Compute the modality gap Δtext,img using (Modality GAP). Is it positive?

  2. Visualize the embeddings using t-SNE with perplexity 30. Do you observe separate modality clusters?

  3. Compute the modality centroid directions 𝒛text and 𝒛img and measure the angle between them. How does this angle relate to the modality gap?

  4. Apply PCA to remove the first principal component (which often captures the modality gap direction). Re-measure Δtext,img. Does the gap shrink? Does retrieval accuracy change?

Cross-Modal Retrieval

With multimodal embedding spaces established, we turn to the central capability they enable: cross-modal retrieval, the task of using a query in one modality to retrieve relevant results in another. This is not merely a technical exercise; it is a fundamental shift in how humans can interact with information. Instead of being confined to searching text with text queries or images with image queries, cross-modal retrieval allows a user to hum a melody and find the music video, sketch a rough drawing and find photographs, or describe a sound in words and find audio recordings.

The mathematical framework is a natural extension of single-modal retrieval to the cross-modal setting.

Definition 40 (Cross-Modal Retrieval).

Let 𝒳Q and 𝒳D be the query and document modality spaces, with encoders fQ:𝒳Qd and fD:𝒳Dd mapping to a shared embedding space. Given a query 𝒒𝒳Q and a corpus 𝒞={d1,,dN}𝒳D, the cross-modal retrieval task returns the ranked list (Crossmodal Ranking)π(𝒒)=argsorti{1,,N}(fQ(𝒒),fD(di)), where , is the inner product after 2-normalization (i.e., cosine similarity).

Text-to-Image and Image-to-Text Retrieval

Text-image retrieval is the most extensively studied cross-modal task, catalyzed by the success of CLIP [9] and the abundance of web-crawled image-text pairs. The task comes in two directions: text-to-image (given a caption, find the matching image) and image-to-text (given an image, find the matching caption).

These two directions are not symmetric in difficulty. Image-to-text retrieval is generally easier because a single image typically has many valid textual descriptions (a photograph of a dog in a park can be described as “a dog playing in the grass,” “a golden retriever in a park,” “an animal outdoors on a sunny day,” etc.), so the retrieval system has many correct targets. Text-to-image retrieval is harder because a specific textual description typically matches fewer images in the corpus.

Remark 31 (The Asymmetry of Cross-Modal Recall).

On standard benchmarks (Flickr30k, COCO), text-to-image Recall@1 is consistently 2–5 percentage points lower than image-to-text Recall@1 for the same model. This is not a model deficiency but a reflection of the one-to-many mapping from images to descriptions. For a corpus of N images each with K captions, the image-to-text task has K correct answers per query but the text-to-image task has only 1 correct answer per query (or a small number, when multiple images share similar content). This combinatorial asymmetry inflates image-to-text recall relative to text-to-image recall.

The state-of-the-art approach follows a two-stage pipeline. In the embedding stage, both the query and all corpus items are encoded into the shared space. In the retrieval stage, approximate nearest neighbor (ANN) search identifies the top-k candidates. The embedding stage is dominated by the encoder's computational cost (a forward pass through a Transformer), while the retrieval stage is dominated by the ANN search cost (sublinear in N for tree-based or graph-based indices).

Proposition 22 (Hard Negative Mining for Cross-Modal Training).

Let (𝒒,𝒅+) be a matched query-document pair and {𝒅j}j=1B1 be in-batch negatives. Define the hardness of a negative as hj=fQ(𝒒),fD(𝒅j). The gradient of the InfoNCE loss with respect to the query encoder parameters 𝜽 is (HARD NEG Gradient)𝜽=𝜽fQ(𝒒),fD(𝒅+)+j=1B1wj𝜽fQ(𝒒),fD(𝒅j), where wj=exp(hj/τ)/kexp(hk/τ) is the softmax weight over negatives. Hard negatives (large hj) receive exponentially more gradient weight. This implies that the most informative training signal comes from negatives that the current model confuses with positives, not from trivially distinguishable negatives.

In practice, hard negative mining is critical for achieving strong cross-modal retrieval. Training with random negatives converges quickly to a “good enough” alignment but plateaus well below the performance achievable with carefully mined hard negatives. The most effective approach uses the current model to find hard negatives within a large candidate pool, then trains on batches enriched with these hard negatives.

For SigLIP [20], the contrastive loss is reformulated using a sigmoid function applied to each query-document pair independently, rather than the softmax over the batch used in CLIP. This removes the requirement for a global normalization across the batch and enables more stable training at very large batch sizes.

Text-to-Audio and Audio-to-Text Retrieval

The extension of contrastive alignment from the visual domain to audio produced CLAP (Contrastive Language-Audio Pretraining) [22], which learns a shared embedding space for text and audio. CLAP follows the same architectural blueprint as CLIP: a text encoder (typically a pretrained language model) and an audio encoder (typically a convolutional or Transformer model operating on mel-spectrogram inputs) are trained with contrastive loss on paired (text, audio) data.

The formal objective is identical to CLIP's InfoNCE loss, with the image encoder replaced by an audio encoder: (CLAP LOSS)CLAP=1Bi=1Blogexp(ft(𝒙it),fa(𝒙ia)/τ)j=1Bexp(ft(𝒙it),fa(𝒙ja)/τ), where ft is the text encoder, fa is the audio encoder, (𝒙it,𝒙ia) are matched text-audio pairs, and B is the batch size.

The unique challenges of text-audio retrieval include:

  • Temporal extent: Audio events unfold over time. A text description may refer to the overall scene (“a busy street”), a specific event (“a car horn honking”), or a temporal pattern (“footsteps gradually getting louder”). The audio encoder must capture temporal structure at multiple scales.

  • Polyphony: Natural audio contains multiple simultaneous sources. A recording of “birds singing in a forest with a stream” contains at least three overlapping sound classes. The embedding must represent this compositional structure.

  • Data scarcity: Compared to the billions of image-text pairs available on the web, text-audio pairs are orders of magnitude rarer. AudioCaps contains only 46k clips; Clotho contains only 5k.

Despite these challenges, CLAP enables compelling applications: natural language audio search (“find me the sound of rain on a tin roof”), audio captioning (generating text descriptions of audio), and zero-shot audio classification (classifying sounds using text labels without task-specific training).

Remark 32 (The Audio Embedding Landscape).

The audio modality occupies a curious middle ground between text and vision. Like text, audio is temporal and sequential. Like vision, audio is dense and continuous (when represented as a spectrogram). This dual nature means that audio embeddings can borrow techniques from both NLP (transformer architectures for sequential modeling) and computer vision (patch-based tokenization of spectrograms, treating them as “images”). The most successful audio encoders, including those used in CLAP and ImageBind, exploit this duality: they convert audio to mel-spectrograms and process them with architectures originally designed for images, while also using positional encodings that respect the temporal ordering of spectrogram patches. The fact that this “audio as image” approach works so well is itself evidence that the boundary between modalities is less fundamental than it appears.

Video-Text Retrieval

Video-text retrieval adds the dimension of temporal complexity. A video is not merely a collection of frames but a sequence of events, actions, and state changes that unfold over time. A text description of a video may refer to a single moment (“the cat jumps onto the table”), a temporal sequence (“first the chef chops onions, then adds them to the pan”), or a high-level summary (“a cooking tutorial for French onion soup”).

The computational challenge is also more severe. Encoding a video requires processing dozens to hundreds of frames. Naive approaches that encode every frame independently and aggregate the embeddings lose temporal information. More sophisticated approaches use temporal attention mechanisms, 3D convolutions, or video-specific Transformer architectures, but these increase computational cost proportionally.

Example 25 (Temporal Sensitivity in Video Retrieval).

Consider two videos: (A) a person picks up a cup, drinks from it, and puts it down; (B) a person puts down a cup, picks it up, and drinks from it. The same set of frames appears in both videos, but in different temporal order. A frame-level embedding that ignores temporal order would assign identical representations to both videos, yet the text descriptions “picking up a cup and drinking” and “putting down a cup, then picking it up” should retrieve different videos. This illustrates why temporal modeling is essential: the embedding must be order-sensitive, not just content-sensitive.

Historical Note.

From keyword search to semantic search to multimodal search. The evolution of information retrieval is a story of steadily expanding the definition of “relevance.” In the 1960s, keyword-based systems matched documents to queries by exact term overlap. In the 1990s, latent semantic indexing (LSI) introduced the idea that documents could be relevant even without sharing exact terms, by projecting both queries and documents into a low-dimensional space via SVD. In the 2010s, neural embeddings (Word2Vec, then BERT) made this projection learned and context-dependent. In the 2020s, multimodal embeddings extended relevance across modalities: an image can be “relevant” to a text query, a sound can be “relevant” to a visual query.

Each expansion required not just better algorithms but a broader theory of relevance. The mathematical frameworks evolved from Boolean logic (keyword matching) to linear algebra (LSI) to metric geometry (neural embeddings) to the cross-modal alignment theory we develop in this chapter. The common thread is the reduction of relevance to proximity in a learned space.

Any-to-Any Retrieval: The Ultimate Goal

The logical endpoint of multimodal embedding spaces is any-to-any retrieval: the ability to use a query in any modality to retrieve results in any other modality. With M modalities, this subsumes all M2 directed retrieval tasks (including intra-modal retrieval as a special case) under a single framework.

Definition 41 (Any-to-Any Retrieval System).

An any-to-any retrieval system is a tuple (,f,𝒞,s) where:

  1. ={1,,M} is a set of modalities.

  2. f:m𝒳md is a unified encoder (or a collection of aligned encoders) mapping any modality to a shared embedding space.

  3. 𝒞=m𝒞m is a multimodal corpus, where 𝒞m𝒳m is the sub-corpus for modality m.

  4. s:d×d is a similarity function (e.g., cosine similarity).

For any query q𝒳m (any modality m), the system returns the ranked list over the entire multimodal corpus: (ANY TO ANY Ranking)π(q)=argsortc𝒞(s(f(q),f(c))).

The cross-modal retrieval matrix showing which modality pairs have trained retrieval models (green), which rely on emergent zero-shot transfer through the image hub (amber), and which are intra-modal tasks (blue). The asymmetry of the matrix reflects the current state of the field: image-centric pairs have direct training data, while other combinations depend on transitive alignment through ImageBind [15].

Zero-Shot Cross-Modal Transfer

The most intellectually satisfying capability of unified embedding spaces is zero-shot cross-modal transfer: performing retrieval between modality pairs for which no paired training data exists. ImageBind [15] demonstrates this concretely: given only (image, audio) and (image, text) training pairs, the model can perform audio-to-text retrieval without having seen a single audio-text pair.

This capability has profound implications for scalability. With M modalities, direct pairwise alignment requires (M2) paired datasets. For M=6 (ImageBind's setting), that is 15 datasets. But with zero-shot transfer through an anchor modality, only M1=5 datasets are needed (one per non-anchor modality paired with the anchor). The savings grow quadratically: for M=10 modalities, direct alignment needs 45 datasets versus only 9 for anchor-based alignment.

The mechanism is simple but profound. The image encoder creates a “bridge” in embedding space. An audio clip of a barking dog maps near the embedding of a photograph of a barking dog (because they were trained on image-audio pairs). The photograph of a barking dog maps near the embedding of the text “a dog barking” (because they were trained on image-text pairs). By transitivity, the audio clip maps near the text, enabling audio-to-text retrieval.

Zero-shot cross-modal transfer via the image bridge. Audio and image encoders are trained together (left solid arrow), and image and text encoders are trained together (right solid arrow). In the shared embedding space, the audio embedding fa(𝒙a) lands near the image embedding fI(𝒙I), which lands near the text embedding ft(𝒙t). By transitivity, the audio and text embeddings are close (dashed arrow), enabling zero-shot audio-to-text retrieval.

Lemma 6 (Transfer Loss Through the Bridge).

Let εmI=1𝔼[fm(𝒙),fI(𝒙I)] and εIn=1𝔼[fI(𝒙I),fn(𝒚)] be the alignment errors for modality m to image and image to modality n, respectively, measured on semantically matched inputs. The expected zero-shot cross-modal similarity satisfies (Transfer LOSS)𝔼[fm(𝒙),fn(𝒚)]1εmIεIn2εmIεIn. The transfer loss (the reduction in expected similarity due to the indirection through the image bridge) is at most εmI+εIn+2εmIεIn.

Proof.

By the triangle inequality on the unit sphere, for unit vectors 𝒛m,𝒛I,𝒛n: 𝒛m𝒛n𝒛m𝒛I+𝒛I𝒛n. Using 𝒛m𝒛I2=2(1𝒛m,𝒛I)=2εmI and similarly for the other term: 2(1𝒛m,𝒛n)=𝒛m𝒛n2(𝒛m𝒛I+𝒛I𝒛n)2=2εmI+2εIn+24εmIεIn. Rearranging and taking expectations yields the stated bound.

The practical implication is that the transfer loss grows as the sum (not the product) of the individual alignment errors, plus a geometric mean term. If both pairwise alignments are good (εmI,εIn0.1), the transfer loss is at most 0.1+0.1+20.01=0.4, which implies a zero-shot similarity of at least 0.6. This is tight enough for many retrieval applications.

Information-Theoretic Limits of Cross-Modal Retrieval

We now ask a deeper question: given a fixed embedding dimension d, what is the maximum possible retrieval performance? This is fundamentally an information-theoretic question, because the embedding acts as a lossy compression of the input, and the retrieval accuracy depends on how much information about the relevant document is preserved in the compressed representation.

The framework of rate-distortion theory [37][4] provides the right lens. We can view the embedding as a channel through which information about the query's semantic content is transmitted. The embedding dimension d constrains the capacity of this channel.

Definition 42 (Embedding Channel Capacity).

Let Q𝒳Q be a random query and D𝒳D be its relevant document. The embedding functions fQ and fD define an embedding channel from Q to the retrieved document D^. The embedding channel capacity is the maximum mutual information between the query and the retrieved document, optimized over all retrieval strategies: (Channel Capacity)C(d)=supfQ,fD𝖨(Q;D^|fQ,fD), where the supremum is over all encoder pairs (fQ,fD) mapping to d, and D^ is the nearest-neighbor retrieval result in the embedding space.

Theorem 8 (Embedding Bottleneck).

For d-dimensional embeddings with 2-normalized vectors (i.e., embeddings lie on 𝕊d1), the mutual information between the query Q and the retrieved document D^ is bounded by (Bottleneck Bound)𝖨(Q;D^)d2log2(1+N2/dπe)bits, where N is the corpus size. For a corpus of N documents in which exactly one is relevant, correct retrieval requires 𝖨(Q;D^)log2N bits, yielding the minimum embedding dimension (MIN Dimension)dmin2log2Nlog2(1+N2/dmin/(πe)). For large N, this simplifies to dmin=Ω(logN).

Proof sketch.

The key idea is that d-dimensional unit sphere embeddings can encode at most O(dlogN) bits of information about corpus membership, because the ϵ-covering number of 𝕊d1 is (const/ϵ)d. To distinguish N corpus items, we need the embeddings to be at least ϵ-separated, with ϵN1/d.

More precisely, by a sphere-packing argument, the maximum number of non-overlapping spherical caps of angular radius θ on 𝕊d1 is bounded by the Rankin bound: M(θ,d)(sinθ)(d1). Setting M=N and solving for the information content of the angular position yields the stated bound. The factor of πe arises from the Gaussian approximation to the cap volume in high dimensions.

Remark 33 (Practical Implications of the Bottleneck).

For a corpus of N=109 (one billion) documents, the theorem implies dmin=Ω(30), which is trivially satisfied by modern embeddings (256 to 3072 dimensions). The theorem tells us that most of the embedding capacity in current systems is used for fine-grained discrimination, not for raw identification. This excess capacity is what enables approximate retrieval: even if the nearest-neighbor search is approximate (returning a result within a factor of 1+ϵ of the true nearest neighbor), the rich geometry of the embedding space ensures that the result is still semantically close to the query.

Exercise 39 (Rate-Distortion Bound for Matryoshka Embeddings).

Consider a Matryoshka embedding with nested dimensions d1=64,d2=256,d3=1024,d4=3072. For a corpus of N=108 documents:

  1. Compute the embedding bottleneck bound ((Bottleneck Bound)) for each dimension d.

  2. At which dimension d does the bound first exceed log2N26.6 bits, the minimum information needed to uniquely identify the correct document?

  3. In practice, retrieval accuracy improves well beyond the point where the information-theoretic minimum is met. Why? (Hint: the bound assumes adversarial corpus construction. Real corpora have structure.)

Downstream Applications of Foundational Embeddings

The preceding sections have developed the mathematical foundations of multimodal embedding spaces and cross-modal retrieval. Now we turn to the question that ultimately justifies all this theory: what can you build with it? The answer, it turns out, is astonishingly broad. Foundational embeddings are not merely a better search engine. They are a new computational primitive, a universal similarity function that can be composed, filtered, combined, and reasoned over to create applications that would have been inconceivable five years ago.

We survey established applications, then venture into speculative territory where the most exciting possibilities live.

Key Idea.

Embeddings as a Computational Primitive. A foundational embedding is not an application; it is a primitive, like addition or sorting, upon which applications are built. The key operations on this primitive are:

  1. Similarity: s(𝒙,𝒚)=f(𝒙),f(𝒚) compares any two inputs across any modalities.

  2. Retrieval: arg maxd𝒞f(q),f(d) finds the most relevant item in any corpus for any query.

  3. Clustering: k-means or spectral clustering on {f(xi)} groups semantically related items regardless of modality.

  4. Arithmetic: f(“king”)f(“man”)+f(“woman”)f(“queen”) performs analogical reasoning in embedding space.

  5. Interpolation: λf(𝒙)+(1λ)f(𝒚) blends the semantics of two inputs.

Every application in this section is built from these five operations, composed in different ways for different purposes.

Creative Discovery and Artistic Exploration

The art world has always been organized by metadata: artist name, year, medium, movement, gallery. But the most interesting connections between artworks are often visual, connections that defy textual categorization. A Rothko color field and a Turner seascape share a luminous quality that no tag captures. A Hokusai wave and a Van Gogh night sky share a dynamic spiral energy that is felt rather than described.

Multimodal embeddings make these felt connections computable. By embedding artworks into a shared space, one can retrieve “paintings that feel like this one” without needing to articulate what “feel like” means. The embedding captures the visual gestalt, the holistic perceptual impression that resists decomposition into discrete attributes.

But the truly novel capability is cross-modal creative retrieval. Given a piece of music, find paintings that evoke the same mood. Given a poem, find photographs that capture the same atmosphere. Given a perfume description (“woody, with notes of cedar and a hint of vanilla”), find visual artworks that evoke the same sensory palette. These queries are absurd in a keyword-based system. In a multimodal embedding space, they are just nearest neighbor searches.

Example 26 (Synesthetic Art Curation).

A museum curator wants to design an exhibition called “The Sound of Blue,” pairing visual artworks with musical compositions. Using a multimodal embedding model:

  1. Embed all visual artworks in the collection (12,000 paintings and sculptures, photographed and embedded as images).

  2. Embed a curated library of musical compositions (5,000 tracks, embedded as audio).

  3. For each artwork, retrieve the 5 nearest musical compositions in embedding space.

  4. For each piece of music, retrieve the 5 nearest artworks.

  5. The curator reviews these pairings, selecting those that resonate artistically, a human-AI collaboration where the embedding model proposes and the curator disposes.

The result is an exhibition where visitors hear music that “matches” each painting, not through explicit programming but through the emergent geometry of a shared semantic space.

Accessibility Through Retrieval

For the 2.2 billion people worldwide with vision impairment, the visual world is mediated by descriptions. Alt text on web images, screen reader outputs, and audio descriptions of videos are critical accessibility tools, but they are expensive to produce manually and are missing for the vast majority of visual content.

Embedding-based retrieval offers a scalable alternative. Given an image that lacks a description, retrieve the most similar image in a database of described images, and transfer its description. The key insight is that descriptions do not need to be generated from scratch; they can be retrieved from a large pool of existing descriptions.

Key Idea.

Retrieval-Augmented Description. For an undescribed image 𝒙, compute its embedding f(𝒙)d. Retrieve the k nearest described images from a reference database: {(𝒙i,ti)}i=1k where ti is the text description of image 𝒙i. The transferred description is a function of the retrieved descriptions: (Transferred Description)t^(𝒙)=g(t1,,tk;s1,,sk), where si=f(𝒙),f(𝒙i) is the similarity score and g is an aggregation function (e.g., the description of the nearest neighbor, or an LLM-generated summary of the top-k descriptions weighted by similarity).

This approach has a crucial advantage over pure generation: the descriptions are grounded in human-written text, reducing the risk of hallucinated or misleading content. A visually impaired user receives a description that was written by a human for a visually similar image, not fabricated by a model that might confuse a cat for a dog.

The same principle extends to audio accessibility. A deaf user encountering a video can benefit from retrieved descriptions of similar audio tracks. If the video's soundtrack is similar (in embedding space) to a previously described audio clip, the existing description can be transferred: “sounds of traffic and distant sirens” provides environmental context that a visual-only experience cannot convey. Cross-modal retrieval thus becomes a bridge between sensory experiences, using the information available in one modality to augment the experience of another.

Content Moderation at Scale

Content moderation is one of the most consequential applications of embedding-based retrieval. Platforms hosting user-generated content must identify and remove harmful material, including known child sexual abuse material (CSAM), violent extremist content, copyright-infringing material, and spam, at a scale of billions of uploads per day.

The traditional approach uses perceptual hashing (e.g., PhotoDNA for images, MD5 hashes for exact duplicates), which matches against a database of known harmful content. Perceptual hashes are fast and deterministic but brittle: a simple crop, resize, or color shift can evade detection.

Embedding-based retrieval replaces the hash with a learned representation that is robust to superficial transformations. A harmful image and its cropped, resized, or color-shifted variant map to nearby points in embedding space, enabling detection even when the content has been deliberately modified to evade hash-based systems.

Caution.

Bias in embedding-based moderation. Embedding models inherit biases from their training data. Studies have shown that CLIP-based embeddings associate certain demographics with harmful content at higher rates than others, reflecting biases in the web-crawled training data. A content moderation system built on biased embeddings will over-flag content from underrepresented groups and under-flag content from overrepresented groups. This is not a hypothetical risk; it has been documented in deployed systems [9]. Any production deployment of embedding-based moderation must include bias auditing, per-group false-positive rate monitoring, and human review for edge cases.

Scientific Discovery Across Modalities

Science communicates through a rich multimodal fabric: papers contain text, equations, figures, tables, and citations; datasets contain numbers, images, and metadata; presentations contain slides, speech, and video. Traditional scientific search operates almost exclusively on text (titles, abstracts, keywords), leaving the vast majority of scientific content unsearchable.

Multimodal embeddings open the door to searching the full fabric of scientific communication. Consider these scenarios:

  • Figure-to-paper retrieval: A researcher has a figure from a conference talk but cannot remember which paper it came from. Embed the figure, search against a database of paper figures, retrieve the source paper.

  • Text-to-figure retrieval: A researcher writing a survey wants to find all published figures that visualize “attention weights in transformer models.” A text query retrieves relevant figures from across the literature.

  • Equation-to-paper retrieval: A researcher encounters an equation and wants to find its origin or related work. If equations are rendered as images, they can be embedded and matched against a database of equation images from published papers.

  • Data-to-method retrieval: Given a dataset's characteristics (embedded as a structured description), retrieve papers that have achieved good results on similar datasets.

Research 3.

Open problem: Embedding scientific equations. Equations are the most information-dense modality in scientific communication, yet they are poorly served by current embedding models. An equation like tρ+(ρ𝒙)=0 is not “an image” (it has precise symbolic structure), not “text” (it uses mathematical notation that NLP tokenizers mangle), and not “structured data” (it has semantic meaning beyond its syntactic form). Developing embedding models that natively understand the structure and semantics of mathematical notation, mapping equations with the same mathematical content but different notational conventions to nearby points, is an open problem with enormous potential impact on scientific information retrieval.

Multimodal Product Search

E-commerce was among the first industries to deploy multimodal embeddings at scale. The use case is intuitive: a customer sees a pair of shoes on the street, takes a photograph, and searches for similar products. Or a customer describes what they want in natural language: “a mid-century modern coffee table in walnut with tapered legs.” Or a customer provides an image of their living room and asks for furniture that would “go with” the existing decor.

Each of these queries leverages a different modality (image, text, or image-as-context), but all are resolved by the same mechanism: embed the query, search the product embedding index, return the nearest neighbors.

The commercial impact is substantial. Visual search increases conversion rates by 30–50% compared to text-only search for categories where visual appearance dominates the purchase decision (fashion, furniture, home decor). Multimodal search, combining text and image cues, performs even better because it captures both the visual gestalt and the specific attributes the customer cares about.

Example 27 (Hybrid Text-Image Product Queries).

A customer uploads a photograph of a blue ceramic vase and adds the text “something like this but taller and in terracotta.” The retrieval system must combine two signals: the visual similarity to the photograph (shape, texture, style) and the textual modification (taller, terracotta). One approach embeds the image and text separately, then combines them: (Hybrid Query)𝒒hybrid=λfimg(𝒙photo)+(1λ)ftext(𝒙description), where λ[0,1] controls the balance between visual and textual cues. A more sophisticated approach uses a cross-attention mechanism that conditions the image embedding on the text, allowing the text to “edit” the visual query in embedding space. The latter approach better handles instructions like “same shape but different color,” where the text specifies which visual attributes to preserve and which to modify.

Remark 34 (Cold Start in Product Search).

New products present a cold-start problem for recommendation systems but not for embedding-based search. A product with zero purchase history and zero clicks can still be retrieved if its image and description produce an embedding close to the user's query. This is a fundamental advantage of content-based retrieval (via embeddings) over collaborative filtering: relevance is determined by the intrinsic properties of the product, not by the behavior of other users. For platforms with rapidly changing catalogs (fashion retailers adding hundreds of new items daily), this property is essential.

Cross-Modal Medical Retrieval

The medical domain presents a particularly compelling case for cross-modal retrieval because clinical decision-making inherently involves multiple modalities: radiology images (X-rays, CT scans, MRIs), clinical notes (free text), laboratory results (structured data), pathology slides (microscopy images), and patient histories (longitudinal text).

Example 28 (Case-Based Diagnostic Retrieval).

A radiologist examines a chest X-ray showing an unusual opacity. Using a cross-modal retrieval system, they can:

  1. Image-to-image: Find prior chest X-rays with similar opacities, along with their confirmed diagnoses.

  2. Image-to-text: Retrieve clinical notes from cases with similar imaging findings, providing context on symptoms, comorbidities, and outcomes.

  3. Text-to-image: Query “ground-glass opacity in the right lower lobe with pleural effusion” and retrieve matching images from the hospital's archive.

  4. Multimodal-to-multimodal: Combine the X-ray image with the patient's clinical notes to retrieve the most similar complete cases (image + text jointly).

This is not a replacement for clinical judgment; it is evidence-based medicine operationalized as nearest-neighbor search in embedding space.

The privacy implications are severe. Medical embeddings must be designed so that patient-identifying information cannot be reconstructed from the embedding vector, even under adversarial attack. This connects to the broader field of privacy-preserving embeddings, where differential privacy or adversarial debiasing techniques are applied during embedding training to ensure that sensitive attributes are not encoded in the representation.

Definition 43 (Privacy-Preserving Embedding).

A privacy-preserving embedding fϵ:𝒳d satisfies (ϵ,δ)-differential privacy if for any two inputs 𝒙,𝒙 differing in a single patient attribute, and any measurable set Sd: (DP Embedding)Pr[fϵ(𝒙)S]eϵPr[fϵ(𝒙)S]+δ. The privacy-utility tradeoff is governed by the relationship between ϵ (privacy budget), d (embedding dimension), and retrieval accuracy: lower ϵ provides stronger privacy but degrades the embedding's discriminative power.

The formal tension between privacy and utility in medical embeddings is a special case of a fundamental information-theoretic tradeoff. The embedding must contain enough information to discriminate between different medical conditions (for retrieval to be useful) but not enough to identify individual patients (for privacy to be maintained). Formalizing this tradeoff and finding the Pareto frontier between privacy and retrieval accuracy is an active area of research with significant clinical implications.

Beyond the Horizon: Visionary Applications

The applications surveyed above are either deployed or under active development. We now venture into more speculative territory, exploring applications that become conceivable, even if not yet practical, once we take the premises of multimodal embedding spaces to their logical conclusion. These are not idle fantasies; each follows directly from capabilities that current embedding models either already possess or are close to possessing.

Emotional Retrieval.

Emotions are arguably the most important human information modality, yet they are absent from every information retrieval system ever built. What if we could embed emotional states? A user listens to a piece of music that makes them feel melancholy. They want to find a painting that evokes the same feeling, or a poem, or a scene from a film. This is not text search (“find sad paintings”) but something deeper: the query is not a text label of the emotion but the emotion itself, as evoked by a specific sensory experience.

The path to emotional retrieval lies in the observation that multimodal embeddings already capture some emotional information. CLIP embeddings of images rated as “serene” by human annotators cluster together in embedding space, separated from images rated as “anxious” or “joyful.” This is not because CLIP was trained on emotion labels; it is because the visual features that evoke serenity (soft colors, open spaces, horizontal compositions) are correlated with the text descriptions that appear alongside such images on the web. Emotional information is already latent in the embedding geometry.

The research challenge is to amplify this latent emotional signal. Fine-tuning on emotion-annotated datasets, incorporating physiological signals (heart rate, galvanic skin response) as additional modalities, or training on affective descriptions (“this image makes me feel calm”) rather than factual ones (“a sunset over the ocean”) could produce embeddings where the emotional dimension is a first-class citizen rather than an incidental byproduct.

Thought Retrieval.

If emotional retrieval seems speculative, thought retrieval borders on science fiction, but the boundary is narrower than one might expect. Recent work in neural decoding has demonstrated that fMRI signals recorded while a subject views an image can be decoded into a representation that, when projected into CLIP embedding space, correctly identifies which image the subject was viewing from a set of candidates. The brain activity is literally being embedded into the same space as images and text.

Extend this to retrieval: a subject thinks of a visual concept, a face, a landscape, an object. Their brain activity is recorded (via fMRI, EEG, or a future non-invasive neural interface), embedded into the multimodal space, and used as a query. The system retrieves images, sounds, or text that match the subject's mental imagery. This is not content-based retrieval in the traditional sense; it is intention-based retrieval, where the query is the user's thought itself.

Insight.

The Embedding Space as a Universal Lingua Franca. The deep significance of thought retrieval is not the specific application but the principle it reveals. The multimodal embedding space is becoming a universal lingua franca for information, a space in which any form of meaning, whether expressed as text, image, sound, or neural activity, can be represented, compared, and translated. The embedding dimension d is the bandwidth of this universal language. As d grows and training data spans more modalities, the embedding space converges toward a representation of meaning itself, stripped of the accidents of its physical encoding.

Cross-Temporal Retrieval.

History is filled with recurrence. A medieval siege and a modern urban warfare scenario share tactical patterns. A 17th-century financial bubble and a 21st-century cryptocurrency crash follow similar dynamics. An Art Deco building facade and a modern minimalist building share geometric sensibilities that transcend their 80-year separation.

Cross-temporal retrieval uses embeddings to find these connections across time. Given a historical artifact (a photograph, a document, a map), retrieve its modern analog: the contemporary object, event, or concept that is most semantically similar. This requires embeddings that capture abstract patterns rather than surface features, embeddings that recognize the structural similarity between a Roman aqueduct and a modern pipeline, or between a medieval manuscript's illumination and a modern infographic's design language.

The educational potential is immense. Imagine a history student who can point their camera at a museum artifact and instantly see its modern parallels, not through manually curated links but through the emergent geometry of a well-trained embedding space.

Example 29 (Architectural Analogy Retrieval).

A database contains photographs of 50,000 historical buildings (ancient through modern) with metadata. A user photographs a Roman arch and queries for modern analogs. The embedding model, trained on diverse architectural imagery, places the Roman arch near modern structures that share its key geometric features: parabolic curves, load-bearing masonry, monumental scale. The top retrievals include a modern concrete shell structure by Félix Candela, a Santiago Calatrava bridge, and a contemporary museum entrance. None of these would be found by keyword search on “Roman architecture”; the connection is purely visual and structural, captured by the embedding geometry. The system has effectively learned an architectural “grammar” that transcends historical period.

Synesthetic Retrieval.

Synesthesia, the neurological phenomenon in which stimulation of one sense triggers an involuntary experience in another (seeing colors when hearing music, tasting shapes), has long fascinated artists and scientists. Multimodal embedding spaces make synesthetic associations computable.

What does the color blue sound like? In a well-trained multimodal embedding space, one can embed images of blue objects, retrieve the nearest audio clips, and listen to what the model “thinks” blue sounds like. What does a C-major chord look like? Embed the chord as audio, retrieve the nearest images. These queries exploit the cross-modal geometry of the embedding space to create synesthetic mappings that are data-driven rather than arbitrary.

Whether these computed synesthetic associations align with the experiences of human synesthetes is an open empirical question, one that connects computational embedding theory to the neuroscience of cross-modal perception.

Dream Indexing.

The most speculative application of all: indexing the content of dreams. As neural decoding technology advances from fMRI (expensive, slow, low temporal resolution) toward high-density EEG or optical neural interfaces (potentially portable and real-time), it becomes conceivable to record brain activity during REM sleep and embed the resulting signals into a multimodal space. The “dream embedding” would sit near images, sounds, and narratives that resemble the dream content. Upon waking, the dreamer could query their dream log: “Show me what I dreamed about last Tuesday” would return a collage of images, sounds, and text fragments that the embedding model associates with the recorded neural activity.

This application is decades away, if it is possible at all. But it illustrates the ultimate promise of multimodal embedding spaces: if any signal, from any source, can be embedded into the same space, then the space becomes a universal index of human experience.

Embedding-Mediated Translation.

A more near-term visionary application is embedding-mediated translation between modalities. Rather than training a separate generative model for each modality pair (text-to-image, image-to-audio, audio-to-video, etc.), one trains a single conditional generator that takes an embedding vector as input and produces output in a specified target modality. The embedding serves as the modality-agnostic representation of “what to generate,” and the generator handles the “how.”

Definition 44 (Embedding-Mediated Generation).

An embedding-mediated generator for modality m is a function gm:d𝒳m that maps embedding vectors to outputs in modality m. Given an input x𝒳n from any source modality n, the cross-modal generation pipeline is: (EMB Mediated GEN)y^m=gm(f(x)), where f is the multimodal encoder and gm is the modality-specific generator. This decouples the understanding of “what” (handled by f) from the generation of “how” (handled by gm), and enables cross-modal generation between any pair of modalities with only M generators rather than M2 translation models.

This architecture reduces the M2 translation problem to M generation problems, each conditioned on the same embedding space. The embedding space serves as the interlingua, the intermediate representation through which all modality pairs communicate.

The application landscape of foundational embeddings. Deployed applications (green) include product search, content moderation, accessibility, medical retrieval, scientific discovery, and creative curation. Visionary applications (orange) include emotional retrieval, thought retrieval, cross-temporal retrieval, and synesthetic retrieval. All radiate from the same foundational embedding infrastructure.

Open Problems and Research Frontiers

Research 4.

Open problems in foundational embedding applications.

  1. Compositional retrieval: Current embeddings represent holistic semantics well but struggle with compositional queries like “a red car next to a blue truck” (they may retrieve a blue car next to a red truck). How can embeddings be made compositionally faithful?

  2. Temporal dynamics in embeddings: The world changes, and so should embeddings. A photograph of the World Trade Center has fundamentally different semantic associations before and after September 2001. How should embedding models handle temporal context?

  3. Cultural grounding: Embeddings trained on English-language web data embed Western cultural associations. A model might associate “wedding” with white dresses rather than red saris. How can embeddings be culturally pluralistic?

  4. Embedding forensics: Given only an embedding vector, can one determine which model produced it, what input it encodes, or whether it has been adversarially perturbed? This is the embedding analog of image forensics.

  5. Continual embedding learning: Production corpora grow continuously. How can embedding models be updated to incorporate new concepts without catastrophic forgetting of existing representations?

  6. Grounding in physical interaction: Current embeddings capture appearance and description but not affordance. A hammer and a rock may serve the same function (driving a nail in an emergency) but look nothing alike. Can embeddings capture functional similarity alongside perceptual similarity?

  7. Theoretical limits of cross-modal alignment: What is the information-theoretic limit on how well two modalities can be aligned given finite paired data? Is there an analog of the Bayes error rate for cross-modal retrieval?

Caution.

Bias amplification in embedding-based retrieval. Retrieval systems do not merely reflect the biases in their training data; they amplify them. This amplification occurs through a feedback loop: biased embeddings produce biased retrieval results, which are presented to users, who interact with them (clicking, saving, sharing), generating interaction data that is used to fine-tune the next generation of embeddings. Each iteration tightens the bias.

Formally, let b0 be the initial bias in the embedding space (measured, e.g., as the differential association between a demographic group and positive versus negative content). After T rounds of the deploy-collect-retrain cycle, the bias amplifies to approximately bTb0(1+γ)T for a positive amplification rate γ that depends on the user interaction model. Even small initial biases (b0=0.01) can grow to problematic levels (bT>0.1) within a few retraining cycles.

Mitigations include: (a) bias auditing at each retraining cycle, (b) counterfactual data augmentation to balance demographic representation, (c) adversarial debiasing objectives during embedding training, and (d) post-hoc calibration of retrieval scores across demographic groups. None of these is sufficient alone; responsible deployment requires all four.

Exercise 40 (Building a Cross-Modal Retrieval System).

Using a pretrained multimodal embedding model (e.g., CLIP or an open-source ImageBind implementation), build a cross-modal retrieval system:

  1. Index construction: Download a multimodal dataset (e.g., AudioCaps for audio-text, or Flickr30k for image-text). Embed all items and build a FAISS index for approximate nearest neighbor search.

  2. Text-to-image retrieval: Given a text query, retrieve the top-5 images. Measure Recall@1 and Recall@5 on the test set.

  3. Image-to-text retrieval: Given an image query, retrieve the top-5 text descriptions. Compare performance with text-to-image. Is the asymmetry described in Remark 31 present?

  4. Matryoshka experiment: If using a model with Matryoshka embeddings, repeat the retrieval experiments at dimensions 256, 768, and 3072. Plot Recall@1 versus dimension. At what dimension does performance plateau?

  5. Bias audit: For a subset of queries related to people (e.g., “a person cooking”), examine the retrieved images. Is there evidence of demographic bias in the results? Propose a quantitative metric to measure this bias.

Exercise 41 (Emergent Zero-Shot Retrieval).

Using ImageBind (or an equivalent model supporting audio and text):

  1. Embed 100 audio clips and 100 text descriptions from different domains (e.g., AudioCaps for audio, hand-written descriptions for text).

  2. Perform audio-to-text retrieval: for each audio clip, retrieve the nearest text description. Evaluate the quality of matches manually on a 1–5 scale.

  3. Compare the zero-shot audio-to-text performance with the direct audio-to-image and image-to-text performance. Is the transfer loss consistent with the bound in Lemma 6?

  4. Propose an experiment to test whether longer transfer chains (e.g., audio image text video) degrade more rapidly than the lemma predicts.

Conjecture 1 (The Universal Embedding Hypothesis).

There exists a finite embedding dimension d such that all human-perceptible semantic distinctions can be faithfully represented on 𝕊d1. That is, for any two inputs x,y (in any modality) that a human judge would consider semantically different, a sufficiently well-trained universal embedding model assigns them representations with cosine similarity below a threshold τ<1, and for any two inputs that a human judge would consider semantically identical, the model assigns representations with cosine similarity above τ.

If this conjecture is true, the question shifts from “can we build a universal embedding?” to “what is d?” Current evidence suggests d10,000, but determining even an order-of-magnitude estimate remains an open problem. The conjecture connects to deep questions in cognitive science about the dimensionality of human semantic representation, and to information-theoretic questions about the intrinsic dimensionality of “meaning.”

This conjecture, if true, would imply that the era of modality-specific retrieval is a temporary phase in the history of information systems. The destination is a single embedding space, a single index, and a single retrieval mechanism for all forms of human information. The mathematical foundations developed in this chapter, from contrastive alignment to rate-distortion bounds to modality gap analysis, are the tools that will either prove or disprove this conjecture, and that will guide the engineering of the universal retrieval systems of the future.

Exercise 42 (Modality Gap Reduction Strategies).

The modality gap (The Modality Gap Problem) reduces retrieval accuracy because it biases the nearest-neighbor search toward same-modality results. Consider the following strategies for reducing the gap:

  1. Post-hoc centering: Subtract each modality's centroid from its embeddings: f~m(𝒙)=fm(𝒙)𝒛m. Re-normalize to the unit sphere. Does this eliminate the gap? What information might be lost?

  2. Shared projection head: Add a shared linear projection 𝐖d×d after all modality encoders, trained to minimize the modality gap while preserving intra-modal discriminability. Formulate this as an optimization problem with two competing objectives.

  3. Adversarial modality confusion: Train a modality classifier on top of the embeddings (“given this embedding, which modality produced it?”) and add its negative cross-entropy to the training loss, encouraging embeddings that are modality-agnostic. Why might this approach harm retrieval accuracy if applied too aggressively?

  4. Theoretical analysis: Using Theorem 7, derive conditions under which strategy (a) provably reduces the gap to zero. Under what conditions does it fail?

Exercise 43 (Information Content of Embeddings).

This exercise explores the practical implications of the embedding bottleneck theorem (Theorem 8).

  1. For a corpus of N=106 images, compute the minimum embedding dimension dmin required for unique identification. Compare this with the dimensions used by CLIP (512), ImageBind (1024), and Gemini Embedding (3072).

  2. The theorem assumes worst-case corpus construction. In practice, natural image corpora have structure (e.g., images of cats cluster together). Argue informally that this structure allows retrieval to succeed at dimensions much lower than dmin.

  3. Design an experiment to estimate the effective dimensionality of a real embedding space: the number of dimensions that carry meaningful variance. (Hint: PCA on a large set of embeddings.) How does the effective dimensionality compare with the nominal dimensionality?

  4. If we quantize each embedding coordinate to b bits (e.g., b=8 for int8 quantization), the total information capacity is db bits. For CLIP at d=512, b=32 (float32), this is 16,384 bits. How does this compare with log2N for a billion-document corpus? What does the excess capacity buy us?

Generative Reranking

You have one thousand potentially relevant documents. A simple scorer, perhaps BM25 or a bi-encoder, ranked them in a fraction of a second. But a large language model can understand nuance, context, and intent in ways that a bag-of-words statistic or a dot product in embedding space simply cannot. Can the LLM rerank those documents more accurately? Yes, and this insight is transforming the entire retrieval pipeline.

The idea is disarmingly simple: take the candidate list produced by a cheap first-stage retriever, then use a more powerful (and more expensive) model to refine the ordering. The first-stage retriever provides recall: it finds documents that might be relevant. The reranker provides precision: it puts the truly relevant documents at the top. This two-stage pattern, sometimes called retrieve-then-rerank, has become the dominant architecture in modern information retrieval.

What makes recent work exciting is the realisation that generative language models, models trained to produce text rather than classify it, can serve as extraordinarily effective rerankers. The key distinction lies in how the model processes the query and document, and how many documents it considers at once. This distinction gives rise to four paradigms: pointwise, pairwise, listwise, and setwise reranking.

Pointwise Reranking

The simplest approach scores each document independently. Given a query q and a candidate document di, the reranker produces a relevance score s(q,di) without reference to any other document in the candidate set. The final ranking is obtained by sorting documents by their scores.

Definition 45 (Pointwise Reranker).

A pointwise reranker is a function s:𝒬×𝒟 that assigns a relevance score to each query-document pair independently. Given a candidate set {d1,,dn}, the reranked list is the permutation π satisfying (Pointwise Ranking)s(q,dπ(1))s(q,dπ(2))s(q,dπ(n)).

Cross-Encoders with BERT

The cross-encoder architecture, introduced in the context of natural language inference and adapted for retrieval, concatenates the query and document into a single input sequence and passes it through a Transformer encoder [83]. The [CLS] token representation is fed to a classification head that outputs a relevance score: (Cross Encoder)s(q,d)=𝐖BERT([𝙲𝙻𝚂]q[𝚂𝙴𝙿]d)[𝙲𝙻𝚂]+b, where 𝐖h is a learned projection and b is a scalar bias. The critical advantage over bi-encoders is that the query and document tokens attend to each other throughout every Transformer layer, enabling fine-grained interaction modelling. The critical disadvantage is computational cost: a separate forward pass is required for every query-document pair.

Remark 35.

For a candidate set of n documents, the cross-encoder requires n forward passes, each with sequence length proportional to |q|+|di|. In contrast, a bi-encoder computes query and document embeddings independently, requiring only a single dot product per candidate at query time. This cost asymmetry is precisely what motivates the two-stage retrieve-then-rerank architecture: the bi-encoder handles the bulk filtering, and the cross-encoder refines a much smaller candidate set.

monoT5: Sequence-to-Sequence Relevance Scoring

Nogueira et al. [84] proposed a remarkably elegant reformulation: instead of adding a classification head to an encoder, use a sequence-to-sequence model and ask it to generate a relevance judgment. Given query q and document d, the input to T5 [85] is:

Query: $q$ Document: $d$ Relevant:

The model generates either “true” or “false” as output. The relevance score is derived from the probability assigned to the “true” token: (Monot5 Score)s(q,d)=P𝜽(“true”|q,d).

This formulation is powerful for two reasons. First, it leverages the pre-trained knowledge encoded in T5's parameters: the model has already seen billions of tokens and developed a rich understanding of relevance, topicality, and semantic similarity. Second, it requires no architectural modifications; any sequence-to-sequence model can serve as a pointwise reranker with this prompt template.

Example 30 (monoT5 in Practice).

Consider the query “What causes tides?” and two candidate documents:

  • d1: “Tides are caused by the gravitational pull of the Moon and, to a lesser extent, the Sun on Earth's oceans.”

  • d2: “The Tide brand of laundry detergent was introduced by Procter & Gamble in 1946.”

A BM25 scorer might rank both documents similarly, since both contain the word “tide.” But monoT5, processing the full query-document context, assigns P(“true”|q,d1)0.97 and P(“true”|q,d2)0.02, correctly distinguishing the oceanographic sense from the commercial one.

Pairwise Reranking

Pointwise reranking treats each document in isolation. But relevance is often relative: document dA might be hard to judge on its own, but clearly more relevant than document dB when the two are compared side by side. Pairwise reranking exploits this observation.

Definition 46 (Pairwise Reranker).

A pairwise reranker is a function c:𝒬×𝒟×𝒟[0,1] that, given a query q and two documents dA,dB, returns the probability that dA is more relevant than dB: (Pairwise Score)c(q,dA,dB)=P(dAdB|q). A full ranking is obtained by aggregating pairwise preferences, for example via a sorting algorithm that uses c as its comparison function.

duoT5: Pairwise Comparison via Generation

The duoT5 model extends the monoT5 idea to the pairwise setting. Given a query and two documents, the T5 model receives:

Query: $q$ Document0: $d_A$ Document1: $d_B$ More relevant:

The model generates either “Document0” or “Document1,” and the comparison score is: (Duot5 Score)c(q,dA,dB)=P𝜽(“Document0”|q,dA,dB).

Remark 36.

A subtle issue with pairwise reranking is that the preference function c need not be transitive. It is possible that c(q,dA,dB)>0.5 and c(q,dB,dC)>0.5 but c(q,dA,dC)<0.5, forming a preference cycle. In practice, this is rare for well-calibrated models, but sorting algorithms that assume transitivity may produce inconsistent results. The Copeland voting rule, which ranks documents by the number of pairwise victories, is a robust aggregation strategy that handles non-transitive preferences gracefully.

The principal drawback of pairwise reranking is computational. Ranking n documents requires (n2)=O(n2) pairwise comparisons in the worst case. Even with efficient sorting algorithms that require only O(nlogn) comparisons, each comparison involves a full forward pass through the language model. For large candidate sets, this cost is prohibitive.

Listwise Reranking

The natural next step is to process the entire candidate list at once. Instead of scoring documents individually or comparing them in pairs, a listwise reranker receives the query and all n candidate documents simultaneously and produces a permutation of the entire list.

Definition 47 (Listwise Reranker).

A listwise reranker is a function σ:𝒬×𝒟nSn that maps a query and an ordered list of n candidate documents to a permutation σSn, where Sn is the symmetric group on n elements. The reranked list places document dσ(1) first, dσ(2) second, and so on.

LLM Permutation Generation

Hou et al. [24] demonstrated that large language models can directly generate permutations. The prompt presents the query and a numbered list of document passages, then asks the LLM to output the passage numbers in order of decreasing relevance. For example:

I will provide a query and a list of passages. Rank the passages based on their relevance to the query. Output the ranking as a list of passage numbers from most to least relevant.

Query: $q$

Passage [1]: $d_1$

Passage [2]: $d_2$

Passage [$n$]: $d_n$

Ranking:

The model generates a sequence such as “[3] > [1] > [5] > [2] > [4],” which is parsed into the permutation σ=(3,1,5,2,4).

The appeal of listwise reranking is that the model can consider all documents simultaneously, making globally coherent comparisons. The challenge is context length: a list of even 20 moderately long passages may exceed the context window of many language models, and attention cost grows quadratically with sequence length.

Sliding Window Approaches

To handle lists longer than the context window allows, sliding window strategies partition the candidate list into overlapping windows and rerank each window independently. The results are then merged using a bubble-sort-like procedure: the top-ranked document from the current window is compared against documents in the next window, and the process repeats until the entire list has been processed.

Algorithm 9 (Sliding Window Listwise Reranking).

  1. Input: Query q; candidate list =(d1,,dn); window size w; step size s; listwise reranker σLLM
  2. Output: Reranked list
  3. input ordering
  4. for pass=1,2,,T convergence
  5. for i=n,ns,n2s,,1 slide from bottom to top
  6. startmax(1,iw+1)
  7. endmin(n,start+w1)
  8. 𝒲([start],,[end]) extract window
  9. πσLLM(q,𝒲) rerank window
  10. [start:end]permute(𝒲,π) apply permutation
  11. return

The sliding window approach trades optimality for tractability. Each window reranking is a local operation, and relevant documents gradually “bubble up” through the list across multiple passes. In practice, two to three passes suffice for most applications, and the approach scales to lists of hundreds or thousands of documents.

Lemma 7 (Convergence of Sliding Window Reranking).

Let σ be the true relevance-based permutation, and let σT be the permutation produced after T passes of the sliding window algorithm with window size w and step size s=1. If the listwise reranker σLLM produces the correct ordering within each window with probability at least 1δ, then after T=n/w passes, the top-w documents are correctly ranked with probability at least (1δ)T.

Proof.

After one complete bottom-to-top pass, the most relevant document in the entire list has been compared against every other document through overlapping windows. If each window is correctly ranked (probability 1δ per window), the most relevant document “bubbles” to position 1. By induction, after T passes, the top-Tw documents have had the opportunity to be correctly positioned. The probability that all n/w window rankings in a single pass are correct is at least (1δ)n/w by a union bound, giving the stated guarantee after T passes by independence across passes.

Remark 37.

The sliding window approach is structurally analogous to bubble sort, where adjacent elements are compared and swapped. Just as bubble sort requires O(n) passes in the worst case, the sliding window reranker may require multiple passes to propagate a highly relevant document from the bottom of the list to the top. However, because the initial ordering is already a reasonable ranking (provided by the first-stage retriever), the number of required passes is typically much smaller than the worst case.

Setwise Reranking: The Efficiency Frontier

Pointwise reranking requires n LLM calls. Pairwise reranking requires O(nlogn) calls at minimum and O(n2) in the worst case. Listwise reranking requires only a single call for the entire list, but is limited by context length. Setwise reranking, introduced by Zhuang et al. [23], occupies a sweet spot between these extremes.

Definition 48 (Setwise Reranker).

A setwise reranker operates by repeatedly presenting the query q alongside a subset S{d1,,dn} of k candidate documents and asking the LLM to identify the most relevant document in S. The selected document is placed at the top of the output ranking and removed from the candidate pool. The process repeats with the remaining candidates until all documents have been ranked. Formally, at each step t: (Setwise Selection)dt=arg maxdStP𝜽(d|q,St), where St𝒞t is a subset of size k drawn from the remaining candidates 𝒞t, and P𝜽(d|q,St) is the probability that the LLM identifies document d as the most relevant in St.

The key insight is that the LLM processes only k documents per call, keeping the context length manageable, while the selection procedure produces a globally meaningful ranking. The subset St is typically chosen to include the top candidates from the remaining pool according to the first-stage retriever's scores.

Algorithm 10 (Setwise LLM Reranking).

  1. Input: Query q; candidate set 𝒞={d1,,dn} with initial scores; subset size k; number of documents to rank mn
  2. Output: Top-m reranked list
  3. () empty ranked list
  4. 𝒞pool𝒞 candidates
  5. for t=1,2,,m
  6. Sttop-k(𝒞pool) select k candidates by initial score
  7. Construct prompt: “Given query q and documents St={di1,,dik}, which is most relevant?”
  8. dtLLM-select(q,St) decode most probable document identifier
  9. Append dt to
  10. 𝒞pool𝒞pool{dt}
  11. return

Proposition 23 (Setwise Ranking Reduces LLM Calls).

To rank the top m documents from a candidate set of size n using setwise reranking with subset size k, the number of LLM calls is exactly m, each processing k documents. In contrast, pairwise reranking requires Ω(nlogn) LLM calls for a complete ranking, and Ω(mn) calls for the top-m ranking via selection. The setwise approach therefore reduces LLM calls from O(mn) to O(m) with a per-call cost proportional to kn.

Proof.

At each of the m iterations, the setwise algorithm makes exactly one LLM call that processes k documents. Thus the total number of LLM calls is m.

For pairwise reranking via repeated selection (analogous to selection sort), finding the top-ranked document requires n1 comparisons, the second-ranked requires n2, and so on. The total number of pairwise comparisons for the top m documents is: (Pairwise Calls)i=0m1(n1i)=mnmm(m1)2=O(mn). Each comparison requires one LLM call. Therefore, the setwise approach uses O(m) calls compared to O(mn) for pairwise selection, a reduction by a factor of n.

When k is fixed, each setwise LLM call processes k document passages, so the total token cost is O(mk), which for kn is dramatically cheaper than the O(mn) token cost of pairwise selection.

Remark 38.

The quality of setwise ranking depends on the subset size k. If k=2, setwise reranking degenerates to pairwise comparison with a single-elimination tournament structure. If k=n, it becomes listwise reranking. Empirically, k in the range 5 to 20 provides a good balance between efficiency and ranking quality.

Example 31 (Setwise Reranking for Legal Search).

Consider a legal researcher querying “precedent for employer liability in remote work injuries.” A BM25 retriever returns 100 candidate case documents. The setwise reranker with k=10 selects the 10 top-scoring candidates, presents them to the LLM alongside the query, and asks which case is most relevant. The LLM, understanding that “remote work injuries” requires cases about workplace injury law in non-traditional settings (not just keyword overlap with “remote” or “work”), selects a 2021 workers' compensation ruling involving a home office accident. This document is placed first in the output ranking, and the process repeats with the remaining 99 candidates. After 10 iterations, the top-10 ranking is complete, having required only 10 LLM calls rather than the 100 needed by pointwise reranking.

FIRST: Fast Listwise Ranking via Single Tokens

Listwise reranking with LLMs typically requires the model to generate an entire permutation as a sequence of tokens. FIRST (Fast lIstwise Ranking via Single Token decoding) [86] observes that if we only need to identify the top document, we can do so by examining the logits over a single token position.

The idea is as follows. Present the LLM with the query and k passages, each labelled with a single-character identifier (A, B, C, ). Then ask the model: “The most relevant passage is:” and examine the probability distribution over the next token. The passage whose identifier receives the highest probability is deemed most relevant: (First Score)d=djwherej=arg maxi{1,,k}P𝜽(tokeni|q,d1,,dk), where tokeni is the character identifier for passage i.

Key Idea.

One Token Is All You Need The probability distribution over a single decoded token implicitly encodes the model's ranking of all k passages. By examining this distribution rather than generating a full permutation sequence, we reduce decoding latency from O(k) autoregressive steps to a single forward pass. This is especially valuable when using large models where each decoding step is expensive.

To rank all n documents (not just the top one), FIRST combines single-token decoding with a selection procedure similar to the setwise approach: identify the best document in the current window, remove it, and repeat. Alternatively, the probability distribution over all k identifiers can be used directly as scores, though this requires careful calibration.

Remark 39.

A subtlety of single-token decoding is that the logit distribution over passage identifiers is not necessarily well calibrated. The LLM may assign disproportionate probability mass to identifier “A” simply because it appears first in the prompt (position bias), not because passage A is most relevant. Zhuang et al. [23] address this by averaging across multiple random permutations of the passage ordering in the prompt, a technique called permutation calibration. Specifically, for T random orderings π1,,πT of the k passages: (First Calibrated)s^(q,dj)=1Tt=1TP𝜽(token(πt1(j))|q,dπt(1),,dπt(k)), where token(πt1(j)) is the identifier assigned to document dj under permutation πt. This averaging eliminates position bias at the cost of T additional forward passes per window.

Example 32 (Position Bias in Listwise Reranking).

Experiments by Hou et al. [24] revealed that GPT-4, when asked to rank 20 passages, systematically favoured passages listed earlier in the prompt. Passage [1] was ranked in the top 3 approximately 40% of the time regardless of its actual relevance, compared to an expected rate of 15% under uniform random placement. Reversing the presentation order reversed the bias: passage [20] (now first in the prompt) received the same inflated ranking. This position bias is a fundamental challenge for listwise reranking and motivates both the permutation calibration technique described above and the development of fine-tuned rerankers that are explicitly trained to be order-invariant.

RLCF: Learning to Rerank from Contrastive Feedback

The reranking methods described so far rely on the general capabilities of pre-trained language models. RLCF (Reinforcement Learning from Contrastive Feedback) [87] takes the next step: it fine-tunes the LLM reranker using reinforcement learning, where the reward signal comes from contrastive comparisons between the model's ranking and human preferences.

Definition 49 (Contrastive Feedback Reward).

Let π𝜽 be a language model that produces rankings, and let σ and σ be two rankings of the same candidate set. The contrastive feedback reward is: (RLCF Reward)R(σ,σ)=i=1nj=i+1n𝟙[σ(i)σ(j)]gain(σ(i),σ(j)), where σ(i)σ(j) denotes that the document at position i is more relevant than the document at position j according to human annotations, and gain(,) measures the magnitude of the preference.

The training procedure alternates between generating rankings using the current policy π𝜽 and updating the policy to maximise the expected contrastive reward. The contrastive structure of the reward encourages the model to focus on the relative ordering of documents rather than their absolute relevance scores, which aligns well with the evaluation metrics used in information retrieval (NDCG, MAP, MRR).

Example 33 (RLCF Training Loop).

Consider fine-tuning a Flan-T5-XL model as an RLCF reranker. The process begins with a supervised warm-up phase: the model is trained on a small set of human-annotated rankings using a listwise cross-entropy loss. Then, reinforcement learning takes over. The model generates rankings for training queries, and the contrastive reward (Definition 49) is computed by comparing the generated ranking against human preference annotations. The policy gradient update encourages the model to produce rankings that agree with human judgments on pairwise comparisons. After several thousand RL steps, the model learns to produce rankings that are not only accurate on average but also well calibrated: documents that the model ranks highly are consistently preferred by human annotators.

Remark 40.

The distinction between RLCF and supervised fine-tuning (SFT) is important. SFT trains the model to reproduce a single “correct” ranking, which may not exist when annotators disagree. RLCF trains the model to maximise agreement with the distribution of human preferences, naturally handling annotator disagreement by optimising for the majority preference on each pairwise comparison. This makes RLCF particularly well suited for ambiguous queries where relevance is a matter of degree rather than a binary judgment.

Formal Analysis: Computational Complexity

We now consolidate the computational analysis of all four reranking paradigms. Let n denote the number of candidate documents, L the average document length in tokens, q the query length, and C(s) the cost of a single LLM forward pass on a sequence of length s.

Theorem 9 (Complexity of Reranking Paradigms).

The total computational cost of reranking n documents under each paradigm is:

  1. Pointwise: nC(q+L). Each document requires one independent forward pass.

  2. Pairwise (via sorting): O(nlogn)C(q+2L). Each comparison processes two documents.

  3. Listwise: C(q+nL) for a single-pass ranking, which is feasible only when q+nL fits within the context window.

  4. Setwise (top-m): mC(q+kL), where kn is the subset size.

For quadratic attention models where C(s)=O(s2), listwise reranking has cost O((q+nL)2), which is prohibitive for large n. Setwise reranking avoids this by keeping k small: mO((q+kL)2).

Proof.

The pointwise cost follows directly from the independence of scoring operations. For pairwise reranking, an optimal comparison sort requires Θ(nlogn) comparisons, each processing a sequence of length q+2L. The listwise cost is a single forward pass on the concatenation of the query and all n documents. The setwise cost follows from Proposition 23: m calls, each on a sequence of length q+kL. The quadratic attention costs follow from C(s)=O(s2).

The four reranking paradigms compared. Pointwise scoring evaluates each document independently, requiring n LLM calls. Pairwise comparison judges relative relevance between pairs, requiring O(nlogn) calls. Listwise processing ranks the entire list in a single call, but is limited by context length. Setwise ranking selects the best document from a small subset at each step, requiring m calls for the top-m ranking.
The reranking cascade. A cheap first-stage retriever (BM25 or bi-encoder) quickly identifies a manageable set of candidates from a large corpus. An expensive but accurate LLM reranker then refines this set, pushing the most relevant documents to the top. The cascade achieves the accuracy of the expensive model at a fraction of the cost of applying it to the full corpus.

Empirical Comparison

Table 9 summarises the performance and efficiency characteristics of the major reranking approaches on the TREC Deep Learning benchmarks.

MethodParadigmNDCG@10MRR@10LLM Calls
BM25 (no reranking)0.4800.6600
BERT cross-encoderPointwise0.7100.835100
monoT5 (3B)Pointwise0.7250.850100
duoT5 (3B)Pairwise0.7400.860660
LLM listwise (GPT-4)Listwise0.7500.8705–10
Setwise (k=10)Setwise0.7380.85510
FIRSTListwise0.7350.8525–10
RLCF-tunedListwise0.7550.8755–10
Comparison of reranking methods on TREC-DL benchmarks. NDCG@10 and MRR@10 are reported on the TREC-DL 2020 passage ranking task. LLM calls indicates the number of model forward passes required to rerank 100 candidates.

Insight.

The Accuracy-Efficiency Pareto Frontier No single reranking paradigm dominates all others. Pointwise methods are simple and parallelisable but leave quality on the table. Pairwise methods capture fine-grained preferences but are expensive. Listwise methods are the most accurate but limited by context length. Setwise methods offer the best balance for practical deployment. The optimal choice depends on the specific latency budget, the available model size, and the acceptable quality threshold. As a rule of thumb: if you can afford one LLM call per query, use listwise; if you need sub-second latency, use pointwise with a small cross-encoder; if you are somewhere in between, setwise with k10 is a strong default.

Caution.

Do Not Trust a Single Reranker Blindly LLM rerankers can be confidently wrong. A reranker might assign high relevance to a document that matches the query's surface keywords but contradicts its intent, or demote a highly relevant document that uses different terminology. In high-stakes applications (medical, legal, financial), always combine the reranker's output with other signals (term matching, citation analysis, domain-specific knowledge graphs) and present multiple candidates to the user rather than relying on a single top-ranked result. The reranker is a powerful tool, but it is not an oracle.

Exercise 44.

Implement a monoT5-style pointwise reranker using a pre-trained T5-small model. Evaluate it on the MS MARCO passage ranking development set. Then implement the setwise variant with k=5 and k=10. Compare NDCG@10 and wall-clock time per query.

Exercise 45.

Implement the sliding window listwise reranking algorithm from Algorithm 9. Experiment with different window sizes w{5,10,20} and step sizes s{1,3,5}. How many passes are needed for the ranking to converge? Plot NDCG@10 as a function of the number of LLM calls.

Synthetic Data Generation for Retrieval

Training a neural retriever requires labelled data: pairs of queries and relevant documents, annotated by human judges. But human annotation is expensive, slow, and often inconsistent. The TREC Deep Learning track, one of the most widely used benchmarks in information retrieval, contains only a few thousand judged queries. The MS MARCO dataset, substantially larger, still represents a tiny fraction of the possible query-document pairs. And when you want to deploy a retriever in a new domain, medical literature, legal documents, internal corporate knowledge bases, the training data simply does not exist.

This is the bootstrapping problem: building a retriever for a new domain requires training data, but obtaining that training data requires either a retriever (to surface documents for annotation) or an enormous human labelling effort. The solution, it turns out, is to let the language models generate the training data themselves.

InPars: Query Generation for Domain Adaptation

Bonifacio et al. [88] proposed InPars (Inquisitive Parrots), a method that uses large language models to generate synthetic queries for documents in a target corpus. The procedure is elegant in its simplicity.

Given a document d from the target corpus, prompt the LLM with a few examples of (document, query) pairs drawn from a seed dataset, followed by the target document. The LLM then generates a plausible query for which d would be a relevant answer. The synthetic query-document pair (qsyn,d) becomes a positive training example for the retriever.

Definition 50 (Few-Shot Query Generation).

Given a target document d𝒟target and a set of seed examples {(d1s,q1s),,(dms,qms)}, the few-shot query generation procedure constructs the prompt: (Inpars Prompt)prompt=[(d1s,q1s);;(dms,qms);d], and samples qsynP𝜽(|prompt) from the language model. The resulting pair (qsyn,d) is added to the synthetic training set.

The InPars training data generation loop. Documents are sampled from the target corpus, and a few-shot prompted LLM generates synthetic queries for each document. The resulting query-document pairs are used to fine-tune a retriever, which can then be deployed on the target domain. The process requires no human annotation of the target corpus.

The synthetic training set is typically filtered to remove low-quality queries (e.g., those that are too short, too generic, or obviously unrelated to the document). A common filtering strategy uses the language model's own confidence: queries with low generation probability are discarded. The filtered set is then used to fine-tune a bi-encoder or cross-encoder retriever.

Example 34 (Domain Adaptation with InPars).

Consider adapting a general-purpose retriever to a biomedical corpus. The seed examples might include pairs from MS MARCO, such as:

  • Document: “Aspirin inhibits the enzyme cyclooxygenase”

  • Query: “How does aspirin work?”

Given a new biomedical document about the CRISPR-Cas9 mechanism, the LLM might generate the synthetic query “What is the mechanism of CRISPR-Cas9 gene editing?” This pair becomes training data for the domain-specific retriever, enabling it to handle biomedical queries without any biomedical annotations.

Remark 41.

The InPars procedure scales naturally with corpus size. For a corpus of N documents, the cost is approximately N LLM inference calls (one per document), each producing a short query. This is a one-time cost, amortised over the lifetime of the retriever. For a corpus of one million documents using a moderately sized LLM, the total cost is on the order of tens of dollars in API fees, a trivial expense compared to the cost of human annotation, which at $0.50 per query-document judgment would cost $500,000 for the same coverage.

Proposition 24 (Quality of InPars-Generated Training Data).

Let 𝒟syn={(qisyn,di)}i=1N be a synthetic training set generated by InPars, and let R𝜽syn be a retriever trained on 𝒟syn. If the LLM's query generation distribution P𝝓(q|d) satisfies (Inpars KL)DKL(Preal(q|d)P𝝓(q|d))ϵ for all d𝒟, where Preal(q|d) is the true distribution of user queries for which d is relevant, then the retrieval performance gap satisfies: (Inpars Bound)|𝔼qPreal[NDCG(R𝜽syn,q)]𝔼qPreal[NDCG(R𝜽,q)]|O(ϵ), where R𝜽 is the retriever trained on real human-annotated data.

Proof.

By Pinsker's inequality, the total variation distance between Preal(q|d) and P𝝓(q|d) is bounded by ϵ/2. The retriever's loss function (e.g., contrastive loss) evaluated under the synthetic distribution differs from its evaluation under the real distribution by at most the total variation distance times the maximum loss value. Since NDCG is bounded in [0,1], the gap in expected NDCG is bounded by O(ϵ). The bound follows by noting that the retriever optimised under the synthetic distribution is at most O(ϵ)-suboptimal relative to the retriever optimised under the real distribution.

HyDE: Hypothetical Document Embeddings

If InPars generates synthetic queries for documents, HyDE (Hypothetical Document Embeddings) [89] does something conceptually reversed and strikingly beautiful: it generates synthetic documents for queries.

The core observation is this: queries and documents live in different linguistic spaces. A query is typically short, fragmentary, and ambiguous (“best treatment for lower back pain”). A relevant document is typically long, detailed, and self-contained (“Lumbar disc herniation is treated through a combination of physical therapy, anti-inflammatory medications, and in severe cases, surgical intervention”). Embedding a query and embedding a relevant document into the same space is precisely the challenge that makes dense retrieval hard.

HyDE bypasses this challenge entirely. Instead of embedding the query directly, it first uses an LLM to generate a hypothetical document: a passage that would plausibly answer the query. This hypothetical document, though potentially inaccurate in its specifics, captures the linguistic style, vocabulary, and topical focus of a relevant document. It is then embedded using a standard dense encoder, and the resulting embedding is used to retrieve real documents via nearest-neighbour search.

Definition 51 (Hypothetical Document Embedding).

Let G𝝓 be a generative language model and f𝜽 be a dense document encoder. The hypothetical document embedding for a query q is: (HYDE)𝒒hyde=f𝜽(G𝝓(q)), where G𝝓(q) is a hypothetical document generated by the language model in response to the query q. Retrieval is then performed by finding the nearest neighbours of 𝒒hyde in the document embedding space: (HYDE Retrieval)d=arg maxd𝒟f𝜽(d),𝒒hyde.

The HyDE pipeline. A query is first passed to an LLM, which generates a hypothetical document that would plausibly answer the query. This hypothetical document is encoded by a standard dense encoder, and the resulting embedding is used to search the document index via nearest-neighbour similarity. The hypothetical document bridges the linguistic gap between queries and documents.

The beauty of HyDE is that it achieves zero-shot dense retrieval: it requires no training data whatsoever. The language model provides the domain knowledge (it knows what a relevant document would look like), and the dense encoder provides the embedding space (it maps the hypothetical document to the right neighbourhood in vector space). Neither component needs task-specific fine-tuning.

Algorithm 11 (HyDE Retrieval).

  1. Input: Query q; LLM generator G𝝓; dense encoder f𝜽; document index with pre-computed embeddings {f𝜽(d):d𝒟}; number of hypothetical documents H; number of results k
  2. Output: Top-k retrieved documents
  3. for h=1,2,,H
  4. d^hG𝝓(q) generate hypothetical document
  5. 𝒛hf𝜽(d^h) encode hypothetical document
  6. 𝒒hyde1Hh=1H𝒛h average embeddings
  7. top-k({f𝜽(d),𝒒hyde:d𝒟})
  8. return

Key Idea.

Bridging the Query-Document Gap The fundamental challenge of dense retrieval is that queries and documents are linguistically different. A query asks a question; a document states facts. HyDE bridges this gap by transforming the query into the language of documents before embedding. The hypothetical document need not be factually accurate; it merely needs to be in the right region of the document embedding space. Even a hallucinated document about the right topic, using the right vocabulary, will embed close to real relevant documents.

Remark 42.

Generating multiple hypothetical documents (H>1) and averaging their embeddings improves robustness. Different generations may emphasise different aspects of the query, and averaging smooths out individual hallucinations while preserving the common topical signal. This is reminiscent of ensemble methods in supervised learning, where averaging predictions from multiple models reduces variance.

Example 35 (HyDE for Technical Queries).

Consider the query “Explain the attention mechanism in Transformers.” HyDE prompts the LLM to generate a hypothetical answer, which might read: “The attention mechanism in Transformers computes a weighted sum of value vectors, where the weights are determined by the compatibility between query and key vectors using a scaled dot-product” This hypothetical passage, though generic, occupies the same embedding neighbourhood as actual technical documents about Transformer attention. Dense retrieval using 𝒒hyde surfaces papers and tutorials about attention mechanisms, even though the original query is just a short imperative sentence.

Proposition 25 (HyDE Approximation Quality).

Let d be the true relevant document for query q, and let d^=G𝝓(q) be the hypothetical document generated by the LLM. If the dense encoder f𝜽 is β-Lipschitz (i.e., f𝜽(a)f𝜽(b)βab for a suitable text distance metric ), then: (HYDE Bound)𝒒hydef𝜽(d)βd^d. In words, the distance between the HyDE embedding and the true document's embedding is bounded by the “textual distance” between the hypothetical and true documents, scaled by the encoder's Lipschitz constant. When the LLM generates a hypothetical document that is topically similar to d (small d^d), the HyDE embedding lands close to the true document in the vector space, enabling successful retrieval.

Proof.

By the Lipschitz property of f𝜽: 𝒒hydef𝜽(d)=f𝜽(d^)f𝜽(d)βd^d, which is the claimed bound. The bound is tight when the encoder preserves distances exactly (an isometry), and loose when the encoder collapses textual variations (as desired for robust retrieval).

Remark 43.

HyDE can fail in two characteristic ways. First, when the LLM generates a hypothetical document about the wrong topic entirely (a major hallucination), the HyDE embedding lands in a distant region of the vector space, and the retrieved documents are irrelevant. Second, when the query is highly specific and the LLM generates a generic answer, the HyDE embedding may be close to many documents but not specifically close to the one truly relevant document. The multi-sample averaging technique (Remark 42) mitigates the first failure mode but not the second. For highly specific queries, a traditional dense retriever trained on in-domain data typically outperforms HyDE.

Insight.

When to Use HyDE vs. Fine-Tuned Retrieval HyDE excels in zero-shot and low-resource settings where no task-specific training data is available. Its strength is precisely that it requires no training: plug in any LLM and any pre-trained encoder, and you have a working retriever. However, once labelled data becomes available (even synthetic data from InPars), a fine-tuned bi-encoder or cross-encoder typically surpasses HyDE, because fine-tuning directly optimises the query-document matching function. The practical recommendation is: use HyDE as a strong zero-shot baseline and a rapid prototyping tool, then transition to a fine-tuned retriever as training data accumulates. In the intermediate regime, where some data is available but not enough for reliable fine-tuning, HyDE can be combined with supervised signals by using the HyDE embedding as an additional feature in a learned scoring function.

Example 36 (HyDE Across Languages).

HyDE is particularly effective for cross-lingual retrieval, where the query is in one language and the documents are in another. A user issues a query in English: “What are the environmental effects of deforestation in the Amazon?” An LLM generates a hypothetical document in Portuguese (the language of many Amazon-related documents): “O desmatamento na Amazônia tem efeitos ambientais graves, incluindo perda de biodiversidade, alterações climáticas regionais” The multilingual encoder embeds this Portuguese hypothetical document close to real Portuguese documents about Amazonian deforestation. The approach requires no parallel corpora or cross-lingual training data; the LLM's multilingual capabilities handle the language transfer, and the multilingual encoder handles the embedding alignment.

Promptagator: Few-Shot Retriever Training

Promptagator extends the InPars idea by incorporating a consistency-based filtering step. After generating synthetic queries, a retriever is trained on the synthetic data and used to re-retrieve documents for each synthetic query. If the original document d is not retrieved in the top-k results for its synthetic query qsyn, the pair is considered unreliable and discarded. This round-trip consistency filter significantly improves the quality of the training data.

Definition 52 (Round-Trip Consistency Filter).

Given a synthetic training pair (qsyn,d) and a retriever R𝜽 trained on the current synthetic dataset, the round-trip consistency filter retains the pair if and only if: (Round TRIP)dtop-k(R𝜽(qsyn)), where top-k(R𝜽(qsyn)) denotes the k documents with the highest retrieval scores for query qsyn.

The filtering is performed iteratively: generate synthetic data, train a retriever, filter the data using the trained retriever, retrain on the filtered data. Each iteration produces a cleaner training set and a stronger retriever.

Example 37 (Promptagator for Scientific Literature).

Suppose we wish to build a retriever for a corpus of 500,000 computer science papers. Promptagator proceeds as follows. First, generate synthetic queries for each paper using an LLM with 3 seed examples drawn from a small set of manually annotated queries. Second, train an initial bi-encoder on the resulting 500,000 synthetic pairs. Third, for each synthetic query qsyn, use the trained bi-encoder to retrieve the top-100 papers. If the original paper d does not appear in this top-100 list, discard the pair (qsyn,d) as unreliable. Typically, 30–50% of pairs are filtered out in this step. Fourth, retrain the bi-encoder on the filtered dataset. The resulting retriever substantially outperforms the initial model, because the filtered pairs are those for which the query-document association is strong enough to survive a round-trip through the embedding space.

Synthetic Hard Negatives

Training effective retrievers requires not only positive examples (relevant documents) but also informative negative examples (irrelevant documents that are hard to distinguish from relevant ones). Random negatives are easy to obtain but provide little training signal; the model quickly learns to reject obviously irrelevant documents and stops improving. Hard negatives, documents that are topically related but not truly relevant, force the model to make fine-grained distinctions.

Language models can generate synthetic hard negatives by modifying relevant documents in subtle ways: changing key facts, altering the time period, or shifting the focus slightly. For a query about “treatment options for Type 2 diabetes,” a synthetic hard negative might discuss treatment options for Type 1 diabetes, or discuss Type 2 diabetes diagnostics rather than treatment.

Remark 44.

The difficulty of synthetic hard negatives must be carefully calibrated. Negatives that are too similar to positives may actually be relevant, introducing label noise. Negatives that are too dissimilar provide no training signal. A useful heuristic is to generate negatives that differ from the positive document in exactly one factual dimension while remaining topically coherent.

Risks and Limitations

Synthetic data generation for retrieval is powerful but fraught with risks. Three deserve particular attention.

Hallucination propagation.

When an LLM generates a synthetic query or document, it may hallucinate details that do not appear in the source document. If the retriever is trained to match these hallucinated details, it learns to retrieve documents based on fabricated content. This is particularly dangerous in high-stakes domains (medical, legal) where factual accuracy is paramount.

Distribution shift.

Synthetic data reflects the distribution of the language model, not the distribution of real user queries. LLM-generated queries tend to be more grammatical, more complete, and more informative than real user queries, which are often telegraphic, misspelled, and ambiguous. A retriever trained exclusively on synthetic data may underperform on real queries that fall outside the synthetic distribution.

Example 38 (Distribution Shift in E-Commerce Search).

An e-commerce company uses InPars to generate synthetic queries for its product catalogue. The LLM, trained on well-formed text, generates queries like “ergonomic office chair with lumbar support and adjustable armrests.” But real users type queries like “comfy desk chair” or “chair back hurt.” The retriever trained on synthetic data learns to match formal product descriptions to formal queries, but struggles with the colloquial, abbreviated, and sometimes ungrammatical queries that real customers actually submit. Mixing a small amount of real query logs into the training data mitigates this gap substantially.

Evaluation contamination.

This is perhaps the most insidious risk.

Caution.

The Evaluation Trap When synthetic data is generated from the same LLM that is used for evaluation, the resulting benchmarks may overestimate the retriever's true performance. The synthetic queries reflect the LLM's biases and knowledge, and a retriever trained on this data inherits those biases. If the evaluation queries are also LLM-generated, the retriever appears to perform well because it has learned to match the LLM's internal patterns, not because it genuinely understands relevance. Always evaluate on human-annotated benchmarks, ideally from a different distribution than the training data, and be sceptical of results that seem too good on synthetic evaluations.

Exercise 46.

Implement the InPars query generation pipeline for a domain of your choice. Use a pre-trained LLM to generate 10,000 synthetic queries for documents in your target corpus. Train a bi-encoder retriever on the synthetic data and evaluate on a held-out human-annotated test set. Compare against a retriever trained on MS MARCO data without domain adaptation.

Exercise 47.

Implement HyDE retrieval with H=1,3,5 hypothetical documents. Evaluate on three BEIR benchmark datasets. Does averaging more hypothetical documents consistently improve performance? How does the latency scale with H?

Exercise 48.

Design a controlled experiment to measure the effect of synthetic hard negatives on retriever quality. Train three versions of a bi-encoder: one with random negatives, one with BM25 hard negatives, and one with LLM-generated hard negatives. Compare Recall@100 and NDCG@10 on the TREC-DL 2020 test set.

Generative Retrieval

What if the search index is the model? Every retrieval system we have encountered so far maintains an external data structure, an inverted index, a vector store, a graph, to hold the corpus. The model (be it a sparse scorer, a dense encoder, or a cross-encoder) queries this external structure to find relevant documents. Generative retrieval eliminates the external index entirely. The model memorises the corpus in its parameters and, given a query, directly generates the identifier of the relevant document.

This is a radical departure from the retrieve-then-read paradigm. There is no index to build, no approximate nearest-neighbour search to perform, no document embeddings to store. The entire retrieval pipeline collapses into a single autoregressive generation step: query in, document identifier out.

The idea is audacious, elegant, and deeply controversial. Let us examine it carefully.

DSI: The Differentiable Search Index

Tay et al. [90] introduced the Differentiable Search Index (DSI), the seminal work in generative retrieval. The architecture is a standard sequence-to-sequence Transformer (T5) that is trained to perform two tasks:

  1. Memorisation: given a document d, generate its identifier DocID(d). This phase forces the model to encode the content of every document in the corpus into its parameters.

  2. Retrieval: given a query q, generate the DocID of the most relevant document. This phase teaches the model to map queries to the correct identifiers.

Definition 53 (Generative Retrieval Model).

A generative retrieval model is a parametric function P𝜽:𝒬Δ() that maps a query q to a probability distribution over a set of document identifiers ={i1,i2,,iN}. Retrieval is performed by finding the identifier with the highest probability: (Generative Retrieval)i=arg maxiP𝜽(i|q). When the identifier is a multi-token sequence i=(t1,t2,,tL), the probability factorises autoregressively: (Generative Autoregressive)P𝜽(i|q)==1LP𝜽(t|t1,,t1,q).

DocID Design

The design of the document identifier is the most critical architectural decision in generative retrieval. Tay et al. explored three approaches:

Numeric IDs.

Each document receives an arbitrary integer, represented as a sequence of digit tokens. Document 42,857 becomes the token sequence “4”, “2”, “8”, “5”, “7”. This is the simplest approach, but it forces the model to memorise an arbitrary mapping between document content and meaningless numbers, a task that is fundamentally at odds with the language model's strengths.

String IDs.

Each document receives a human-readable identifier, such as a title or URL. The document about tidal forces might receive the ID “Tidal_Force_Wikipedia”. This is more natural for the language model, since the identifier is semantically related to the content. However, titles may be ambiguous (multiple documents with similar titles) or too long to generate efficiently.

Semantic hierarchical IDs.

Documents are organised into a hierarchy via clustering, and each document's ID is its path through the hierarchy. For example, a corpus might be divided into 100 top-level clusters, each subdivided into 100 sub-clusters, and each sub-cluster containing individual documents. Document 42,857 might receive the hierarchical ID “37-15-42”, meaning cluster 37, sub-cluster 15, position 42. If the clustering is semantic (based on document embeddings), then similar documents have similar prefixes, and the model can learn to navigate the hierarchy by progressively narrowing the topic.

Key Idea.

Semantic Structure in Identifiers The key insight of hierarchical IDs is that they transform retrieval from a flat lookup problem into a structured navigation problem. Instead of predicting one of N unrelated identifiers, the model predicts a sequence of L tokens, each from a vocabulary of size NL. At each step, the model narrows the search space by a factor of NL, using the semantic content of the query to guide the descent through the hierarchy. This is analogous to traversing a B-tree in database systems, but learned end-to-end.

Training

DSI training proceeds in two phases. In the memorisation phase, the model is trained on input-output pairs of the form (d,DocID(d)), where the input is the full document text (or a representative passage) and the output is the document identifier. The training objective is the standard sequence-to-sequence cross-entropy loss: (DSI Memorisation)mem=d𝒟logP𝜽(DocID(d)|d).

In the retrieval phase, the model is fine-tuned on query-document identifier pairs (q,DocID(d+)), where d+ is a document known to be relevant to q: (DSI Retrieval)ret=(q,d+)𝒯logP𝜽(DocID(d+)|q).

The total loss combines both phases: (DSI Total LOSS)DSI=λmemmem+λretret, where λmem and λret are balancing coefficients.

The DSI architecture. A single Transformer model serves as both the index and the retriever. In the memorisation phase (left), the model learns to map documents to their identifiers, encoding the corpus content in its parameters. In the retrieval phase (right), the model learns to map queries to relevant document identifiers. There is no external index; the entire corpus is stored in the model weights 𝜽.

Example 39 (DSI on Natural Questions).

The original DSI experiments used the Natural Questions dataset, containing approximately 320,000 Wikipedia passages. With a T5-XXL backbone (11 billion parameters) and semantic hierarchical IDs, DSI achieved competitive recall with BM25 and dual-encoder baselines. The model effectively memorised the content of 320,000 passages and learned to route queries to the correct identifiers through the semantic hierarchy.

Remark 45.

At inference time, DSI uses beam search to generate document identifiers. With beam width B, the model produces the top-B most probable identifier sequences, which correspond to the B documents that the model considers most relevant. This naturally supports top-k retrieval: setting B=k yields k candidate documents. However, beam search can produce invalid identifiers (sequences that do not correspond to any document). Constrained beam search, which restricts each decoding step to tokens that are valid continuations of existing document IDs, eliminates this problem at a modest computational cost.

Lemma 8 (Constrained Decoding Preserves Ranking Quality).

Let 𝒯 be a prefix trie constructed from all valid document identifiers. Constrained decoding restricts the generation at each step to the set 𝒱={t:(t1,,t1,t)𝒯} of valid continuations. The resulting ranking over valid identifiers is identical to the ranking obtained by unconstrained generation followed by filtering, i.e., for any two valid identifiers i,i: (Constrained Ranking)P𝜽constrained(i|q)P𝜽constrained(i|q)P𝜽(i|q)P𝜽(i|q).

Proof.

Constrained decoding normalises the probability mass at each step over the valid continuation set: P𝜽constrained(t|t<,q)=P𝜽(t|t<,q)/t𝒱P𝜽(t|t<,q). Since the normalisation constant depends only on the prefix t< and not on the specific continuation t, the relative ordering of continuations at each step is preserved. By induction over the sequence length L, the relative ordering of complete identifiers is preserved.

Semantic IDs via Hierarchical Clustering

The design of meaningful document identifiers has emerged as a research direction in its own right. The most promising approach constructs identifiers through hierarchical clustering of document embeddings, producing IDs that reflect semantic structure.

RQ-VAE for Identifier Learning

Residual quantisation with a variational autoencoder (RQ-VAE) provides an elegant framework for learning semantic identifiers. The procedure works as follows:

  1. Encode each document d into a dense embedding 𝒛=f𝜽(d)D.

  2. Apply residual quantisation with L levels. At level , find the nearest codeword c in codebook 𝒞={c,1,,c,K}: (Rqvae Quantise)c=arg minc𝒞𝒓1c2, where 𝒓0=𝒛 and 𝒓=𝒓1c is the residual after quantisation.

  3. The semantic ID of document d is the sequence of codebook indices: SemanticID(d)=(k1,k2,,kL), where c=c,k.

Definition 54 (Semantic Identifier via RQ-VAE).

A semantic identifier is a sequence of discrete codes (k1,k2,,kL)[K]L obtained by applying residual quantisation to a document embedding. The identifier satisfies the property that semantically similar documents share common prefixes: (Semantic Prefix)sim(d,d) high such that kj=kj for j=1,,, where (k1,,kL) and (k1,,kL) are the semantic IDs of d and d respectively.

The connection to product quantisation, a well-established technique in approximate nearest-neighbour search, is direct. Product quantisation decomposes the embedding space into subspaces and quantises each subspace independently; residual quantisation applies quantisation sequentially to the residual error. Both produce compact codes that approximate the original embeddings, but residual quantisation produces naturally hierarchical codes: the first codeword captures coarse structure, and subsequent codewords refine it.

Proposition 26 (Reconstruction Error of RQ-VAE Semantic IDs).

After L levels of residual quantisation with K codewords per level, the reconstruction error for a document embedding 𝒛 is: (Rqvae Error)𝒛𝒛^2=𝒓L2=𝒛=1Lc2. If the codewords are optimally placed (as in k-means) and the embedding distribution is sub-Gaussian with variance proxy σ2, then the expected reconstruction error satisfies: (Rqvae Bound)𝔼[𝒓L2]σ2DK2/DρL, where D is the embedding dimension, K is the codebook size, and ρ<1 is a contraction factor that depends on the distribution's tail behaviour. Each additional level reduces the error geometrically.

Proof sketch.

At each level , the residual 𝒓 is the quantisation error of 𝒓1 under the codebook 𝒞. By the rate-distortion theory for k-means quantisation of a D-dimensional sub-Gaussian random vector, the expected distortion at each level is bounded by σ2DK2/D, where σ2 is the variance of 𝒓1. Since σ2ρσ12 for optimal quantisation with contraction ρ=1K2/D (approximately), the bound follows by induction.

Semantic ID hierarchy. Documents are organised into a tree structure via hierarchical clustering. Each document's identifier is its path from the root to the leaf. Semantically similar documents (e.g., d1 and d2) share common prefixes (both under node 1-1), while dissimilar documents (e.g., d1 and d7) diverge early in the tree. The generative retrieval model navigates this tree autoregressively, predicting one level at a time.

TIGER: Generative Retrieval for Recommendation

Rajput et al. [91] extended generative retrieval to the recommendation setting with TIGER (Transformer Index for GEnerative Recommenders). In recommendation, the “corpus” is a catalogue of items (products, movies, songs), and the “query” is a user's interaction history.

TIGER assigns each item a semantic ID learned via RQ-VAE on item content embeddings (e.g., text descriptions, images, or audio features). The recommendation model, a Transformer, takes the user's interaction history (a sequence of semantic IDs of previously consumed items) and autoregressively generates the semantic ID of the next item to recommend: (Tiger)P(inext|i1,i2,,it;𝜽)==1LP𝜽(knext|k1next,,k1next,i1,,it), where (k1next,,kLnext) is the semantic ID of the next item.

Remark 46.

TIGER offers several advantages over traditional collaborative filtering and content-based recommendation. First, the semantic IDs capture item content, enabling zero-shot recommendation for new items that share semantic features with existing items (the cold-start problem). Second, the autoregressive generation naturally supports diverse recommendations: beam search over the semantic ID tree produces multiple candidate items from different branches of the hierarchy. Third, the entire system is end-to-end differentiable, allowing joint optimisation of the ID assignment and the recommendation model.

Example 40 (TIGER for Music Recommendation).

Consider a music streaming service with 10 million tracks. TIGER encodes each track using audio features (mel-spectrograms), textual metadata (title, artist, genre tags), and collaborative signals (co-listen patterns). RQ-VAE with L=4 levels and K=256 codewords per level produces semantic IDs capable of addressing 25644.3 billion unique items. A user who has recently listened to jazz fusion tracks receives a sequence of semantic IDs like (42, 17, 8, 195), (42, 18, 3, 77), (42, 17, 12, 201). The shared prefix (42, 17, ...) indicates that these tracks live in a similar region of the acoustic embedding space. The Transformer generates the next semantic ID autoregressively, predicting first the coarse cluster (42, indicating jazz), then the sub-cluster (17, indicating fusion), then finer refinements. Beam search at each level produces diverse recommendations spanning different corners of the jazz fusion space.

Remark 47.

The semantic ID framework naturally addresses the cold-start problem. A new item added to the catalogue receives a semantic ID based on its content features alone (no interaction history required). Because the ID reflects the item's semantic characteristics, the recommendation model can immediately incorporate it: a new jazz fusion track receives an ID with prefix (42, 17, ...) and is automatically considered alongside existing tracks in that region. Traditional collaborative filtering models, which rely entirely on interaction patterns, cannot recommend items with zero interactions.

IDGenRec: LLM-RecSys Alignment

Tan et al. [92] proposed IDGenRec, which addresses a key limitation of previous generative recommendation models: the identifiers were designed independently of the language model. IDGenRec aligns the identifier design with the LLM's tokeniser and pre-trained knowledge.

Instead of numeric or RQ-VAE-based codes, IDGenRec generates textual IDs that consist of semantically meaningful word tokens from the LLM's vocabulary. Each item receives a textual identifier that is both unique and descriptive, e.g., “vintage leather messenger bag” rather than “42-15-7”. The LLM can leverage its pre-trained understanding of these words to make recommendations without needing to learn arbitrary code mappings from scratch.

Definition 55 (Textual Item Identifier).

A textual item identifier is a sequence of tokens TID(i)=(w1,w2,,wM) drawn from the LLM's vocabulary 𝒱 such that:

  1. Uniqueness: TID(i)TID(j) for all ij.

  2. Semantics: the tokens are semantically related to the item's content, so that PLLM(TID(i)|description(i)) is high.

  3. Conciseness: the identifier is short enough for efficient generation, typically M10 tokens.

Remark 48.

The alignment between identifier tokens and the LLM's pre-trained knowledge is crucial. When a model encounters the textual ID “vintage leather messenger bag,” its pre-trained representations immediately activate concepts related to leather goods, bags, and vintage aesthetics. This semantic priming reduces the amount of fine-tuning needed to learn the recommendation task, because the model already “understands” what the identifier refers to. In contrast, a numeric ID like “42-15-7” provides no such semantic priming, and the model must learn the entire mapping from scratch.

Example 41 (IDGenRec for Movie Recommendation).

Consider a movie recommendation system. Traditional approaches assign each movie an arbitrary integer ID (e.g., MovieLens ID 1 for Toy Story). IDGenRec instead assigns the textual identifier “animated family adventure Pixar 1995.” Given a user's history encoded as a sequence of such textual IDs, the LLM generates the next textual ID autoregressively. If the user's history includes “animated family adventure Pixar 1995” and “animated princess musical Disney 1991,” the model might generate “animated musical comedy Disney 1992,” which maps to Aladdin. The generation leverages the LLM's knowledge of movie attributes, years, and studios, enabling recommendations that go beyond simple collaborative filtering patterns.

CorpusLM: Unified Retrieval and Knowledge

Li et al. [93] proposed CorpusLM, a unified framework that trains a single language model to perform both generative retrieval and knowledge-intensive language tasks (question answering, fact verification, dialogue). The key observation is that retrieval and knowledge tasks share a common requirement: the model must internalise the corpus and produce relevant information on demand.

CorpusLM trains on a mixture of tasks:

  • Retrieval: query DocID, as in DSI.

  • Generation: query answer, using knowledge stored in the parameters.

  • Memorisation: document DocID, to maintain corpus coverage.

The multi-task training enables knowledge transfer: the retrieval task forces the model to organise its knowledge by document, while the generation task forces it to extract and synthesise information across documents.

The training objective combines all three tasks: (Corpuslm LOSS)CorpusLM=λrret+λggen+λmmem, where ret is the retrieval loss (cross-entropy over DocIDs given queries), gen is the generation loss (cross-entropy over answer tokens given queries), and mem is the memorisation loss (cross-entropy over DocIDs given documents). The balancing coefficients λr, λg, λm control the relative importance of each task.

Key Idea.

Retrieval as a Byproduct of Language Modelling CorpusLM embodies a provocative hypothesis: retrieval and generation are not separate capabilities but two aspects of the same underlying competence. A model that truly “understands” a document should be able both to retrieve it (given a query that it answers) and to generate its content (given a prompt that describes it). By training a single model on both tasks, CorpusLM encourages the development of unified representations that support both capabilities. Whether this unified approach can scale to web-scale corpora remains an open question, but the conceptual elegance is undeniable.

Example 42 (CorpusLM for Question Answering).

Given the question “Who invented the telephone?”, CorpusLM can respond in two modes. In retrieval mode, it generates the DocID of the Wikipedia article about Alexander Graham Bell. In generation mode, it directly produces the answer “Alexander Graham Bell is credited with inventing the telephone in 1876.” Both responses draw on the same parametric knowledge, but the retrieval mode additionally provides provenance (the specific document).

Limitations and Open Questions

Generative retrieval is intellectually compelling but faces fundamental challenges that temper its practical applicability.

Scalability.

A Transformer must memorise the entire corpus in its parameters. As the corpus grows, the model must grow proportionally to maintain retrieval quality. The original DSI experiments used 320,000 passages; web-scale corpora contain billions. Can a model with a fixed parameter count memorise billions of documents? Information theory suggests not.

Corpus updates.

Adding a new document to a traditional index takes milliseconds. Adding a new document to a generative retrieval model requires retraining or at minimum fine-tuning the entire model, a process that takes hours or days. For corpora that change frequently (news, social media, e-commerce), this is a severe limitation.

Hallucinated identifiers.

An autoregressive model can generate identifier sequences that do not correspond to any document in the corpus. With numeric IDs, the model might generate “42857” when no document has that ID. With semantic hierarchical IDs, the model might navigate to a leaf node that is empty. Constrained decoding can mitigate this problem by restricting generation to valid prefixes at each step (see Lemma 8), but it adds computational overhead and complexity.

Lack of explainability.

When a traditional retriever returns a document, the relevance signal is transparent: a BM25 score highlights matching terms, a dense retriever provides an embedding similarity, and a cross-encoder produces an interpretable relevance probability. When a generative retrieval model produces a DocID, the reasons for selection are opaque. The model navigated its parametric memory through a series of autoregressive token predictions, and there is no straightforward way to explain why this particular document was selected over others.

Research 5.

Open Problems in Generative Retrieval Several fundamental questions remain open in generative retrieval. First, can incremental learning techniques (continual learning, parameter-efficient fine-tuning) enable efficient corpus updates without catastrophic forgetting of previously memorised documents? Second, can generative retrieval models provide calibrated confidence scores, so that the system knows when it is uncertain about a retrieval result? Third, is there a principled way to combine generative retrieval with external indices, perhaps using the generative model for “semantic routing” to a coarse document cluster and an external index for fine-grained retrieval within the cluster? These questions sit at the intersection of information retrieval, continual learning, and neural network theory, and their resolution will determine whether generative retrieval remains an intellectual curiosity or becomes a practical alternative to index-based systems.

Traditional retrieval (left) uses a model to query an external index that stores the corpus. Generative retrieval (right) eliminates the external index entirely: the corpus is memorised in the model's parameters, and the model directly generates document identifiers in response to queries.

Theoretical Analysis

We now turn to the fundamental question: how many parameters does a generative retrieval model need to memorise a corpus of N documents?

Proposition 27 (Memory Capacity for Generative Retrieval).

Let 𝒟={d1,,dN} be a corpus of N documents, each containing at most B bits of information. A generative retrieval model that memorises the corpus with zero error requires at least Ω(NB/logP) parameters, where P is the precision (number of bits) of each parameter.

Proof.

The corpus contains at most NB bits of information. Each parameter of the model stores at most P bits (for a P-bit floating-point representation). A model with M parameters can store at most MP bits of information. For zero-error memorisation, we require MPNB, which gives MNB/P.

More precisely, the model must store enough information to uniquely identify the relevant document for each possible query. If the mapping from queries to documents is injective (each query has a unique relevant document), then the model must distinguish N outcomes, requiring at least log2N bits per query. The total information stored must include both the document identifiers and the query-document associations, giving a lower bound of Ω(NB/logP) parameters.

Remark 49.

In practice, the required capacity is much larger than the information-theoretic lower bound. Neural networks are not optimal information storage devices: they store information in distributed representations with significant redundancy. Empirical observations suggest that a T5-XXL model (11B parameters, approximately 22 GB in 16-bit precision) can reliably memorise on the order of 105 to 106 passages. This is far below the capacity of a simple inverted index on the same hardware.

Conjecture 2 (Scaling Limit of Generative Retrieval).

A generative retrieval model can match the recall of an external-index retrieval system on a corpus of N documents only when the model's parameter count scales at least linearly with N. That is, there exists a constant α>0 (depending on the document distribution and query distribution) such that achieving Recall@k above a threshold τ requires MαN parameters.

This conjecture, if true, implies that generative retrieval faces a fundamental scalability barrier. External-index systems scale sublinearly in compute (logarithmic for tree-based indices, constant for hash-based indices) and linearly in storage. If generative retrieval requires linear parameter scaling, then for sufficiently large corpora, the cost of the generative model will exceed the cost of maintaining an external index.

The evidence supporting this conjecture is both theoretical and empirical. On the theoretical side, Proposition 27 establishes that the parameter count must grow at least as Ω(NB/logP), which is linear in N for fixed document size B. On the empirical side, published results show that generative retrieval quality degrades as corpus size grows beyond 106 documents unless the model size is increased proportionally.

The Road Ahead

Generative retrieval represents a fascinating intellectual direction, but its practical impact remains uncertain. The approach excels in settings where the corpus is small, relatively static, and the model has ample capacity. For large-scale, dynamic corpora, external-index systems remain the pragmatic choice.

The most promising near-term application may be in hybrid systems that combine generative retrieval with traditional methods. A generative model can serve as one signal among many in a retrieve-then-rerank pipeline, contributing its unique ability to capture holistic query-document relationships that are difficult to express as sparse or dense similarity scores.

Historical Note.

From Memex to Generative Retrieval In 1945, Vannevar Bush described the Memex, a hypothetical device that would store all of a person's books, records, and communications, and allow them to be consulted with exceeding speed and flexibility. Bush envisioned a mechanical device with microfilm and levers. Eight decades later, generative retrieval attempts something remarkably similar: encoding an entire corpus in the weights of a neural network, consultable by natural language. The vision has come full circle, from mechanical storage to parametric memory, and the fundamental question remains the same: how do we organise human knowledge so that it can be retrieved when needed?

Exercise 49.

Implement a simplified DSI system using a pre-trained T5-small model and the Natural Questions dataset. Experiment with three types of DocIDs: random numeric, title-based string, and hierarchical (using k-means clustering of document embeddings). Compare Recall@1 and Recall@10 for each ID type. Which ID strategy performs best, and why?

Exercise 50.

Implement semantic ID assignment using residual quantisation. Embed 10,000 Wikipedia passages using a pre-trained encoder, then apply RQ-VAE with L=3 levels and K=100 codewords per level. Visualise the resulting hierarchy: do semantically similar documents receive similar ID prefixes? Measure the collision rate (fraction of documents sharing an identical ID).

Exercise 51.

Design an experiment to empirically test the scaling conjecture (Conjecture 2). Train DSI models of increasing size (T5-small, T5-base, T5-large) on corpora of increasing size (103, 104, 105 passages). Plot Recall@10 as a function of the ratio M/N (parameters per passage). Is there a threshold ratio below which performance collapses?

Exercise 52.

Implement a simplified TIGER-style recommendation system. Use the MovieLens 100K dataset. Assign semantic IDs to movies using RQ-VAE on movie plot embeddings (from a pre-trained sentence encoder) with L=3 levels and K=32 codewords per level. Train a small Transformer to predict the next movie's semantic ID given a user's viewing history. Compare Hit Rate@10 against a standard matrix factorisation baseline. Does the semantic ID structure help with cold-start recommendations for movies with few ratings?

Exercise 53.

Conduct a head-to-head comparison of generative retrieval (DSI with semantic hierarchical IDs) against dense retrieval (a bi-encoder with FAISS index) on the same corpus and query set. Measure three metrics: (1) Recall@10, (2) latency per query, and (3) memory footprint. At what corpus size does the external-index approach begin to dominate in each metric?

Retrieval-Augmented Generation – Foundations

Large language models are brilliant but forgetful. They can write sonnets, summarise legal briefs, and explain quantum mechanics to a five-year-old, yet they cannot reliably tell you who won last week's football match. They hallucinate references that do not exist. They confidently state facts that were true in 2021 but have since changed. They have no mechanism for updating their knowledge without expensive retraining. The root cause is architectural: all of the model's knowledge is compressed into its parameters during pre-training, and those parameters are frozen at inference time.

Retrieval-augmented generation (RAG) is the solution. The idea is disarmingly simple: give the language model a library card. Instead of requiring the model to memorise every fact it might ever need, equip it with a retrieval system that can look up relevant information at inference time and feed it into the generation process. The model still generates fluent language; it simply does so while consulting an external knowledge source.

This section traces the development of RAG from its original formulation [25] through modern extensions including RETRO [26], Fusion-in-Decoder [27], and Self-RAG [28]. We formalise the key architectures, analyse their training objectives, and examine the fundamental design decisions that determine when and how to retrieve.

The Original RAG Framework

The retrieval-augmented generation framework was introduced by Lewis et al. in 2020 [25]. The paper proposed a general-purpose architecture that combines a pre-trained retrieval module with a pre-trained sequence-to-sequence generator, training them jointly end-to-end.

Architecture

The RAG architecture comprises three components:

  1. A parametric retriever pη(𝒛|𝒙), where 𝒙 is the input query and 𝒛 is a retrieved document. Lewis et al. used the Dense Passage Retriever (DPR), which encodes both queries and documents into dense vectors and retrieves by maximum inner product search: (DPR Score)pη(𝒛|𝒙)exp(Eq(𝒙),Ed(𝒛)), where Eq and Ed are BERT-based encoders for queries and documents respectively.

  2. A parametric generator p𝜽(yi|𝒙,𝒛,y1:i1), instantiated as a BART model that takes as input the concatenation of the query 𝒙 and the retrieved document 𝒛, and generates an output sequence 𝒚=(y1,,yN) autoregressively.

  3. A non-parametric knowledge index 𝒵, a dense index over a large corpus (e.g., Wikipedia) that supports fast approximate nearest-neighbour search using MIPS (Maximum Inner Product Search).

The elegance of this design is the separation of concerns. The retriever is responsible for finding relevant information; the generator is responsible for using it. The knowledge index serves as a non-parametric memory that can be updated without retraining: to incorporate new information, one simply adds new documents to the index.

Definition 56 (Retrieval-Augmented Generation).

A retrieval-augmented generation (RAG) system is a tuple (,𝒢,𝒵) comprising:

  • A retriever parameterised by η that maps an input 𝒙 to a distribution over documents pη(𝒛|𝒙) from a corpus 𝒵.

  • A generator 𝒢 parameterised by 𝜽 that produces output tokens conditioned on both the input and retrieved documents: p𝜽(𝒚|𝒙,𝒛).

  • A knowledge index 𝒵={𝒛1,,𝒛M} of M documents, each represented by a dense vector for efficient retrieval.

The joint probability of generating output 𝒚 given input 𝒙 is obtained by marginalising over retrieved documents: (RAG Marginal)P(𝒚|𝒙)=𝒛top-k(𝒙)pη(𝒛|𝒙)p𝜽(𝒚|𝒙,𝒛).

RAG-Sequence vs. RAG-Token

Lewis et al. proposed two variants that differ in how the marginalisation over retrieved documents is performed.

RAG-Sequence.

In RAG-Sequence, a single document is retrieved per output sequence. The model generates the entire output conditioned on that one document, and the final probability is a mixture over the top-k retrieved documents: (RAG Sequence)PRAG-Seq(𝒚|𝒙)=𝒛top-kpη(𝒛|𝒙)i=1Np𝜽(yi|𝒙,𝒛,y1:i1). Each document provides a coherent context for the entire generation. This is appropriate when the answer can be found in a single passage.

RAG-Token.

In RAG-Token, the marginalisation occurs at every output token. Different tokens in the output sequence can attend to different retrieved documents: (RAG Token)PRAG-Tok(𝒚|𝒙)=i=1N𝒛top-kpη(𝒛|𝒙)p𝜽(yi|𝒙,𝒛,y1:i1). This is more expressive: the model can synthesise information from multiple documents within a single output, drawing one fact from document 𝒛1 and another from 𝒛3. However, it requires k forward passes through the generator at each token position, making it more expensive.

Remark 50.

The distinction between RAG-Sequence and RAG-Token mirrors a recurring theme in probabilistic modelling: where to place the summation over latent variables. In RAG-Sequence, the latent variable 𝒛 has global scope (one draw per sequence). In RAG-Token, it has local scope (one draw per token). The global variant is cheaper but less expressive; the local variant is richer but more computationally demanding. This is precisely analogous to the difference between a mixture model with a single latent assignment and a hidden Markov model with per-step latent states.

RAG-Sequence vs. RAG-Token. In RAG-Sequence (left), each retrieved document conditions the generation of an entire output sequence, and the final output is a weighted mixture. In RAG-Token (right), the marginalisation over documents occurs at every token position, allowing different tokens to draw on different retrieved passages. RAG-Token is more expressive but computationally more expensive.

End-to-End Training

A distinctive feature of the original RAG framework is that the retriever and generator are trained jointly. The training objective maximises the marginal log-likelihood of the output given the input: (RAG Training)(η,𝜽)=(𝒙,𝒚)𝒟logP(𝒚|𝒙)=(𝒙,𝒚)𝒟log𝒛top-k(𝒙)pη(𝒛|𝒙)p𝜽(𝒚|𝒙,𝒛).

The gradient flows through both the generator and the retriever. The generator learns which parts of the retrieved document are useful; the retriever learns which documents lead to correct outputs. This creates a virtuous cycle: better retrieval leads to better generation, which provides better training signal for retrieval.

In practice, the document encoder Ed in the retriever is kept frozen during training (updating it would require re-indexing the entire corpus at each training step), while the query encoder Eq and the generator are updated. This asymmetric update strategy is a pragmatic compromise: the query encoder learns to produce queries that match the document representations in the existing index.

Key Idea.

RAG Separates What the Model Knows from What It Can Access The fundamental insight of RAG is the separation between parametric knowledge (facts compressed into the model's weights during pre-training) and non-parametric knowledge (facts stored in an external index that can be queried at inference time). Parametric knowledge is fast to access but expensive to update and prone to staleness. Non-parametric knowledge requires a retrieval step but can be updated instantly by modifying the index. RAG gives the model the best of both worlds: the fluency and reasoning ability of a large language model combined with the currency and verifiability of an external knowledge store.

Algorithm 12 (RAG-Sequence Inference).

  1. Input: Query 𝒙; retriever pη; generator p𝜽; knowledge index 𝒵; number of documents k
  2. Output: Generated output 𝒚^
  3. Retrieve: Compute query embedding 𝒒Eq(𝒙)
  4. Find top-k documents: 𝒵ktop-k𝒛𝒵𝒒,Ed(𝒛)
  5. Compute retrieval scores: sj𝒒,Ed(𝒛j) for each 𝒛j𝒵k
  6. Normalise: pjsoftmax(sj) Retrieval probabilities
  7. for j=1,,k
  8. Generate: 𝒚(j)arg max𝒚p𝜽(𝒚|𝒙,𝒛j) Beam search
  9. Compute generation log-prob: jlogp𝜽(𝒚(j)|𝒙,𝒛j)
  10. Marginalise: 𝒚^arg max𝒚(j)[logpj+j]
  11. return 𝒚^

Example 43 (RAG for Open-Domain Question Answering).

Consider the question 𝒙=“What is the half-life of carbon-14?” The RAG pipeline proceeds as follows:

  1. Encode query. The query encoder produces 𝒒=Eq(𝒙)768.

  2. Retrieve. MIPS against the Wikipedia index returns the top-5 passages. The highest-scoring passage 𝒛1 is from the article on radiocarbon dating: “Carbon-14 has a half-life of 5,730 ± 40 years. It decays by beta emission to nitrogen-14

  3. Generate. The BART generator receives [𝒙;𝒛1] as input and produces 𝒚=“5,730 years.” The retrieval probability for 𝒛1 is p1=0.72.

  4. Marginalise. The model also generates answers conditioned on the other four passages. Passage 𝒛3 (from an article on isotope geochemistry) also yields “5,730 years” with p3=0.15. The total probability mass on the correct answer is 0.72+0.15+0.93.

  5. Output. The final answer is “5,730 years” with high confidence, directly grounded in retrieved evidence.

Without retrieval, the same BART model might produce “5,700 years” or even “5,000 years,” lacking the precision that only an external source can provide.

Historical Note.

From Information Retrieval to Neural Retrieval The marriage of retrieval and generation was not inevitable. For decades, information retrieval and natural language generation developed as separate fields with separate communities, separate conferences, and separate assumptions. Information retrieval, born in the library science tradition, focused on finding relevant documents from a collection. The dominant paradigms were term-frequency methods (TF-IDF, 1972), probabilistic models (BM25, 1994), and learning-to-rank approaches (2000s). Generation, by contrast, focused on producing fluent text, progressing from template-based systems to statistical models to neural sequence-to-sequence architectures.

The critical bridge was dense retrieval. When Karpukhin et al. introduced the Dense Passage Retriever (DPR) in 2020, they showed that a simple dual-encoder architecture trained on question-answer pairs could outperform BM25 on open-domain question answering. DPR made retrieval differentiable: the retrieval score was a smooth function of the query and document encoders, enabling end-to-end training through the retrieval step. Lewis et al. immediately exploited this by connecting DPR to BART, creating RAG. The insight was that if retrieval is differentiable, it can be treated as a latent variable and marginalised out during training, just like any other latent variable in a probabilistic model.

The RAG architecture. A query is encoded into a dense vector by the query encoder, which retrieves the top-k most relevant documents from a pre-built knowledge index via MIPS. The retrieved documents are concatenated with the original query and fed to the generator, which produces the output. The document encoder operates offline to build the index; only the query encoder and generator are active at inference time.

RETRO: Retrieval from Trillions of Tokens

The original RAG framework retrieves documents at the sequence level: given a query, retrieve k passages and condition generation on them. RETRO (Retrieval-Enhanced Transformer), introduced by Borgeaud et al. [26], takes a fundamentally different approach. It retrieves at the chunk level, integrating retrieval directly into the transformer architecture at multiple points during generation.

Chunked Cross-Attention

The key architectural innovation in RETRO is chunked cross-attention (CCA). The input sequence is split into chunks of m tokens each. For each chunk Cu (the u-th chunk of the input), RETRO retrieves the top-k nearest neighbours from a database of 2 trillion tokens. These neighbours are then integrated into the model through a cross-attention mechanism that operates at specific layers.

Formally, let 𝐇u()m×d be the hidden states of chunk u at layer , and let 𝐄u=[𝒆u(1);;𝒆u(k)]km×d be the encoded representations of the k retrieved neighbours for chunk u, each of length m. The chunked cross-attention computes: (Retro CCA)CCA(𝐇u(),𝐄u)=softmax(𝐇u()𝐖Q(𝐄u𝐖K)dk)𝐄u𝐖V, where 𝐖Q,𝐖K,𝐖V are the standard query, key, and value projection matrices. The CCA output is added to the residual stream at designated “retrieval layers” (typically every third layer).

The critical advantage is efficiency. Because retrieval operates at the chunk level, the cross-attention cost scales with the chunk size m rather than the full sequence length. Moreover, the retrieved neighbours are encoded by a frozen BERT encoder, avoiding the need to backpropagate through the retrieval index.

Lemma 9 (RETRO Chunked Cross-Attention Cost).

Let n be the total input sequence length, m the chunk size, k the number of retrieved neighbours per chunk, and m the length of each neighbour. The total cost of chunked cross-attention across all chunks is: (Retro CCA COST)CCCA=nmO(mkmd)=O(nkmd1)=O(nkmd). This is linear in the sequence length n, independent of the chunk size m. In contrast, full self-attention over the input concatenated with all retrieved neighbours would cost O((n+nkm/m)2d), which is quadratic.

Proof.

There are n/m chunks. For each chunk, the cross-attention computes queries from m token representations and keys/values from km neighbour representations, giving a cost of O(mkmd) per chunk. Summing over all n/m chunks: (n/m)O(mkmd)=O(nkmd). The m in the numerator and denominator cancel, yielding a cost that is independent of the chunk size.

Scaling Laws: Retrieval as a Substitute for Parameters

Perhaps the most striking finding from the RETRO paper is that retrieval can substitute for model parameters. A 7.5-billion-parameter RETRO model with access to a 2-trillion-token retrieval database achieves performance comparable to models with 25 times more parameters (around 175 billion, GPT-3 scale) without retrieval on language modelling benchmarks. This suggests a new dimension in the scaling laws for language models: instead of only scaling parameters and training data, one can also scale the retrieval database.

Proposition 28 (Retrieval-Parameter Trade-off).

Let (N,D,R) denote the language modelling loss of a model with N parameters, trained on D tokens, with access to a retrieval database of R tokens. Under the RETRO scaling regime, satisfies: (Retro Scaling)(N,D,R)αNa+βDb+γRc+, where α,β,γ>0 are constants, a,b,c>0 are scaling exponents, and is the irreducible loss. The exponent c for retrieval database size is positive, confirming that increasing the retrieval database reduces loss, even when N and D are held fixed.

Remark 51.

The practical implications of Proposition 28 are profound. Training a 25-billion-parameter model from scratch is enormously expensive, requiring thousands of GPU-hours. Indexing a 2-trillion-token database, by contrast, is a one-time cost that can be amortised across all queries. If retrieval can substitute for parameters at favourable exchange rates, then RAG is not just an accuracy improvement but an economic one: it reduces the total cost of achieving a given performance level.

Fusion-in-Decoder

Fusion-in-Decoder (FiD), proposed by Izacard and Grave [27], offers an elegant solution to a practical problem: how to condition generation on a large number of retrieved passages without the quadratic attention cost of concatenating them all into a single input sequence.

The key idea is simple but effective. Each retrieved passage 𝒛j is independently concatenated with the query 𝒙 and encoded by the encoder: (FID Encode)𝒉j=Encoder([𝒙;𝒛j]),j=1,,k. The encoded representations 𝒉1,,𝒉k are then concatenated and fed to the decoder, which attends over all of them jointly: (FID Decode)P(𝒚|𝒙,𝒛1:k)=Decoder([𝒉1;𝒉2;;𝒉k]).

The advantage is computational. The encoder processes each passage independently, so its cost scales linearly with k. Self-attention within each encoded passage is quadratic in the passage length, but since each passage is short (typically 100 tokens), the total encoder cost is O(kn2) where n is the passage length. This is far cheaper than encoding a single concatenated sequence of length kn, which would cost O(k2n2).

Lemma 10 (Fusion-in-Decoder Attention Complexity).

Let k be the number of retrieved passages, each of length n, and let m be the output length. The attention cost of Fusion-in-Decoder is O(kn2+mkn): the first term is the cost of independently encoding k passages, and the second term is the cost of the decoder cross-attending over the kn concatenated encoder outputs at each of m decoder steps. In contrast, a naive concatenation approach has cost O(k2n2) for the encoder alone.

Proof.

The encoder processes k passages independently, each of length n. Self-attention in each has cost O(n2), so the total encoder cost is O(kn2). The decoder has m steps, and at each step it cross-attends over all kn encoder outputs, contributing O(kn) per step for a total of O(mkn). Adding both terms gives O(kn2+mkn). The naive approach encodes a single sequence of length kn, with self-attention cost O((kn)2)=O(k2n2). Since k is typically 10–100, the FiD approach is significantly cheaper.

FiD achieves state-of-the-art results on open-domain QA benchmarks (Natural Questions, TriviaQA) by leveraging up to 100 retrieved passages, a number that would be infeasible with naive concatenation. The decoder learns to cross-attend selectively, focusing on the most relevant passages and ignoring irrelevant ones.

Adaptive Retrieval: Self-RAG

The systems described so far retrieve for every query. But retrieval is not always necessary. If you ask a language model “What is 2 + 2?” it does not need to consult Wikipedia. If you ask it to write a haiku about autumn, retrieval might actually hurt by introducing irrelevant context that distracts the generator. The question is: can the model learn when to retrieve?

Self-RAG, introduced by Asai et al. [28], answers this question affirmatively. The model is trained to generate special reflection tokens that control the retrieval process and evaluate the quality of the generated output.

Reflection Tokens

Self-RAG introduces four types of reflection tokens:

  1. [Retrieve]: Should the model retrieve? Values: yes, no, continue. The model generates this token before each segment. If the value is yes, retrieval is performed; if no, the model generates from its parametric knowledge alone.

  2. [IsRel]: Is the retrieved passage relevant to the query? Values: relevant, irrelevant. Generated after retrieval, this token filters out passages that the retriever selected but that the generator judges as unhelpful.

  3. [IsSup]: Is the generation supported by the retrieved passage? Values: fully_supported, partially_supported, no_support. This token enforces faithfulness: the model must assess whether its own output is grounded in the evidence.

  4. [IsUse]: Is the overall response useful? Values: rating from 1 to 5. This final reflection token provides an overall quality judgement.

The self-critique mechanism is the defining feature of Self-RAG. Rather than blindly incorporating retrieved information, the model reflects on the quality of retrieval and generation at each step. This transforms the model from a passive consumer of retrieved information into an active critic of its own output.

Self-RAG decision tree. At each generation step, the model first decides whether to retrieve (the [Retrieve] token). If retrieval is triggered, the model assesses relevance ([IsRel]), generates conditioned on relevant passages, checks whether the generation is supported by the evidence ([IsSup]), and finally rates the overall usefulness ([IsUse]). Unsupported or irrelevant results trigger re-generation or passage re-ranking.

Training Self-RAG

Self-RAG is trained in two phases. First, a critic model is trained to generate reflection tokens given (query, passage, generation) triples. The critic is trained on data annotated by GPT-4, which labels each triple with the appropriate reflection token values. Second, the generator is trained to produce both the output text and the reflection tokens, using the critic's labels as supervision.

The training objective combines the standard language modelling loss with a reflection token prediction loss: (Selfrag LOSS)Self-RAG=LM(𝒚|𝒙,𝒛)+λrreflCE(r|𝒙,𝒛,𝒚), where refl={[Retrieve], [IsRel], [IsSup], [IsUse]} and CE is the cross-entropy loss for each reflection token. The hyperparameter λ controls the weight of the reflection loss.

Algorithm 13 (Self-RAG with Reflection Tokens).

  1. Input: Input 𝒙; generator 𝒢; retriever ; critique weights {wrel,wsup,wuse}
  2. Output: Output 𝒚^ with reflection scores
  3. Generate [Retrieve] token: rret𝒢.predict_token(𝒙)
  4. if rret=𝚗𝚘
  5. 𝒚^𝒢.generate(𝒙) No retrieval needed
  6. Generate [IsUse]: suse𝒢.predict_token(𝒙,𝒚^)
  7. return (𝒚^,suse)
  8. Retrieve: {𝒛1,,𝒛k}(𝒙)
  9. for j=1,,k
  10. Generate [IsRel]: srel(j)𝒢.predict_token(𝒙,𝒛j)
  11. if srel(j)=𝚒𝚛𝚛𝚎𝚕𝚎𝚟𝚊𝚗𝚝
  12. continue Skip irrelevant passages
  13. Generate output: 𝒚(j)𝒢.generate(𝒙,𝒛j)
  14. Generate [IsSup]: ssup(j)𝒢.predict_token(𝒙,𝒛j,𝒚(j))
  15. Generate [IsUse]: suse(j)𝒢.predict_token(𝒙,𝒛j,𝒚(j))
  16. Compute score: σjwrelsrel(j)+wsupssup(j)+wusesuse(j)
  17. jarg maxjσj
  18. return (𝒚(j),σj)

The Retrieve-Then-Read vs. Generate-Then-Retrieve Debate

The architectures discussed so far follow the retrieve-then-read paradigm: first retrieve relevant documents, then generate an output conditioned on them. An alternative paradigm inverts the order: generate-then-retrieve [94]. The model first generates a preliminary answer or a set of search queries, then retrieves documents to verify, refine, or extend the initial generation.

The generate-then-retrieve approach has several advantages. First, the model's initial generation can serve as a better query than the raw input, because the model can reformulate the question, expand acronyms, and resolve ambiguities. Second, the retrieved documents can serve as a verification mechanism: if the initial generation is consistent with the retrieved evidence, confidence increases; if it contradicts the evidence, the model can revise.

A formal comparison clarifies the trade-offs. Let 𝒙 be the input, the retriever, and 𝒢 the generator.

Retrieve-then-read.

(Retrieve THEN READ)𝒚^=𝒢(𝒙,(𝒙)). The retrieval query is 𝒙 itself. If 𝒙 is ambiguous, under-specified, or uses different terminology than the documents in the index, retrieval may fail.

Generate-then-retrieve.

(Generate THEN Retrieve)𝒚~=𝒢(𝒙),𝒚^=𝒢(𝒙,(𝒚~)). The retrieval query is the model's preliminary generation 𝒚~, which may be more informative than the raw input. However, this requires two generator passes and one retrieval call, increasing latency.

Iterative retrieval-generation.

(Iterative RAG)𝒚(0)=𝒙,𝒚(t)=𝒢(𝒚(t1),(𝒚(t1))),t=1,,T. The model iteratively refines its output, using each intermediate result as a retrieval query for the next round. This is the most expressive but also the most expensive approach, requiring T generator passes and T retrieval calls.

Remark 52.

The retrieve-then-read and generate-then-retrieve paradigms are not mutually exclusive. Modern systems increasingly adopt iterative approaches that alternate between generation and retrieval: generate an initial draft, retrieve supporting evidence, revise the draft, retrieve again if necessary, and so on. This iterative pattern mirrors how human experts write: draft, research, revise, repeat. The choice among these paradigms depends on the latency budget, the complexity of the query, and the quality of the initial retrieval. For simple factoid questions, retrieve-then-read suffices. For complex multi-hop reasoning, iterative approaches are often necessary.

Insight.

The Quality of the Retrieval Query Determines the Quality of the RAG Output A RAG system is only as good as its retrieval queries. If the query fails to capture the user's intent, the retrieved documents will be irrelevant, and the generator will either hallucinate or produce a generic answer. The generate-then-retrieve paradigm addresses this by using the model's own understanding of the query to formulate a better retrieval request. Self-RAG addresses it by allowing the model to assess retrieval quality after the fact and retry if necessary. Both approaches recognise the same fundamental truth: retrieval is not a solved problem, and the interface between the model and the index deserves as much attention as the model architecture itself.

Exercise 54.

Consider a factoid question answering task with 10 million documents in the index.

  1. Write the RAG-Sequence and RAG-Token objectives for this setting. Under what conditions does RAG-Token reduce to RAG-Sequence?

  2. A user asks: “What country has the largest population?” The model retrieves five passages, three of which mention India (with 2024 data) and two of which mention China (with 2020 data). Explain how RAG-Sequence and RAG-Token would handle this discrepancy differently.

  3. Propose an extension of Self-RAG that generates not only reflection tokens but also re-query tokens that reformulate the retrieval query based on the initial results. Write pseudocode for your proposed algorithm.

Exercise 55.

Consider a RETRO model with chunk size m=64, k=2 retrieved neighbours per chunk, and a retrieval database of R tokens.

  1. Derive the total number of cross-attention operations per input chunk, assuming neighbour length m=64 and hidden dimension d=1024.

  2. If the retrieval database doubles from R to 2R, estimate the expected improvement in perplexity using the scaling law in (Retro Scaling), assuming c0.1.

  3. Compare the memory footprint of storing R=1012 tokens in a dense index (with d=768-dimensional vectors in float16) vs. storing the same number of parameters in a transformer model. Which is more cost-effective?

RAG for Grounding and Verification

Large language models generate text that is fluent, grammatical, and often convincing. The problem is that fluency and truth are orthogonal properties. A model can produce a paragraph that reads beautifully and is entirely false. This is the hallucination problem, and it represents one of the most significant obstacles to deploying language models in high-stakes domains such as medicine, law, and finance.

Retrieval offers a path toward solving this problem. If every claim in the model's output can be traced to a specific source document, then the output is grounded: it is connected to verifiable evidence rather than floating free in the space of plausible-sounding text. This section examines how RAG enables grounding, how to evaluate it, and how to extend it to multi-step reasoning and formal verification.

Attribution and Faithfulness

Two related but distinct concepts govern the quality of grounded generation.

Definition 57 (Attribution).

A generated claim c is attributed to a source document 𝒛 if 𝒛 contains information that, according to a reasonable reading, supports c. Formally, let NLI(𝒛,c){entail,contradict,neutral} denote a natural language inference judgement. Then c is attributed to 𝒛 if NLI(𝒛,c)=entail.

Definition 58 (Faithfulness).

A generated output 𝒚=(c1,,cn) consisting of n claims is faithful to a set of retrieved documents 𝒵k={𝒛1,,𝒛k} if every claim is attributable: (Faithfulness)Faithful(𝒚,𝒵k)ci𝒚,𝒛j𝒵k s.t. NLI(𝒛j,ci)=entail.

Theorem 10 (Faithfulness Bound via Retrieval Quality).

Let 𝒵k be the top-k retrieved passages for query 𝒙, and let 𝒚=(c1,,cn) be the generated output. Let r=Precision@k be the fraction of relevant passages in 𝒵k, and let f be the probability that the generator produces a faithful claim given a relevant passage. Then the expected faithfulness score satisfies: (Faithfulness Bound)𝔼[Faith(𝒚,𝒵k)]1(1rf)k. That is, faithfulness improves with both retrieval precision and the number of retrieved passages, approaching 1 as either r, f, or k increases.

Proof.

A claim ci is faithful if at least one retrieved passage is both relevant and supports the claim. The probability that a single passage is relevant and supports ci is at least rf (precision times generator faithfulness given relevance). The probability that no passage supports ci is at most (1rf)k, assuming independence across passages. Therefore, Pr[ci is faithful]1(1rf)k. Since this holds for each claim, the expected faithfulness score (the average over claims) satisfies the same bound.

The distinction between attribution and faithfulness, on one hand, and correctness, on the other, is crucial. A claim can be faithfully attributed to a source and still be wrong, if the source itself contains an error. Attribution tells us where the information came from; it does not guarantee that the source is reliable.

Caution.

Attribution Is Not Verification A grounded claim can still be wrong if the source is wrong. Attribution establishes provenance, not truth. If a RAG system retrieves an outdated Wikipedia article stating that Pluto is a planet, and the generator faithfully reproduces this claim, the output is attributed (we can trace it to a source) and faithful (it accurately reflects the source) but incorrect (Pluto was reclassified in 2006). Verification requires an additional step: assessing the reliability and currency of the source itself. In high-stakes domains, RAG systems should not only retrieve and attribute but also rank sources by trustworthiness, recency, and authority.

The grounding pipeline. A generated output is decomposed into individual claims. Each claim is linked to a source document via a natural language inference (NLI) checker that determines whether the source entails the claim. The faithfulness score is the fraction of claims that are attributed to at least one source. In this example, claims c1 and c2 are grounded but c3 is not, yielding a faithfulness score of 2/3.

RAG Evaluation Frameworks

Evaluating a RAG system requires assessing multiple dimensions simultaneously. A system that retrieves relevant documents but generates unfaithful answers is dangerous. A system that generates faithful answers to the wrong question is useless. The community has developed multi-dimensional evaluation frameworks to capture these distinctions.

RAGAS: Retrieval-Augmented Generation Assessment

The RAGAS framework [95] decomposes RAG quality into three orthogonal dimensions:

  1. Context relevance: Are the retrieved passages relevant to the query? This measures retrieval quality independently of generation. Let 𝒙 be the query and 𝒵k={𝒛1,,𝒛k} be the retrieved passages. Context relevance is: (Context Relevance)CR(𝒙,𝒵k)=1kj=1k𝟙[𝒛j is relevant to 𝒙].

  2. Faithfulness: Does the generated answer accurately reflect the retrieved context? This measures whether the generator introduces information not supported by the retrieval. Let 𝒚 be the generated answer decomposed into claims {c1,,cn}. Faithfulness is: (Faithfulness Score)Faith(𝒚,𝒵k)=1ni=1n𝟙[𝒛j𝒵k:NLI(𝒛j,ci)=entail].

  3. Answer relevance: Does the generated answer actually address the query? A faithful answer to the wrong question scores high on faithfulness but low on answer relevance. Answer relevance is measured by generating synthetic questions from the answer and computing their semantic similarity to the original query: (Answer Relevance)AR(𝒙,𝒚)=1|𝒬|𝒙𝒬sim(𝒙,𝒙), where 𝒬 is the set of synthetic questions generated from 𝒚 and sim is a semantic similarity function.

The three dimensions of RAG evaluation. Context relevance measures whether the retriever found the right documents. Faithfulness measures whether the generator accurately reflects the retrieved evidence. Answer relevance measures whether the final answer addresses the original query. A system can fail on any dimension independently.

Retrieval-Specific Metrics

Beyond the RAGAS dimensions, several metrics target retrieval quality directly [96]:

  • Precision@k: The fraction of top-k retrieved passages that are relevant: (Precision AT K)Precision@k=|{𝒛j𝒵k:𝒛j is relevant}|k.

  • Recall@k: The fraction of all relevant passages that appear in the top-k: (Recall AT K)Recall@k=|{𝒛j𝒵k:𝒛j is relevant}||{𝒛𝒵:𝒛 is relevant}|.

  • Attribution accuracy: The fraction of generated claims for which the system can identify a supporting source passage. This differs from faithfulness in that attribution requires an explicit link between claim and source, not merely entailment.

Example 44 (Diagnosing RAG Failures with RAGAS).

Consider a medical QA system with the query: “What are the side effects of metformin?”

  • Scenario A: Low context relevance. The retriever returns passages about diabetes management in general, none of which specifically discuss metformin. CR=0.1. The generator hallucinates side effects from its parametric knowledge. Faith=0.2 (most claims are unsupported by retrieval). AR=0.8 (the answer does address the question). Diagnosis: retriever failure.

  • Scenario B: High context relevance, low faithfulness. The retriever returns the correct passages. CR=0.9. But the generator introduces a claim that “metformin causes liver failure,” which none of the retrieved passages support (metformin is contraindicated in liver disease but does not cause it). Faith=0.6. AR=0.9. Diagnosis: generator unfaithfulness.

  • Scenario C: High faithfulness, low answer relevance. The retriever returns relevant passages and the generator faithfully reproduces their content. But the passages discuss metformin's mechanism of action, not its side effects. CR=0.7 (partially relevant). Faith=0.95. AR=0.3. Diagnosis: the retriever found passages about the right drug but wrong topic.

Each scenario requires a different fix: improving the retriever (A), constraining the generator to be more faithful (B), or refining the retrieval query to match the question's intent more precisely (C).

Verification with Retrieved Facts

Grounding takes on special significance in formal domains where correctness can be mechanically checked. Consider theorem proving: a domain where every claim must be logically deduced from axioms and previously established results.

Theorem Proving with Retrieved Lemmas

A particularly compelling application of RAG is automated theorem proving, where the model generates proof steps and retrieves relevant lemmas from a mathematical library to support each step. This connects directly to the formal verification tools discussed in the evolutionary AI chapter, particularly the Lean theorem prover [97].

The proof verification pipeline operates as follows:

  1. Conjecture. The system is given a mathematical statement to prove.

  2. Generate candidate proof steps. A language model proposes a sequence of proof tactics, each of which transforms the current proof state.

  3. Retrieve related theorems. For each proposed tactic, the system retrieves potentially relevant lemmas, definitions, and previously proven theorems from the mathematical library (e.g., Lean's mathlib).

  4. Verify consistency. Each proof step is checked by the formal verifier (Lean's type checker) to ensure it is logically valid. Retrieved lemmas that the proof step depends on must themselves be verified theorems.

  5. Iterate. If a step fails verification, the model backtracks and generates alternative steps, potentially with new retrieval queries informed by the failure.

This pipeline was spectacularly demonstrated by AlphaProof [98], which solved International Mathematical Olympiad problems by combining a language model with the Lean theorem prover. The retrieval component was essential: the model needed access to a vast library of mathematical facts to construct valid proofs.

Retrieval-augmented theorem proving. A language model generates candidate proof tactics, retrieves relevant lemmas from a mathematical library, and submits the augmented proof step to a formal verifier (e.g., Lean). Valid steps advance the proof; invalid steps trigger backtracking and re-generation. The retrieval component provides the model with the mathematical knowledge needed to construct valid proofs.

Example 45 (Retrieval-Augmented Proof Construction).

Suppose the goal is to prove that 2 is irrational in Lean. The model generates the initial tactic: “assume for contradiction that 2=p/q with gcd(p,q)=1.” The retrieval system queries mathlib and returns:

  • Nat.Coprime.eq_one_of_self_mul_self: if gcd(a,b)=1 and a2|b2, then a=1.

  • Int.sqrt_two_not_rat: a direct proof (which the model could invoke if available).

  • Int.even_iff_two_dvd: n is even iff 2|n.

The model uses the first and third lemmas to construct the classic infinite descent argument: p2=2q2 implies p is even, so p=2p, giving 2p2=q2, which implies q is even, contradicting gcd(p,q)=1. Each step is verified by Lean's type checker, ensuring logical correctness.

Exercise 56.

Consider building a retrieval-augmented theorem prover for a library containing 50,000 lemmas.

  1. Each lemma statement is encoded as a 768-dimensional dense vector. Compute the memory required for the index in float32 and in float16. How does this compare to the memory footprint of a 7B-parameter language model?

  2. The prover generates a proof tactic and needs to retrieve the 10 most relevant lemmas. If the inner product computation takes O(d) time per lemma, what is the total retrieval time? How could approximate nearest-neighbour methods (e.g., HNSW) reduce this?

  3. Discuss the failure modes unique to retrieval-augmented theorem proving. How does retrieval failure (returning irrelevant lemmas) differ in its consequences from retrieval failure in open-domain QA?

  4. Propose a method for the theorem prover to learn which lemmas are most useful for which types of proof goals, using the success or failure of the Lean verifier as a reward signal. How does this relate to reinforcement learning from human feedback (RLHF)?

Grounding in Multi-Step Reasoning

Many real-world queries require multi-step reasoning. The question “Did the architect of the Eiffel Tower also design the Statue of Liberty's internal structure?” requires the model to (1) identify the architect of the Eiffel Tower (Gustave Eiffel), (2) identify the designer of the Statue of Liberty's internal structure (also Gustave Eiffel), and (3) determine that they are the same person. Each step may require its own retrieval.

Two approaches have emerged for combining retrieval with chain-of-thought reasoning:

Retrieve once, reason many.

Retrieve all potentially relevant documents at the outset, then perform multi-step reasoning over the retrieved set. This is efficient (only one retrieval call) but may miss documents that become relevant only after intermediate reasoning steps.

Interleaved retrieval and generation.

Retrieve at each reasoning step, using the intermediate results to formulate new retrieval queries. This is more expressive: the model can discover that it needs information about Gustave Eiffel only after the first retrieval reveals him as the Eiffel Tower's architect.

Proposition 29 (Interleaved Retrieval Dominates Single Retrieval).

Let 𝒙 be a query requiring T reasoning steps. Let 𝒵single be the set of documents retrieved by a single retrieval call on 𝒙, and let 𝒵inter=t=1T𝒵(t) be the union of documents retrieved at each reasoning step. Then 𝒵single𝒵inter in general does not hold (the two sets may be incomparable), but the information-theoretic utility satisfies: (Interleaved)𝖨(𝒚;𝒵inter|𝒙)𝖨(𝒚;𝒵single|𝒙), where 𝖨 denotes mutual information and 𝒚 is the correct answer. Equality holds when all relevant information is retrievable from the original query alone.

Proof.

Define the sequence of reasoning states 𝒔0=𝒙,𝒔1,,𝒔T, where 𝒔t incorporates information from retrieval steps 1,,t. At each step t, the retrieval 𝒵(t) is conditioned on 𝒔t1, which encodes the accumulated reasoning. By the data processing inequality, conditioning on more information cannot decrease mutual information: 𝖨(𝒚;𝒵(t)|𝒔t1)𝖨(𝒚;𝒵(t)|𝒔0). The total information from interleaved retrieval is 𝖨(𝒚;𝒵inter|𝒙)=t=1T𝖨(𝒚;𝒵(t)|𝒔t1,𝒵(1:t1)), which by the chain rule of mutual information and the fact that each 𝒵(t) is conditioned on the optimal state 𝒔t1, is at least as large as the single-retrieval quantity.

Exercise 57.

Consider the multi-hop question: “What is the population of the country where the inventor of the telephone was born?”

  1. Identify the reasoning steps required and the retrieval query appropriate for each step.

  2. For the “retrieve once” approach, write a single query that might retrieve all necessary information. Analyse why this query is likely to fail.

  3. Implement the interleaved approach as pseudocode, showing how each retrieval query is formulated based on the previous step's result.

  4. Compute the number of retrieval calls for each approach and discuss the latency-accuracy trade-off.

RAG Across Modalities

The RAG paradigm was born in the world of text, but information does not respect modality boundaries. A doctor diagnosing a patient may need to retrieve medical images alongside journal articles. An engineer troubleshooting a machine may need to retrieve schematic diagrams, maintenance logs in text, and even audio recordings of the machine's operation. A student writing a report may need to retrieve figures, tables, and charts from papers.

Extending RAG to multiple modalities introduces new challenges. How do you index and retrieve images alongside text? How do you fuse information from a retrieved audio clip with a text prompt? What happens when the retrieval modality differs from the generation modality?

This section surveys multimodal RAG across vision, speech, audio, and video, tracing the rapid expansion of the RAG paradigm beyond its textual origins.

Visual Document RAG

Many real-world documents are not plain text. They contain tables, charts, diagrams, equations, and complex layouts that lose crucial information when converted to text via OCR. Visual document RAG addresses this by treating document pages as images and retrieving them based on visual similarity.

VDocRAG: Visually-Rich Document RAG

VDocRAG [29] operates on the principle that the visual rendering of a document is often more informative than its textual extraction. A table in a financial report, for instance, has a spatial structure (rows, columns, headers) that is immediately apparent from the visual rendering but is destroyed by naive text extraction.

The VDocRAG pipeline comprises:

  1. Visual encoding. Each document page is encoded as an image by a vision encoder (e.g., a Vision Transformer), producing a dense representation 𝒗j=ViT(Ij)d for page image Ij.

  2. Visual indexing. The page representations are stored in a dense index, analogous to the text index in standard RAG but over visual representations.

  3. Query-visual retrieval. Given a text query 𝒙, a cross-modal encoder maps it to the same representation space: 𝒒=Ecross(𝒙)d. Retrieval is by maximum inner product search: top-kj𝒒,𝒗j.

  4. Visual-grounded generation. The retrieved page images are fed to a vision-language model that generates the answer conditioned on both the query and the visual content.

The advantage over text-based RAG is substantial for documents with rich visual structure. Tables, charts, and diagrams are retrieved and interpreted in their native visual form, avoiding the information loss inherent in OCR and layout parsing.

Multi-Level Visual QA

Not all visual information is at the same granularity. A question about a specific cell in a table requires fine-grained retrieval; a question about overall trends in a chart requires coarser retrieval. Multi-level VQA [99] addresses this by retrieving at multiple granularities simultaneously: document level, page level, region level, and element level.

Definition 59 (Multi-Level Retrieval).

A multi-level retrieval system maintains indices at L granularity levels 𝒵(1),,𝒵(L), where 𝒵() contains representations at granularity level (e.g., document, page, region, element). Given a query 𝒙, the system retrieves at each level: 𝒵k()=top-k()(𝒙) for =1,,L. The generator conditions on the union: (Multilevel)P(𝒚|𝒙)=p𝜽(𝒚|𝒙,=1L𝒵k()).

Knowledge-Based Visual QA

Some visual questions require external knowledge that is not present in the image. The question “What architectural style is this building?” given a photo requires the model to recognise visual features (pointed arches, flying buttresses) and link them to knowledge about Gothic architecture. KB-VQA systems retrieve from a knowledge base (e.g., Wikipedia, Wikidata) conditioned on both the image and the question, fusing visual perception with encyclopaedic knowledge.

The KB-VQA pipeline combines three types of representation:

  1. A visual representation 𝒗=ViT(I) capturing the image content.

  2. A textual representation 𝒒=Eq(𝒙) capturing the question semantics.

  3. A knowledge representation 𝒌=Ek(𝒛) capturing the retrieved facts from the knowledge base.

The generator fuses all three: P(𝒚|𝒙,I)=p𝜽(𝒚|𝒗,𝒒,𝒌). This three-way fusion is more complex than standard text RAG but enables answering questions that require both visual perception and world knowledge.

Example 46 (KB-VQA in Practice).

A user photographs a building and asks: “When was this building constructed?” The visual encoder recognises features consistent with Art Deco architecture (geometric forms, stepped facade, decorative spandrels). The cross-modal retriever queries a knowledge base and returns the Wikipedia article on the Empire State Building, which includes the construction date (1930–1931). The generator produces: “This building, which appears to be the Empire State Building based on its Art Deco features, was constructed between 1930 and 1931.” The answer integrates visual recognition, knowledge retrieval, and natural language generation.

Speech RAG

Speech processing introduces unique challenges for RAG. Audio signals are high-dimensional and temporally extended. Traditional speech systems rely on an ASR (automatic speech recognition) pipeline to transcribe audio to text, then apply text-based RAG. But this pipeline approach has a fundamental flaw: ASR errors propagate through the entire system. A misrecognised proper noun in the transcription leads to a failed retrieval, which leads to a wrong answer.

ReSLM: Retrieval-Enhanced Speech Language Model

ReSLM [30] addresses the domain adaptation problem in speech recognition through retrieval. When a speech model encounters domain-specific entities (medical terms, company names, technical jargon), it often fails because these entities are underrepresented in its training data.

ReSLM works by maintaining a retrieval index of domain-specific entities along with their audio representations. When the speech model encounters an ambiguous segment, it retrieves the most likely entity from the index and biases the recognition toward it.

The architecture comprises:

  1. Speech encoder. Encodes the input audio into a sequence of frame-level representations 𝐇=(𝒉1,,𝒉T).

  2. Entity retriever. For each audio segment, queries a joint speech-text index of domain entities. The index contains both the text form (“metformin”) and a representative audio embedding of each entity.

  3. Biased decoding. The retrieved entities bias the decoder's output distribution via shallow fusion: (Reslm BIAS)logP(yt|y<t,𝐇)logP(yt|y<t,𝐇)+α𝟙[ytret], where ret is the set of retrieved entities and α>0 is a bias weight.

WavRAG: Audio-Native RAG

WavRAG [31] takes a more radical approach: it bypasses ASR entirely, performing retrieval directly in the audio domain.

Insight.

Bypassing ASR Eliminates Error Compounding In a traditional pipeline, an ASR error rate of 10% means that roughly 10% of the retrieval queries contain errors. If the retrieval system has its own 10% error rate on correct queries, the compounded error rate on queries with ASR mistakes is substantially higher: the retriever receives a garbled query and returns irrelevant results. WavRAG's direct audio retrieval avoids this compounding: the retrieval operates on the original audio signal, not on a potentially corrupted transcription. The total error is that of a single system rather than the product of two.

WavRAG represents both audio queries and audio documents as embeddings in a shared space, using a model trained with contrastive learning. The query is an audio segment; the index contains audio segments paired with their metadata. Retrieval is by standard nearest-neighbour search in the embedding space.

Speech RAG: pipeline vs. end-to-end. The traditional pipeline (top) transcribes audio via ASR, then applies text-based RAG. ASR errors corrupt the retrieval query, leading to cascading failures. WavRAG (bottom) bypasses ASR entirely, encoding audio directly into an embedding space for retrieval. This eliminates the error compounding inherent in the pipeline approach.

Audio RAG for Generation

The RAG paradigm extends naturally to audio generation. Just as a text RAG system retrieves passages to condition text generation, an audio RAG system retrieves audio clips to condition audio synthesis.

Re-AudioLDM: Retrieval-Augmented Audio Generation

Re-AudioLDM [32] augments a latent diffusion model for audio generation with a retrieval component based on CLAP (Contrastive Language-Audio Pretraining).

The system operates as follows:

  1. Text prompt encoding. A text caption (e.g., “a dog barking in the rain”) is encoded by the CLAP text encoder into an embedding 𝒕d.

  2. Audio retrieval. The CLAP embedding is used to retrieve the top-k most similar audio clips from a large audio database: 𝒜k=top-ka𝒜𝒕,Ea(a), where Ea is the CLAP audio encoder.

  3. Feature extraction. Acoustic features are extracted from the retrieved clips (e.g., mel-spectrograms, CLAP embeddings) and aggregated into a conditioning vector 𝒄ret.

  4. Conditioned diffusion. The latent diffusion model generates audio conditioned on both the text embedding and the retrieval features: (Reaudioldm)𝒛^0=LDM(𝒛T,𝒕,𝒄ret), where 𝒛T is noise and 𝒛^0 is the denoised latent, which is decoded to a waveform by a vocoder.

The retrieved audio serves as an acoustic “reference” that guides the diffusion model toward realistic sound textures. Without retrieval, the model must generate the characteristics of rain, dog barking, and their interaction entirely from its parametric knowledge. With retrieval, it can copy acoustic textures from real recordings, producing outputs with greater fidelity and naturalness.

RECAP: Retrieval-Augmented Audio Captioning

The inverse task, describing audio in natural language, also benefits from retrieval. RECAP [33] retrieves similar audio clips along with their human-written captions and uses both the audio similarity and caption similarity to improve captioning quality.

The model computes a similarity-weighted aggregation of retrieved captions: (Recap)𝒄cap=j=1kexp(𝒆,Ea(aj)/τ)jexp(𝒆,Ea(aj)/τ)Et(captionj), where 𝒆 is the query audio embedding, aj is the j-th retrieved audio clip, captionj is its caption, Et is a text encoder, and τ is a temperature parameter. This aggregated caption embedding conditions the captioning model, providing both semantic guidance (what sounds are present) and stylistic guidance (how to describe them).

Video RAG

Video introduces the temporal dimension to multimodal RAG. Retrieving relevant video clips for question answering requires understanding both the visual content and its temporal evolution. A question like “Show me the moment when the goal was scored” requires retrieving a specific temporal segment from a longer video.

Video RAG systems typically employ a two-stage approach. First, a video is segmented into clips (either by fixed temporal windows or by scene boundary detection). Each clip is encoded into a dense vector by a video encoder (e.g., a Video-Swin Transformer or a CLIP-based model). Second, at query time, the text query is encoded and matched against the clip representations. The retrieved clips condition the generation of the answer, which may be text (video QA), a temporal boundary (moment retrieval), or a summary (video captioning).

Formally, let V=(f1,f2,,fT) be a video of T frames. The video is partitioned into T/w clips of w frames each. Each clip Ci=(f(i1)w+1,,fiw) is encoded as 𝒄i=EV(Ci)d. At query time, the text query 𝒙 is encoded as 𝒒=Eq(𝒙)d, and the top-k clips are retrieved: (Video RAG)𝒞k=top-ki𝒒,𝒄i. The generator then produces the answer conditioned on the query and the retrieved clips: P(𝒚|𝒙,V)=p𝜽(𝒚|𝒙,𝒞k).

Remark 53.

Video RAG faces unique challenges compared to text or image RAG. The index is vastly larger (one hour of video at 30fps produces 108,000 frames), temporal alignment is critical (retrieving the right 3-second clip from a 2-hour video), and the modality gap between text queries and video content is wider than between text queries and text documents. Efficient indexing, hierarchical retrieval (first retrieve the right video, then the right clip, then the right frame), and strong cross-modal encoders are all essential.

Multimodal RAG Architecture

We now present a unified view of multimodal RAG, drawing together the modality-specific systems described above.

Multimodal RAG architecture. A query is routed to modality-specific retrievers that search text, image, audio, and video indices. The retrieved results from all modalities are fused by a multimodal generator that produces the final answer. Each retrieval stream operates in its native modality, avoiding the information loss of cross-modal conversion.
SystemInputOutputRetrievalKey Innovation
RAG [25]TextTextDPREnd-to-end retriever-generator training
RETRO [26]TextTextChunk-levelChunked cross-attention from trillion-token DB
FiD [27]TextTextDPRIndependent passage encoding, joint decoding
Self-RAG [28]TextTextAdaptiveReflection tokens for when-to-retrieve
VDocRAG [29]TextTextVisualRetrieval over rendered document pages
ReSLM [30]SpeechTextSpeech+TextEntity-biased speech recognition
WavRAG [31]AudioTextAudioDirect audio retrieval, no ASR
Re-AudioLDM [32]TextAudioCLAPRetrieval-conditioned audio diffusion
RECAP [33]AudioTextCLAPRetrieval-augmented audio captioning
RAG variants across modalities. Each variant adapts the core RAG paradigm (retrieve then generate) to a specific input/output modality pair, with modality-appropriate encoders and retrieval indices.

Key Idea.

RAG Is a General Paradigm, Not a Text-Only Technique The RAG framework is modality-agnostic in its core design. The three components – a retriever, an index, and a generator – can be instantiated in any modality. What changes across modalities is the encoder (BERT for text, ViT for images, CLAP for audio, Video-Swin for video), the index structure (dense vectors, visual features, audio embeddings), and the generator (BART, diffusion model, speech synthesiser). The underlying principle remains the same: augment the generator's parametric knowledge with retrieved non-parametric information to improve accuracy, reduce hallucination, and enable adaptation to new domains without retraining.

Exercise 58.

Consider designing a RAG system for a museum guide application that must answer visitor questions about artworks using text descriptions, high-resolution images, and audio narrations.

  1. Design the index structure. What representations would you store for each modality? How would you handle cross-modal retrieval (e.g., a text question about a painting)?

  2. A visitor asks: “What technique did Monet use to paint the water in this painting?” Trace the multimodal RAG pipeline, specifying which modalities are retrieved and how they are fused.

  3. Compare the pipeline approach (retrieve in each modality independently, then fuse) with a unified approach (encode all modalities into a shared space, retrieve jointly). What are the trade-offs in terms of index size, retrieval quality, and system complexity?

  4. Extend the RAGAS evaluation framework to this multimodal setting. How would you measure context relevance when the context includes both an image and a text passage?

Exercise 59.

A hospital wants to deploy a speech-enabled RAG system for doctors who dictate patient notes and ask questions about drug interactions.

  1. Explain why the pipeline approach (ASR text RAG) is particularly dangerous in this setting. Give a concrete example of how an ASR error could lead to a harmful outcome.

  2. Design a WavRAG-style system for this application. Specify the audio encoder, the index contents (what audio clips and metadata to store), and the generation model.

  3. The system must handle both English and Spanish speakers. How would you extend the retrieval index to support bilingual queries without maintaining separate indices for each language?

  4. Compute the index size (in GB) for a database of 100,000 drug entities, each represented by a 512-dimensional float32 embedding, plus a 256-dimensional audio embedding. Is this feasible to deploy on a hospital server?

Research 6.

Open Problems in Multimodal RAG Several fundamental challenges remain open in multimodal RAG:

  1. Cross-modal alignment. Current systems use separately trained encoders for each modality. A unified encoder that produces aligned representations across text, image, audio, and video without modality-specific fine-tuning remains elusive.

  2. Temporal retrieval. Retrieving the right moment from a long video or audio recording is far harder than retrieving a text passage. The temporal granularity problem (how long should a retrievable “chunk” be?) has no universal answer.

  3. Evaluation. The RAGAS framework is designed for text. Extending faithfulness and attribution metrics to images (“is this generated description faithful to the retrieved image?”) and audio (“is this caption faithful to the retrieved audio clip?”) requires new evaluation paradigms.

  4. Efficiency. Multimodal indices are orders of magnitude larger than text indices. One hour of video at 1fps produces 3,600 frame embeddings; a million hours produces 3.6 billion embeddings. Efficient indexing and approximate nearest-neighbour methods tailored to multimodal data are needed.

Memory-Augmented Retrieval

Every time you chat with a large language model, something remarkable happens: the model produces fluent, contextually appropriate responses that give the impression of understanding and recall. Yet the moment the context window ends, every detail of your conversation vanishes. The model does not remember your name, your preferences, or the intricate problem you spent forty minutes explaining. It wakes up, tabula rasa, with every new session.

This is not merely an engineering inconvenience. It is a fundamental limitation that separates current language models from anything resembling genuine intelligence. The solution is memory, and the central thesis of this section is that memory is retrieval. The two concepts are not merely analogous; they are computationally identical, differing only in the time scale over which information is stored and recalled.

The Memory-Retrieval Equivalence

The cognitive science of memory, from Tulving's seminal distinction between episodic and semantic memory [36] to Squire's taxonomy of memory systems [41], reveals a striking correspondence with the architecture of modern retrieval systems. Consider the three fundamental operations that any memory system must support:

  1. Encoding. A new experience must be transformed into an internal representation suitable for storage. In the brain, this involves hippocampal pattern separation and the formation of engrams [34][35]. In a retrieval system, this is indexing: a document is embedded into a vector space and stored in an index.

  2. Storage. The encoded representation must persist over time. Biological memory achieves this through synaptic consolidation, transferring fragile hippocampal traces into stable neocortical representations. A retrieval system achieves this through persistent vector databases, inverted indices, or key-value stores.

  3. Retrieval. Given a cue (a thought, a sensation, a question), the system must recover the stored representation. In the brain, this is pattern completion: a partial cue activates the full memory trace. In a retrieval system, this is a query: the cue is embedded and the nearest neighbours in the index are returned.

Definition 60 (Memory-Augmented Retrieval System).

A memory-augmented retrieval system is a tuple =(,𝒮,,𝒟) where:

  • :𝒳d is an encoder that maps raw inputs (conversation turns, documents, experiences) to d-dimensional embeddings,

  • 𝒮={(𝒛i,mi,ti)}i=1N is a memory store consisting of embedding-content-timestamp triples, where 𝒛i=(mi)d, mi is the raw content, and ti is the time of encoding,

  • :d×𝒮𝒮k is a retrieval function that, given a query embedding and the memory store, returns the top-k most relevant memories,

  • 𝒟:𝒮𝒮 is a decay function that periodically prunes or down-weights memories according to a forgetting policy.

The mapping between biological memory and retrieval is not merely metaphorical. It is structural: each component of Definition 60 has a direct neural counterpart.

Key Idea.

Memory is retrieval. They are the same computational problem operating at different time scales. Storing a memory is indexing a document. Recalling a memory is executing a retrieval query. Forgetting is index pruning with temporal decay. Once you see this equivalence, every advance in retrieval technology becomes an advance in artificial memory, and vice versa.

To make the equivalence precise, we define a relevance scoring function that combines the factors governing both biological recall and computational retrieval.

Definition 61 (Memory Relevance Score).

Given a query embedding 𝒒d, a memory (𝒛i,mi,ti)𝒮, and the current time t, the memory relevance score is (Relevance)rel(𝒒,𝒛i,ti;t)=sim(𝒒,𝒛i)semantic similarityω(mi)importanceexp(λ(tti))recency decay, where sim(,) is a similarity function (e.g., cosine similarity), ω:𝒳>0 assigns an importance weight to each memory, and λ>0 controls the rate of temporal decay.

This three-factor model captures a fundamental insight from psychology: we recall memories that are relevant to the current context (semantic similarity), that were important when they were formed (importance weighting), and that are recent (recency bias), unless their importance is sufficiently high to overcome the decay.

Example 47 (The Birthday Effect).

Consider a personal AI assistant that has been running for a year. A friend mentioned their birthday in passing eleven months ago (tti=11 months). With the decay parameter λ=0.1 per month, the recency factor is e0.1×110.33. If the importance weight is low (ω=1), the memory will be difficult to retrieve. But if the assistant correctly classified the birthday as high-importance (ω=10), the effective score is 0.33×10=3.3, which may exceed the scores of more recent but less important memories. This mirrors human memory: you remember important events from long ago while forgetting trivial events from yesterday.

Remark 54.

The exponential decay in (Relevance) is motivated by Ebbinghaus's forgetting curve, one of the oldest quantitative laws in psychology. Ebbinghaus showed that retention decreases approximately exponentially with time, a finding that has been replicated thousands of times across different memory tasks and populations. The importance-weighted variant in our model corresponds to the well-documented effect of emotional salience on memory consolidation: emotionally significant memories are encoded more strongly and decay more slowly.

The Context Window Problem

The context window of a transformer-based language model is the maximum number of tokens it can attend to simultaneously. For GPT-4, this is 128K tokens. For Claude, it ranges up to 200K tokens. For Gemini 1.5 Pro, it is an impressive 1M tokens. These numbers sound large, but they are woefully insufficient for many real-world applications.

Consider a software engineer who wants an AI assistant to understand their entire codebase. A medium-sized project might contain 500,000 lines of code, or roughly 10 million tokens. Even Gemini's 1M-token context window can hold only 10% of this codebase. A lawyer reviewing discovery documents for a complex case may face millions of pages. A doctor's complete medical history may span decades of records. In every case, the context window is a bottleneck.

The fundamental issue is computational. Self-attention in a standard transformer has O(n2) complexity in the sequence length n. Doubling the context window quadruples the attention cost. Even with efficient attention variants (linear attention, FlashAttention, ring attention), the memory and compute costs of very long contexts remain substantial.

Proposition 30 (Context as Retrieval).

Let 𝒞=(c1,c2,,cT) be a conversation history of T turns, and let L be the context window length of a language model. If T>L, then any strategy for selecting which turns to include in the context window is equivalent to a retrieval problem: given the current query cT and the full history 𝒞, select a subset 𝒞𝒞 with |𝒞|L that maximises the model's performance on the current turn.

Proof.

The proof is essentially definitional, but the formalisation is instructive. Let f𝜽 be the language model with parameters 𝜽 and context window L. The model's output at turn T is f𝜽(𝒞) for some subset 𝒞 of at most L tokens. Let (f𝜽(𝒞),cT+1) be a loss function measuring the quality of the model's output relative to the ideal next response cT+1. The optimal context selection strategy solves (Context OPT)𝒞=arg min𝒞𝒞,|𝒞|L(f𝜽(𝒞),cT+1). This is precisely a retrieval problem: from the corpus 𝒞, select the subset most relevant to the query (the current conversational context) subject to a budget constraint (the window length L).

Three main strategies have emerged for managing context when the conversation history exceeds the window:

Sliding Window.

The simplest approach: keep only the most recent L tokens. This discards all information from earlier in the conversation. Formally, 𝒞=(cTL+1,,cT). The sliding window is cheap and simple but catastrophically forgetful: if the user mentioned a crucial constraint in the first message, it is gone forever once the window slides past it.

Summarisation.

Periodically compress older portions of the conversation into a summary. The context then contains the summary plus the recent turns: 𝒞=(summary(c1,,cTL/2),cTL/2+1,,cT). Summarisation preserves more information than the sliding window, but the compression is lossy. Details are lost, nuances are flattened, and the quality of the summary itself depends on the model that generates it.

Retrieval-Augmented Context.

Store the entire conversation history in a retrieval index. At each turn, embed the current query and retrieve the most relevant past turns. The context becomes 𝒞=(𝒒,𝒮)(cTr+1,,cT), where the last r turns are always included for coherence and the retrieved turns provide relevant long-term context. This is the approach advocated by Definition 60: the conversation history is the corpus, each turn is a document, and the current query drives retrieval.

Example 48 (Comparing Context Strategies).

Suppose a user has a 200-turn conversation with a coding assistant (context window L=50 turns). In turn 5, the user specified: “All functions must return typed dictionaries, never raw tuples.” In turn 195, the user asks: “Write a function to parse the config file.”

Sliding window: The context contains turns 151–200. Turn 5 is lost. The assistant may return raw tuples.

Summarisation: If the summariser was good, the summary mentions the typing constraint. If not, it is lost.

Retrieval-augmented: When the query “Write a function to parse the config file” is embedded, the retrieval system can surface turn 5 because “typed dictionaries” and “function” have high semantic relevance to code-writing queries. The constraint is preserved.

Three strategies for managing context when the conversation exceeds the context window. (a) The sliding window discards old turns entirely. (b) Summarisation compresses old turns into a lossy summary. (c) Retrieval-augmented context stores all turns in a vector index and retrieves the most relevant ones, preserving important details regardless of their age.

Memory-Augmented Architectures

The retrieval-augmented context strategy described above operates outside the model: the retrieval system selects context, and the model processes it as if it were ordinary input. A more ambitious approach integrates memory directly into the model architecture.

MemoryBank.

The MemoryBank framework [100] equips an LLM with a persistent external memory that is updated after each conversation. After each session, the system: (i) extracts key facts and events from the conversation, (ii) embeds them using the model's own encoder, (iii) stores them in a vector database with importance scores and timestamps, and (iv) applies the Ebbinghaus-inspired forgetting mechanism of (Relevance). At the start of each new session, the system retrieves relevant memories and injects them into the prompt.

Memorising Transformers.

The Memorising Transformer [101] takes a more architectural approach: it adds a kNN-augmented attention layer that can attend to a large external memory of key-value pairs. During training, the model stores key-value pairs from previous batches in a memory bank. During inference, the attention mechanism computes attention scores over both the local context and the external memory: (MEM Transformer)Attn(𝒒,𝐊,𝐕)=softmax(𝒒[𝐊local;𝐊mem]d)[𝐕local;𝐕mem], where [;] denotes concatenation, 𝐊local and 𝐕local are the keys and values from the current context, and 𝐊mem and 𝐕mem are retrieved from the external memory.

Connection to Engram Theory.

The concept of an engram, a physical trace of memory in the brain [34], provides a compelling biological parallel for memory-augmented architectures. In neuroscience, an engram is a specific pattern of neural activation that encodes a memory. Retrieval involves reactivating this pattern, which is precisely what a kNN lookup over stored key-value pairs achieves. For a deeper treatment of memory architectures in neural networks, including their connection to continual learning, we refer the reader to our dedicated memory chapter (24).

Memory-augmented retrieval architecture. Long-term memory (a vector database) stores all past interactions. When a new query arrives, it is embedded and used to retrieve relevant memories into working memory. The retrieved memories are injected into the context window alongside the current query. After the model responds, the new interaction is encoded and stored back into long-term memory. A decay function gradually reduces the retrievability of older, less important memories.

Retrieval for Continual Learning

The connection between memory and retrieval extends beyond conversation management to one of the deepest problems in machine learning: catastrophic forgetting. When a neural network is trained on a sequence of tasks, learning new tasks tends to overwrite the weights responsible for old tasks, causing performance on earlier tasks to collapse.

Retrieval offers an elegant solution. Rather than relying entirely on the network's parameters to encode all knowledge, we can store experiences (input-output pairs from previous tasks) in an external memory and retrieve them during training on new tasks. This is experience replay, one of the most effective strategies for continual learning (see 26 for a comprehensive treatment).

Proposition 31 (Retrieval Mitigates Catastrophic Forgetting).

Let f𝜽 be a model trained sequentially on tasks 𝒯1,𝒯2,,𝒯K. Let k(𝜽) be the loss on task k. If at each training step on task k>1, we retrieve B examples from a memory buffer containing examples from tasks 1,,k1 and include them in the training batch, then the expected increase in loss on any previous task j<k satisfies (Forgetting Bound)𝔼[j(𝜽k)j(𝜽k1)]CB𝜽k(𝜽)𝜽j(𝜽)2, where C is a constant depending on the learning rate and the curvature of the loss landscape.

The bound reveals two key insights. First, the forgetting rate decreases as 1/B: more retrieved examples means less forgetting. Second, forgetting is worst when the gradients of the new task and the old task are highly conflicting (large gradient difference norm), which is precisely when replay is most needed.

The key design choice in retrieval-based continual learning is which experiences to store and retrieve. Random sampling works surprisingly well, but targeted strategies can do better:

  • Reservoir sampling maintains a uniform sample over all past experiences, regardless of which task they came from.

  • Herding-based selection chooses examples whose embeddings best approximate the mean embedding of each task, preserving the distributional properties of the original data.

  • Retrieval by gradient conflict: store examples whose gradients most conflict with the current task, since these are the ones most at risk of being forgotten.

Vector Embeddings for Memory

The practical implementation of memory-augmented retrieval hinges on the quality of the embeddings used to represent memories. A good memory embedding must satisfy several properties:

  1. Semantic faithfulness. Semantically similar memories should have similar embeddings: sim((mi),(mj)) should correlate with the semantic similarity of mi and mj.

  2. Temporal awareness. The embedding should encode (or be accompanied by) temporal information, enabling recency-based retrieval.

  3. Compositional structure. The embedding space should support operations like analogy (“what was the equivalent of X in context Y?”) and negation (“retrieve memories unlike X”).

  4. Efficient indexing. The embeddings must be compatible with approximate nearest-neighbour data structures for fast retrieval.

In practice, conversation turns are typically embedded using the same encoder used for document retrieval (e.g., a sentence transformer or an API-based embedding model). The temporal component is handled separately, as in (Relevance), by storing timestamps alongside embeddings.

Algorithm 14 (Memory-Augmented Context Management).

Given a language model f𝜽 with context window L, an encoder , a memory store 𝒮, decay rate λ, importance function ω, and a new user query q:

  1. Encode query: 𝒒(q).

  2. Score memories: For each (𝒛i,mi,ti)𝒮, compute sisim(𝒒,𝒛i)ω(mi)exp(λ(tti)).

  3. Retrieve: Select the top-k memories k={m(1),,m(k)} by score, where k is chosen so that the total token count of k plus the recent turns does not exceed L.

  4. Construct context: 𝒞[system prompt;k;recent turns;q].

  5. Generate: rf𝜽(𝒞).

  6. Store new memory: 𝒮𝒮{((q⊕︎r),q⊕︎r,t)}, where ⊕︎ denotes concatenation.

  7. Decay: Periodically remove memories where ω(mi)exp(λ(tti))<ϵ for a threshold ϵ>0.

The memory-retrieval equivalence. Each stage of human memory (sensory input, short-term memory, long-term memory) maps directly to a stage of the retrieval pipeline (raw document, embedding, vector index). Attention corresponds to tokenisation and encoding; consolidation corresponds to indexing; and recall corresponds to retrieval. The dashed vertical arrows marked indicate the functional equivalence between biological and computational memory operations.

Historical Note.

The idea that memory and retrieval are fundamentally linked has deep roots. In 1972, Endel Tulving introduced the encoding specificity principle [36]: a memory can be retrieved only if the retrieval cue matches the conditions under which the memory was encoded. This is precisely the principle underlying embedding-based retrieval: a query retrieves a document only if their embeddings are similar, which happens only if they share semantic content. Tulving could not have known it, but his psychological principle anticipated the mathematical structure of modern vector retrieval by half a century.

Retrieval-Augmented Generation as Memory

With the memory-retrieval equivalence established, we can now view retrieval-augmented generation [25] through a completely new lens. A RAG system is not merely a clever engineering trick for injecting knowledge into a language model. It is a cognitive architecture: the language model is the “thinking” component (analogous to working memory and executive function), and the retrieval system is the “remembering” component (analogous to long-term memory).

Proposition 32 (RAG as Cognitive Architecture).

A RAG system (,f𝜽) consisting of a retrieval system and a language model f𝜽 is functionally equivalent to a memory-augmented cognitive system with:

  1. Sensory buffer: the raw user query q.

  2. Working memory: the context window of f𝜽, holding the query and retrieved documents.

  3. Long-term memory: the retrieval index, containing all indexed documents.

  4. Executive function: the model f𝜽 itself, which integrates information from working memory to produce a response.

  5. Memory consolidation: the indexing pipeline that transforms raw documents into retrievable embeddings.

The system's behaviour is determined by the interaction between these components, just as human cognition arises from the interplay of working memory, long-term memory, and executive control.

This perspective immediately suggests improvements. If RAG is a cognitive architecture, then insights from cognitive science should transfer. For example:

  • Chunking: Cognitive science shows that working memory has limited capacity (the famous “7 ± 2” items of Miller). Similarly, the context window has limited capacity. Just as humans chunk information to fit more into working memory, RAG systems should chunk retrieved documents into semantically coherent units rather than arbitrary token spans.

  • Spaced retrieval: In human memory, spaced repetition strengthens recall. In RAG, retrieving a document multiple times across different queries should increase its importance weight, making it more accessible in the future.

  • Interference: In human memory, similar memories interfere with each other (the fan effect). In retrieval, many similar documents in the index can reduce precision. De-duplication and diversity-promoting retrieval mitigate this.

The RETRO architecture [26] takes this cognitive perspective to its logical conclusion by interleaving retrieval directly into the transformer layers. At every chunk boundary, the model retrieves relevant passages from a massive external database and fuses them into the residual stream via cross-attention. The result is a model that “thinks and remembers” simultaneously, rather than treating retrieval as a separate pre-processing step.

Lemma 11 (Memory Capacity of RAG vs. Parametric Models).

Let f𝜽 be a parametric language model with P parameters stored at b-bit precision, and let be a retrieval system with access to a corpus of N documents, each with entropy H0 bits. The knowledge capacity of the parametric model is at most Pb bits, while the knowledge capacity of the RAG system is at most Pb+NH0 bits. For typical values (P=70×109, b=16, N=109, H0=105), Parametric capacity=70×109×16=1.12×1012 bits140 GB,RAG capacity1.12×1012+1014 bits12.5 TB. The retrieval component increases the effective knowledge capacity by nearly two orders of magnitude.

Exercise 60.

Consider a personal AI assistant with a memory store containing N=10,000 conversation turns spanning one year.

  1. (a)

    If the decay parameter is λ=0.01 per day and the importance weight is uniformly ω=1, what fraction of the oldest memories (from day 1) have a recency factor above 0.01?

  2. (b)

    Propose an importance function ω() that assigns higher weight to memories containing names, dates, and explicit user preferences. How would you implement this in practice?

  3. (c)

    The user says “Remember, I am allergic to penicillin” on day 5. Argue that without a high importance weight, this critical memory might be irretrievable by day 300. Compute the minimum importance weight needed to keep the recency-weighted score above 0.1.

Exercise 61.

Prove that the memory-augmented context management algorithm (Algorithm 14) is optimal in the following sense: among all algorithms that select k memories from 𝒮 based only on the relevance scores rel(𝒒,𝒛i,ti;t), the greedy top-k selection maximises the sum of relevance scores in the retrieved set. Under what conditions might a non-greedy selection (e.g., diversity-promoting) yield better end-to-end generation quality despite a lower total relevance score?

Information-Theoretic Analysis of Retrieval

When you compress a 10,000-word document into a 3,072-dimensional vector embedding, how much information do you lose? And what are the consequences of that loss for retrieval accuracy?

These are not idle questions. Every retrieval system in production today, from Google Search to the RAG pipeline powering your favourite AI assistant, relies on a lossy compression step: documents are mapped to finite-dimensional vectors, and retrieval operates on these compressed representations rather than on the documents themselves. The information lost in this compression imposes a fundamental ceiling on retrieval accuracy, a ceiling that no amount of clever engineering can overcome.

In this section, we develop a rigorous information-theoretic framework for understanding this ceiling. We draw on Shannon's foundational work [4] and the modern theory of rate-distortion [37] to derive precise bounds on what embedding-based retrieval can and cannot achieve.

The Embedding as a Lossy Channel

Consider a document X drawn from a source distribution p(X) over a document space 𝒳. An embedding function :𝒳d maps X to a d-dimensional vector 𝒛=(X)d. From the perspective of information theory, the embedding function defines a channel from documents to embeddings, and the mutual information 𝖨(X;𝒛) quantifies how much information about the document is preserved in the embedding.

The critical observation is that this channel is necessarily lossy: a real-valued vector in d cannot, in general, encode all the information in an arbitrary document. The Data Processing Inequality provides the first constraint.

Theorem 11 (Data Processing Inequality for Retrieval).

Let X be a document, 𝒛=(X) its embedding, and X^=(𝒛) the retrieved document. Then (DPI)𝖨(X;X^)𝖨(X;𝒛)𝖧(X), where 𝖨(;) denotes mutual information and 𝖧() denotes entropy. Moreover, the first inequality is tight if and only if the retrieval function is a sufficient statistic of 𝒛 for X.

Proof.

The documents, embeddings, and retrieved documents form a Markov chain: X𝒛X^. By the Data Processing Inequality [37], for any Markov chain ABC, we have 𝖨(A;C)𝖨(A;B). Applying this with A=X, B=𝒛, C=X^ gives the first inequality. The second follows from 𝖨(X;𝒛)𝖧(X) since mutual information cannot exceed the entropy of either variable. Equality in the first inequality holds if and only if XX^𝒛 is also a Markov chain, which is the condition for X^ being a sufficient statistic.

Remark 55.

Theorem 11 tells us that every step in the retrieval pipeline can only destroy information, never create it. The embedding step loses information about the document. The indexing and approximate nearest-neighbour search lose information about the embedding. The re-ranking step may recover some information by consulting the original documents, but it cannot recover what was lost in the embedding. This is why the embedding quality is the single most important factor in retrieval system design.

Rate-Distortion Theory for Retrieval

Shannon's rate-distortion theory provides a precise framework for understanding the trade-off between compression and fidelity. We now apply it to the retrieval setting.

Let X be a random document and 𝒛 its embedding. Define a distortion function d:𝒳×d0 that measures how much information relevant to retrieval is lost when X is represented by 𝒛. A natural choice is the retrieval distortion: (Distortion)d(X,𝒛)=1Pr[Xtop-k(𝒛,𝒮)], which is 0 if the document is always in the top-k results when relevant and 1 if it is never retrieved.

Definition 62 (Rate-Distortion Function for Retrieval).

The retrieval rate-distortion function is (Ratedistortion)R(D)=minp(𝒛|X):𝔼[d(X,𝒛)]D𝖨(X;𝒛), where the minimisation is over all conditional distributions p(𝒛|X) (i.e., all possible embedding functions, including stochastic ones) such that the expected retrieval distortion does not exceed D.

The rate-distortion function tells us the minimum number of bits of mutual information needed between document and embedding to achieve a given level of retrieval accuracy. If we want distortion at most D, we need at least R(D) bits of information in the embedding.

Theorem 12 (The Embedding Bottleneck).

For a d-dimensional embedding with b-bit precision per dimension (e.g., b=32 for float32), the maximum mutual information between document and embedding is bounded by (Bottleneck)𝖨(X;𝒛)db bits. Consequently, the minimum achievable retrieval distortion is bounded below by (MIN Distortion)DR1(db), where R1 is the inverse of the rate-distortion function.

Proof.

The embedding 𝒛d is represented using d floating-point numbers, each with b bits of precision. The total number of distinct embeddings is at most 2db. By the maximum-entropy principle, a discrete random variable taking at most N values has entropy at most log2N. Therefore 𝖧(𝒛)db bits, and since 𝖨(X;𝒛)𝖧(𝒛), the first bound follows.

For the second bound, observe that achieving distortion D requires 𝖨(X;𝒛)R(D) by the definition of the rate-distortion function. Since 𝖨(X;𝒛)db, we need R(D)db, which gives DR1(db) since R is a non-increasing function.

Example 49 (Capacity of a Modern Embedding).

Consider a state-of-the-art embedding model producing d=3072-dimensional vectors with float32 precision (b=32 bits). The channel capacity is at most 𝖨(X;𝒛)3072×32=98,304 bits12 kilobytes. This is the theoretical maximum information content of the embedding. In practice, the actual mutual information is much lower because:

  1. The embedding dimensions are correlated (reducing effective capacity).

  2. The embedding function is not optimised for maximum mutual information but for contrastive similarity.

  3. The float32 precision is not fully utilised: many embedding values cluster in a small range.

A realistic estimate might be 10–20% of the theoretical maximum, or roughly 10,000–20,000 bits. A typical English document of 5,000 words has an entropy of roughly 50,000–100,000 bits (at approximately 10–20 bits per word after accounting for linguistic redundancy). This means the embedding preserves at most 20–40% of the document's information. The rest is irrecoverably lost.

This is not a failure of any particular embedding model. It is a fundamental limit: you cannot losslessly compress 100,000 bits into 20,000 bits. The question is whether the embedding preserves the right 20%, namely the information most useful for retrieval.

Schematic rate-distortion curve for document retrieval. The solid blue curve shows the minimum bit rate needed to achieve a given retrieval distortion. The dashed orange line marks the theoretical channel capacity of a 3072-dimensional float32 embedding (98,304 bits). The dash-dotted green line marks a realistic effective capacity (15K bits). The intersection with the rate-distortion curve determines the minimum achievable distortion: D0.08 at theoretical capacity, but D0.55 at effective capacity. No embedding-based retrieval system can beat these limits.

Insight.

The rate-distortion perspective reveals a sobering truth about embedding-based retrieval: there is a fundamental accuracy ceiling determined by the embedding dimension and precision. You can improve your embedding model, your training data, your loss function, and your approximate nearest-neighbour algorithm, but you cannot exceed the channel capacity of the embedding. The only way to raise the ceiling is to increase the embedding dimension, increase the precision, or move beyond pure embedding-based retrieval to hybrid approaches that consult the original documents (e.g., through re-ranking or multi-stage retrieval).

Information Loss in Embedding

The bottleneck theorem (Theorem 12) gives a worst-case bound based on the raw capacity of the embedding. We can obtain tighter bounds by reasoning about the structure of the information that embeddings capture and the information they discard.

Proposition 33 (Embedding Capacity Bounds Retrieval Recall).

Let 𝒳 be a corpus of N documents, and let :𝒳d be an embedding function. For a query q with a set of R relevant documents 𝒳q𝒳, define recall@k as recall@k=|top-k(q)𝒳q||𝒳q|. If the embedding has effective mutual information 𝖨(X;𝒛)=Ieff bits, and the documents are drawn i.i.d. from a distribution with entropy 𝖧(X)=H0 bits, then the expected recall@k is bounded by (Recall Bound)𝔼[recall@k]min(1,kR+kN(2Ieff1)).

Proof.

The embedding function partitions the document space into at most 2Ieff effectively distinguishable regions (by the operational meaning of mutual information as the logarithm of the effective alphabet size). Within each region, documents are indistinguishable by the retrieval system. Each region contains, on average, N/2Ieff documents.

For a query with R relevant documents, the top-k retrieval can at best select the k nearest regions and return all documents in them. The expected number of relevant documents retrieved is bounded by the sum of: (i) the relevant documents that fall in distinct regions (at most min(R,2Ieff), weighted by k/R) and (ii) the chance alignment within shared regions. The k/N factor accounts for the random baseline: even without any information, selecting k out of N documents uniformly at random yields kR/N relevant documents in expectation. The multiplicative boost from the embedding is at most 2Ieff, giving the stated bound.

Example 50 (Scaling Limits of Embedding Retrieval).

Consider a corpus of N=109 documents (roughly the scale of the indexed web). Suppose the effective mutual information is Ieff=15,000 bits, and each query has R=10 relevant documents. With k=10:

The bound gives 𝔼[recall@10]min(1,1+10109(2150001))=1, which is vacuous because 215000 is astronomically large. This tells us that for corpora of any practically conceivable size, the embedding capacity is not the binding constraint.

The constraint does bind when the effective information is very low. If Ieff=20 bits (e.g., a very coarse binary hash), then 220106, and each hash bucket contains about 109/106=1000 documents. Recall@10 would be approximately 10/1000=0.01, or 1%. This quantifies the intuition that low-dimensional embeddings cannot support precise retrieval over large corpora.

The more practically relevant bound concerns the quality of information captured by the embedding, not just its quantity.

Theorem 13 (Retrieval Error from Irrelevant Information).

Decompose the document's information content as 𝖧(X)=𝖨(X;𝒛)+𝖧(X|𝒛), where 𝖧(X|𝒛) is the information lost in embedding. Further decompose the mutual information as (INFO Decomposition)𝖨(X;𝒛)=𝖨rel(X;𝒛)+𝖨irr(X;𝒛), where 𝖨rel is the mutual information about features relevant to retrieval (e.g., topic, meaning, intent) and 𝖨irr is mutual information about irrelevant features (e.g., formatting, writing style, document length). Then the effective retrieval capacity is (Effective Capacity)Ieff=𝖨rel(X;𝒛)db𝖨irr(X;𝒛), and the minimum retrieval distortion satisfies (Distortion Irrelevant)DR1(db𝖨irr(X;𝒛)). Every bit of embedding capacity wasted on irrelevant information is a bit unavailable for retrieval accuracy.

Proof.

The decomposition follows from the chain rule for mutual information applied to any partition of the document's features into relevant and irrelevant components. By Theorem 12, 𝖨(X;𝒛)db. Since 𝖨(X;𝒛)=𝖨rel+𝖨irr, we get 𝖨reldb𝖨irr. Substituting into the rate-distortion bound gives DR1(𝖨rel)R1(db𝖨irr).

Remark 56.

Theorem 13 explains why contrastive learning works so well for training embedding models. By training on (query, relevant document) pairs, contrastive losses like InfoNCE encourage the embedding to capture information that predicts relevance while discarding information that does not. In the language of our theorem, contrastive training minimises 𝖨irr while maximising 𝖨rel, thereby pushing the system toward the information-theoretically optimal embedding for retrieval.

The Modality Gap

When a retrieval system maps different modalities (text, images, audio) to a shared embedding space, a new source of information loss emerges: the modality gap. Each modality carries information that is specific to it and cannot be expressed in other modalities. The colour palette of an image, the timbre of a voice, the syntactic structure of a sentence: these modality-specific features are necessarily lost when heterogeneous inputs are projected to a common representation.

Theorem 14 (Cross-Modal Information Loss Bound).

Let X1 and X2 be random variables representing inputs from two different modalities (e.g., text and image), and let 𝒛1=1(X1) and 𝒛2=2(X2) be their embeddings in a shared space d. Suppose X1 and X2 share a common semantic content S (e.g., the concept depicted in an image and described in a caption), with modality-specific components M1 and M2 respectively, so that Xi=(S,Mi). Then the cross-modal retrieval precision is bounded by (Crossmodal Bound)𝖨(X1;𝒛2)𝖨(S;𝒛2)min(𝖧(S),db𝖨(M2;𝒛2)). In particular, cross-modal retrieval cannot exploit any modality-specific information M1 about the query: only the shared semantic content S is useful.

Proof.

Since X1=(S,M1) and 𝒛2=2(X2) where X2=(S,M2), we have the Markov chain M1S𝒛2 (the modality-specific features of X1 influence 𝒛2 only through the shared content S). By the Data Processing Inequality, 𝖨(M1;𝒛2)𝖨(M1;S). But M1 is modality-specific and by definition conditionally independent of S given the encoding structure, so 𝖨(M1;𝒛2) is negligible. Therefore 𝖨(X1;𝒛2)=𝖨(S;𝒛2)+𝖨(M1;𝒛2|S)𝖨(S;𝒛2)+𝖨(M1;S)𝖨(S;𝒛2).

For the upper bound on 𝖨(S;𝒛2): by the chain rule, 𝖨(X2;𝒛2)=𝖨(S;𝒛2)+𝖨(M2;𝒛2|S). Since 𝖨(X2;𝒛2)db and 𝖨(M2;𝒛2|S)𝖨(M2;𝒛2), we obtain 𝖨(S;𝒛2)db𝖨(M2;𝒛2|S)db0=db, but a tighter bound is 𝖨(S;𝒛2)+𝖨(M2;𝒛2)db+𝖨(S;M2;𝒛2)db when S and M2 contribute non-overlapping information to 𝒛2. Combining with 𝖨(S;𝒛2)𝖧(S) gives the stated bound.

The theorem has a clear practical message: if your embedding wastes capacity on modality-specific features (𝖨(M2;𝒛2) is large), then less capacity remains for the shared semantic content that enables cross-modal retrieval. This explains why models like CLIP, which are trained specifically to align image and text representations around shared semantics, dramatically outperform models trained independently on each modality.

Information flow through the retrieval-augmented generation pipeline. At each stage, the Data Processing Inequality guarantees that information about the source document X can only decrease. The inequalities along the bottom show the monotonic information loss from source to final output. Each labelled arrow indicates a mechanism of information loss.

The Information Bottleneck Perspective

The analysis so far has focused on capacity: how much information can an embedding hold? A complementary perspective comes from the Information Bottleneck (IB) method [102], which asks: what is the optimal trade-off between compression and relevance?

In the IB framework, we seek an embedding 𝒛 that maximises the information about the relevance variable Y (e.g., the query) while minimising the information about the input X. Formally, the IB objective is (IB)minp(𝒛|X)𝖨(X;𝒛)β𝖨(𝒛;Y), where β>0 controls the trade-off. As β, the objective favours maximum relevance; as β0, it favours maximum compression.

Definition 63 (Retrieval Information Curve).

The retrieval information curve is the Pareto frontier of achievable (𝖨(X;𝒛),𝖨(𝒛;Y)) pairs over all possible embedding functions. Each point on this curve represents an optimal trade-off between compression (low 𝖨(X;𝒛)) and retrieval utility (high 𝖨(𝒛;Y)). The curve is concave by the properties of mutual information and passes through the origin (zero compression, zero utility) and the point (𝖨(X;Y),𝖨(X;Y)) (full relevance preservation).

The IB perspective provides a principled explanation for why contrastive learning produces good retrieval embeddings. The InfoNCE loss, the standard training objective for modern embedding models, can be shown to be a variational lower bound on 𝖨(𝒛;Y). At the same time, the finite dimensionality of the embedding implicitly constrains 𝖨(X;𝒛). Together, these two forces push the embedding toward the IB-optimal point on the retrieval information curve.

Proposition 34 (Contrastive Learning Approximates the IB Optimum).

Let 𝒛=𝜽(X) be a deterministic embedding function parameterised by 𝜽. The InfoNCE objective with K negative samples satisfies (Infonce IB)InfoNCE𝖨(𝒛;Y)+logK. Minimising this loss thus maximises a lower bound on 𝖨(𝒛;Y). Since a deterministic encoder with d-dimensional output satisfies 𝖨(X;𝒛)db by Theorem 12, the trained embedding approximately solves the IB problem with an implicit compression constraint.

Proof.

The InfoNCE bound is a standard result from representation learning: for a set of one positive pair (X,Y) and K1 negative pairs (X,Yj)j=1K1, the InfoNCE loss is =𝔼[logef(𝒛,𝒚)j=0K1ef(𝒛,𝒚j)], where f is the score function and 𝒚0=𝒚 is the positive. It has been shown that logK𝖨(𝒛;Y) (see Oord et al., 2018), giving the stated bound. The compression constraint follows from the dimensionality argument in Theorem 12.

Example 51 (The IB Trade-off in Practice).

Consider two embedding models for a question-answering retrieval task. Model A uses d=768 dimensions and captures mostly topical information (“this document is about quantum physics”). Model B uses d=3072 dimensions and captures both topical and fine-grained factual information (“this document discusses the spin-statistics theorem in the context of identical particles”).

Model A has low 𝖨(X;𝒛) but also low 𝖨(𝒛;Y): it can find documents on the right topic but struggles to distinguish among them. Model B has higher 𝖨(X;𝒛) and higher 𝖨(𝒛;Y): it can find the specific document that answers the question. Both models lie on the retrieval information curve, but at different points. The choice between them depends on the application: for broad topic search, Model A may suffice; for precise factual retrieval, Model B is needed.

Consequences for RAG

The information-theoretic analysis has direct consequences for retrieval-augmented generation (RAG) systems. When a RAG system retrieves documents to ground a language model's output, errors in retrieval propagate through the generation step and compound.

Proposition 35 (RAG Error Propagation).

Let P be the precision of the retrieval system (the probability that a retrieved document is relevant) and let F be the faithfulness of the generator (the probability that the output correctly reflects the retrieved information, given that the retrieved information is correct). Under conditional independence of retrieval and generation errors, the end-to-end correctness probability is (RAG Error)Ce2e=PF. Under the more realistic assumption that errors are positively correlated (the generator is more likely to hallucinate when given irrelevant context), the bound tightens to (RAG Error Correlated)Ce2ePFρP(1P)F(1F), where ρ0 is the correlation between retrieval errors and generation errors.

Proof.

Under independence, Ce2e=Pr[correct retrieval]Pr[faithful generation|correct retrieval]=PF.

For the correlated case, let R be the event of correct retrieval and G the event of faithful generation. We have Pr[R]=P, Pr[G]=F, and Corr(R,G)=ρ. The joint probability Pr[RG]=𝔼[RG]=𝖢ov(R,G)+𝔼[R]𝔼[G]=ρP(1P)F(1F)+PF. But when errors are positively correlated (ρ>0), the failures of R and G tend to co-occur, meaning the successes also co-occur less than independence would predict. By symmetry, positive correlation between errors (i.e., between R and G) implies negative correlation between successes, giving Ce2e=Pr[RG]PFρP(1P)F(1F).

Example 52 (Error Compounding in Practice).

Suppose a RAG system has retrieval precision P=0.85 and generator faithfulness F=0.90. Under independence, the end-to-end correctness is 0.85×0.90=0.765. Already, roughly one in four answers is wrong.

With a modest error correlation of ρ=0.2, the bound becomes 0.7650.20.85×0.15×0.9×0.10.7650.2×0.1070.744. In practice, the situation is often worse: when retrieval returns irrelevant documents, the generator does not merely ignore them; it incorporates them into its response, producing a confident-sounding but incorrect answer. This is why retrieval precision is so critical in RAG: it is the first line of defence against hallucination.

The embedding bottleneck visualised. Documents with high entropy 𝖧(X) are squeezed through a narrow bottleneck (the embedding function) that can transmit at most db bits of information. The difference 𝖧(X)𝖨(X;𝒛) is lost irrecoverably. No downstream processing can recover this information.

Fundamental Limits and Open Questions

We close this section with a conjecture that captures what we believe to be a deep truth about embedding-based retrieval.

Conjecture 3 (No Fixed-Dimensional Embedding Suffices for a Growing Corpus).

Let d be a fixed embedding dimension and b a fixed precision. Let {𝒳N}N=1 be a sequence of corpora with |𝒳N|=N, where documents are drawn i.i.d. from a source with entropy 𝖧(X)>db. For any embedding function N:𝒳Nd and any retrieval function N, the average retrieval precision satisfies (Growing Corpus)limN𝔼[precision@k]=kN0 unless the embedding function N is allowed to depend on N (i.e., is retrained as the corpus grows) or the embedding dimension d grows with N.

Remark 57.

The conjecture formalises an intuition familiar to practitioners: embedding models trained on small corpora degrade when deployed on much larger ones. The information-theoretic argument is that a fixed-capacity channel cannot distinguish an unbounded number of documents. However, we state this as a conjecture rather than a theorem because the precise conditions under which the degradation occurs depend on the structure of the source distribution. If documents are highly clustered (low effective entropy), a fixed-dimensional embedding may suffice for much longer than the worst-case analysis suggests.

Exercise 62.

Suppose you are designing an embedding for a corpus of N=106 scientific papers, each with an average entropy of 80,000 bits.

  1. (a)

    What is the minimum embedding dimension d needed to achieve a theoretical retrieval distortion of D0.1, assuming float32 precision and that the rate-distortion function behaves as R(D)H0(1D) for this source?

  2. (b)

    If the embedding model wastes 30% of its capacity on stylistic features irrelevant to retrieval, how does the minimum distortion change?

  3. (c)

    Explain in words why increasing the corpus size to N=109 does not necessarily require increasing the embedding dimension, despite Conjecture 3.

Exercise 63.

Prove that for a binary symmetric source with 𝖧(X)=n bits and Hamming distortion, the rate-distortion function is R(D)=n[1𝖧b(D)], where 𝖧b(D)=DlogD(1D)log(1D) is the binary entropy function. Use this to compute the minimum embedding dimension needed to achieve distortion D=0.1 for n=1000.

Exercise 64.

Two embedding models are trained for text-image retrieval. Model A produces embeddings in 512 and uses 40% of its capacity on modality-specific features. Model B produces embeddings in 1024 and uses 25% of its capacity on modality-specific features. Both use float32 precision.

  1. (a)

    Compute the effective cross-modal retrieval capacity of each model using Theorem 14.

  2. (b)

    Which model achieves better cross-modal retrieval? Is it always the one with higher total capacity?

  3. (c)

    Derive a condition on the modality-specificity ratio α=𝖨(M;𝒛)/(db) under which doubling the embedding dimension does not improve cross-modal retrieval.

Exercise 65.

A three-stage RAG pipeline consists of: (1) a query reformulator with accuracy A (probability that the reformulated query preserves the user's intent), (2) a retrieval system with precision P, and (3) a generator with faithfulness F.

  1. (a)

    Derive the end-to-end correctness under the assumption that errors at each stage are independent.

  2. (b)

    Show that the optimal investment strategy (which component to improve first) depends on the current values. Specifically, show that C/A=PF, C/P=AF, and C/F=AP, and use this to determine the priority ordering.

  3. (c)

    If the current system has A=0.9, P=0.7, and F=0.95, which component should be improved first?

Retrieval for Verification and Theorem Proving

Generative models produce outputs that look correct. They are fluent, confident, and well-structured. But looking correct is not the same as being correct. A language model can generate a mathematical proof with every step formatted perfectly, every symbol placed precisely, and a devastating logical gap in the middle that would take an expert minutes to find. It can generate a clinical summary that reads like a textbook but contains a drug interaction that could harm a patient. It can produce a legal brief that cites cases with perfect formatting, where half the cases do not exist.

The verification problem, how to check whether a generated output is actually correct, is one of the central challenges of modern AI. In this section, we show how retrieval provides a powerful tool for verification: by retrieving known facts, established theorems, and documented evidence, we can check the consistency of generated outputs against a trusted knowledge base.

This is not the same as retrieval-augmented generation. In RAG, retrieval happens before generation to provide context. In retrieval-based verification, retrieval happens after generation to check the result. The distinction is illustrated in fig:ret:verification-pipeline.

Retrieval-based verification pipeline. Unlike RAG, where retrieval precedes generation, verification retrieves evidence after generation to check the output. The generated output is decomposed into individual claims, evidence is retrieved from a knowledge base, and each claim is checked for entailment or contradiction.

Retrieval for Formal Mathematics

Mathematical theorem proving is an ideal testbed for retrieval-based verification because it has an unambiguous standard of correctness: a proof is either valid or it is not, as determined by a formal proof checker. There is no room for subjective interpretation or partial credit.

Modern proof assistants such as Lean [97], Coq, and Isabelle maintain large libraries of formalised mathematics: thousands of definitions, lemmas, and theorems that have been machine-verified. When a generative model attempts to construct a proof, it needs access to these libraries, and finding the right lemma is a retrieval problem.

Example 53 (Lemma Retrieval in Lean).

Suppose a language model is attempting to prove that the sum of two even numbers is even. In Lean 4, the proof requires finding and applying the lemma Even.add from the Mathlib library. The library contains over 100,000 declarations. The retrieval problem is: given the current proof state (goal: Even(m+n), hypotheses: Even(m), Even(n)), find the most relevant lemma from the library.

A naive keyword search for “even add” might return dozens of results. But embedding-based retrieval can do better: by encoding both the proof state and the lemma statements as vectors, the system can identify lemmas whose type signatures match the current goal, not just lemmas that share keywords.

The AlphaProof system [98] demonstrated the power of combining retrieval with formal verification at the 2024 International Mathematical Olympiad. AlphaProof's architecture integrates three components:

  1. A generative model that proposes proof steps, trained on a large corpus of mathematical text.

  2. A retrieval system that finds relevant lemmas, definitions, and previously proved results from a formalised library.

  3. A formal verifier (Lean) that checks each proof step for correctness, providing an absolute ground truth.

The key insight is that the verifier provides a reward signal for the generative model: correct proof steps receive positive reward, incorrect steps receive negative reward. This enables reinforcement learning over the space of proofs, with retrieval providing the “knowledge base” of available mathematical facts.

Theorem proving augmented with retrieval. The proof tree (blue/green nodes) is constructed by the generative model. At each node, the system retrieves relevant lemmas (amber nodes) from the formalised library (teal). The formal verifier (red) checks each step for correctness. Retrieval narrows the search space by surfacing the most relevant lemmas for the current proof state.

Algorithm 15 (Retrieval-Augmented Proof Search).

Given a proof goal G, a formalised library of lemmas, an embedding function , a generative model f𝜽, and a formal verifier 𝒱:

  1. Embed the goal: 𝒒(G).

  2. Retrieve candidate lemmas: 𝒞top-k(𝒒,{():}).

  3. Generate proof candidates: For each 𝒞, use f𝜽 to generate a proof step s that applies to G.

  4. Verify: For each candidate step s, run 𝒱(G,s). If the verifier accepts, add s to the proof and recurse on any remaining subgoals.

  5. Backtrack: If no candidate step is accepted, backtrack and try a different branch of the proof tree.

  6. Terminate: Return the proof if all subgoals are discharged; otherwise report failure.

Remark 58.

The retrieval step (Step 2) is crucial for efficiency. Without it, the generative model must search the entire library of 100,000+ lemmas at each proof step, which is combinatorially intractable. By narrowing the search to the k most relevant lemmas (typically k=1050), retrieval reduces the branching factor of the proof search from O(||) to O(k), making the problem tractable.

Proposition 36 (Retrieval Reduces Proof Search Complexity).

Let be a library of L lemmas, n the number of steps in a proof, and k the number of retrieved candidates per step. Without retrieval, the proof search tree has branching factor L and the number of candidate proofs is Ln. With retrieval (assuming the correct lemma is always in the top-k), the branching factor reduces to k, giving kn candidates. The speedup factor is (Proof Speedup)Lnkn=(Lk)n. For L=100,000, k=20, and n=10, this is (5000)101037: retrieval makes an otherwise impossible search tractable.

Proof.

At each of n proof steps, the model considers L possible lemmas without retrieval or k with retrieval. The total number of paths through the proof tree is the product of branching factors across all levels: Ln versus kn. The ratio follows immediately. The assumption that the correct lemma is always retrieved (recall = 1) is optimistic; in practice, the speedup is achieved at the cost of some probability of missing the correct proof path.

Lemma 12 (Retrieval Recall and Proof Success).

If the retrieval system has per-step recall r (the probability that the needed lemma is in the top-k), and the proof requires n independent retrieval steps, then the probability of successfully constructing the complete proof is (Proof Success)Pproofrn. For r=0.95 and n=10, this gives Pproof0.95100.60. For n=20, it drops to 0.95200.36. This exponential decay in proof success probability with proof length is a fundamental challenge for retrieval-augmented theorem proving.

Proof.

Each retrieval step succeeds independently with probability r. The proof succeeds only if all n steps succeed, giving Pproof=rn under independence. The inequality accounts for the possibility that retrieval steps may be positively correlated (the same lemma might be needed multiple times), which can only reduce the success probability below the independent case.

Fact-Checking with Retrieval

Formal mathematics provides an unambiguous verification signal, but most real-world verification tasks are messier. When a language model generates a claim about history, medicine, or current events, there is no Lean-like verifier to consult. Instead, we must rely on evidence: documents from trusted sources that either support or contradict the claim.

The retrieval-based fact-checking pipeline consists of three stages:

Stage 1: Claim Decomposition.

Complex statements are broken into atomic, verifiable claims. For example, the statement “Einstein won the Nobel Prize in 1922 for his work on general relativity” decomposes into: (a) Einstein won the Nobel Prize, (b) the year was 1922, and (c) the prize was for general relativity. (Claims (a) and (b) are approximately correct; claim (c) is false: the prize was for the photoelectric effect.)

Stage 2: Evidence Retrieval.

For each atomic claim, retrieve the most relevant documents from a knowledge base. The quality of this retrieval step is the primary determinant of the system's accuracy. If the relevant evidence is not retrieved, the claim cannot be verified.

Stage 3: Entailment Checking.

For each (claim, evidence) pair, determine whether the evidence supports, refutes, or is neutral with respect to the claim. This is a natural language inference (NLI) task, and modern NLI models achieve high accuracy when given the right evidence.

Algorithm 16 (Retrieval-Based Fact Verification).

Given a generated text T, a knowledge base 𝒦, a claim decomposition model 𝒟, a retrieval system , and an NLI model 𝒩:

  1. Decompose: {c1,,cm}𝒟(T).

  2. For each claim ci: enumerate

  3. Retrieve evidence: Ei(ci,𝒦) (top-k documents).

  4. Check entailment: For each eEi, compute 𝒩(ci,e){sᴜᴘᴘᴏʀᴛ,ʀᴇꜰᴜᴛᴇ,ɴᴇᴜᴛʀᴀʟ}.

  5. Aggregate: vimajority({𝒩(ci,e):eEi}). enumerate

  6. Compile verdict: Return {(ci,vi)}i=1m and an overall score S=1mi=1m𝟏[vi=sᴜᴘᴘᴏʀᴛ].

Example 54 (Citation Verification).

A particularly insidious form of AI hallucination is false citation: the model generates a reference that does not exist, or cites a real paper that does not actually support the claim. Retrieval-based verification can detect both cases:

  • Non-existent citations: Retrieve papers by the cited authors and title. If no match is found in the knowledge base (e.g., Semantic Scholar, PubMed, arXiv), flag the citation as potentially fabricated.

  • Misattributed claims: If the paper exists, retrieve its abstract and full text. Check whether the cited paper actually contains or supports the claim attributed to it using the NLI model. Self-RAG [28] provides a framework for this kind of reflective verification.

Scientific Verification

The verification challenge becomes particularly acute in scientific contexts, where claims are complex, evidence is nuanced, and the consequences of error are severe.

Drug Interaction Checking.

A language model summarising a patient's chart might suggest a medication without checking for interactions with the patient's existing prescriptions. Retrieval-based verification can cross-reference the suggested medication against a drug interaction database (e.g., DrugBank), flagging potential conflicts before the recommendation reaches a clinician.

Experimental Reproducibility.

When a model generates a description of a scientific experiment, retrieval can surface similar experiments from the literature, enabling comparison of methods, sample sizes, and reported effects. Discrepancies between the generated description and the retrieved literature may indicate errors or hallucinations.

Consistency with Physical Laws.

For scientific claims involving quantitative predictions (e.g., “the boiling point of this compound is 450K”), retrieval can surface known data points for similar compounds, enabling a sanity check. If the predicted value falls far outside the range of known values, it warrants scrutiny.

Information-Theoretic Limits on Verification

Can a retrieval-based verification system catch all errors? The answer, perhaps unsurprisingly, is no. There are fundamental limits on what verification can achieve, and understanding these limits is essential for deploying verification systems responsibly.

Theorem 15 (Coverage Bound on Verification).

Let 𝒦 be a knowledge base with coverage γ[0,1], defined as the probability that a randomly drawn true claim has supporting evidence in 𝒦. Let be a retrieval system with recall r[0,1] (the probability of retrieving relevant evidence when it exists), and let 𝒩 be an NLI model with accuracy a[0.5,1]. Then the probability that the verification system correctly classifies a claim is bounded by (Verification Bound)Pcorrectγra+(1γ)(1a). In particular, if the knowledge base has coverage γ=0.8, retrieval recall is r=0.9, and NLI accuracy is a=0.95, then Pcorrect0.8×0.9×0.95+0.2×0.05=0.684+0.01=0.694.

Proof.

Consider two cases. If the relevant evidence exists in 𝒦 (probability γ), the retrieval system must find it (probability r), and the NLI model must correctly classify the claim-evidence pair (probability a). The probability of correct classification in this case is γra.

If the relevant evidence does not exist in 𝒦 (probability 1γ), the system retrieves irrelevant evidence. The NLI model, faced with irrelevant evidence, should ideally output “neutral,” but with accuracy a it may misclassify. In the best case, the system correctly abstains (classifies as neutral/unverifiable) with probability that cannot exceed 1a for the correct-on-irrelevant case (since the model has error rate 1a). More precisely, when the evidence is irrelevant, the system's classification reduces to chance behaviour, and the probability of the “correct” verdict (which is “neutral”) is at most 1a in the adversarial case. Combining the two cases gives the stated bound.

Caution.

Verification is only as good as the knowledge base. If the knowledge base is incomplete (low γ), the verification system will fail to catch errors on topics it does not cover. If the knowledge base contains errors, the verification system will endorse incorrect claims. This is the “garbage in, garbage out” principle applied to verification: a fact-checker that verifies claims against a flawed knowledge base is worse than useless, because it gives a false sense of security.

Before deploying a retrieval-based verification system, always assess the coverage, currency, and accuracy of the underlying knowledge base. Domains where knowledge changes rapidly (medicine, law, current events) require continuous knowledge base updates. A verification system with a stale knowledge base will systematically reject true claims about recent developments and accept outdated claims that are no longer true.

Remark 59.

The bound in Theorem 15 is necessarily loose because it does not account for the structure of errors. In practice, errors are not uniformly distributed: generative models tend to hallucinate in predictable ways (e.g., confusing similar entities, generating plausible-sounding but fictional citations). A retrieval system tuned to the error distribution of a specific generator can achieve higher verification accuracy than the worst-case bound suggests. This connection between the error profile of the generator and the design of the verification system is an active area of research.

Self-Verification and Reflexive Retrieval

A recent line of work explores self-verification: the model retrieves evidence and checks its own output without external intervention. Self-RAG [28] introduces special tokens that allow the model to decide when to retrieve, what to retrieve, and whether the retrieved evidence supports the generated output.

The formal framework is elegant. At each generation step, the model outputs one of three reflection tokens:

  1. [Retrieve]: indicates the model's confidence is low and evidence should be retrieved before continuing.

  2. [IsRel]: after retrieval, evaluates whether the retrieved passage is relevant to the query.

  3. [IsSup]: evaluates whether the retrieved passage supports the generated text.

This transforms the model from a passive consumer of retrieved context into an active participant in the retrieval-verification loop. The model learns, through training, when its own knowledge is insufficient and external evidence is needed.

Proposition 37 (Self-Verification Improves with Retrieval Quality).

Let f𝜽 be a self-verifying model with precision pself on its own verification judgements (probability of correctly identifying a supported/unsupported claim). If the underlying retrieval system has precision P and the model's self-verification accuracy improves monotonically with the relevance of retrieved evidence, then the effective self-verification precision satisfies (SELF Verify)peff=pselfP+pbase(1P), where pbase<pself is the model's verification precision when given irrelevant evidence.

Proof.

With probability P, the retrieved evidence is relevant, and the model achieves self-verification precision pself. With probability 1P, the evidence is irrelevant, and the model falls back to its base verification ability pbase. The law of total probability gives the stated result.

The proposition reinforces a theme that runs through this entire chapter: the quality of retrieval is the foundation upon which everything else is built. Better retrieval improves RAG, improves memory, improves verification, and improves self-monitoring.

Retrieval as a Bridge Between Neural and Symbolic AI

Retrieval-based verification occupies a unique position at the intersection of neural and symbolic AI. The generative model is neural: it produces outputs through pattern matching over learned representations. The verifier, in the case of formal mathematics, is symbolic: it checks proofs through logical deduction. Retrieval is the bridge between these two paradigms, selecting from a symbolic knowledge base the facts that the neural model needs to ground its output.

This bridge architecture, neural generation + retrieval + symbolic verification, may represent a more robust paradigm for building trustworthy AI systems than either pure neural or pure symbolic approaches alone. The neural component provides flexibility and natural language understanding. The symbolic component provides guarantees and precision. And retrieval provides the interface between them.

Insight.

The deepest lesson of this section is that verification is harder than generation. A model can generate a plausible-sounding mathematical proof in seconds; verifying it may take hours. A model can generate a medical recommendation in milliseconds; checking it against the literature and the patient's history may require careful expert review. This asymmetry, the ease of generation versus the difficulty of verification, is why retrieval for verification is so important: it automates the most labour- intensive step in the quality assurance pipeline.

In formal mathematics, the verification step is decidable and can be fully automated. In natural language domains, it remains an approximation. Closing this gap, building verification systems for natural language claims that approach the rigour of formal proof checkers, is one of the grand challenges of AI safety.

Exercise 66.

Consider a RAG system that generates research paper summaries and a verification system that checks them. The knowledge base covers 80% of the topics in the target domain, the retrieval system has recall@10 of 0.7, and the NLI model has accuracy 0.88.

  1. (a)

    Using Theorem 15, compute the upper bound on the verification system's accuracy.

  2. (b)

    Which component (coverage, recall, or NLI accuracy) would yield the largest improvement if increased by 10%? Justify your answer mathematically.

  3. (c)

    The system administrator proposes adding Wikipedia as a secondary knowledge base. Discuss the trade-offs: how might this affect coverage, precision, and the risk of verifying against incorrect information?

Exercise 67.

Prove that in the retrieval-augmented proof search algorithm (Algorithm 15), if the retrieval system has recall r (probability that the needed lemma is in the top-k) and the proof has n steps, then the probability of successfully constructing the proof is at most rn. Under what conditions is this bound tight?

Exercise 68.

Consider a self-verifying RAG system where the model generates an answer, retrieves evidence, and then decides whether to keep or revise its answer.

  1. (a)

    Model this as a two-stage decision process. Let p1 be the probability of a correct initial answer and p2 the probability that the self-verification step correctly identifies and fixes an error. Show that the end-to-end accuracy is p1+(1p1)p2q, where q is the probability that the revised answer is correct.

  2. (b)

    Under what conditions does self-verification decrease overall accuracy? (Hint: consider the case where the model “corrects” a correct answer based on misleading retrieved evidence.)

  3. (c)

    Propose a strategy for setting the confidence threshold at which the model decides to retrieve and verify versus trust its initial answer. How does this relate to the precision/recall trade-off in the underlying retrieval system?

Exercise 69.

A multimodal AI system generates a caption for a medical image. Design a retrieval-based verification pipeline that:

  1. (a)

    Retrieves similar medical images from a verified database and compares their captions to the generated one.

  2. (b)

    Retrieves relevant medical literature to verify clinical claims in the caption.

  3. (c)

    Formally analyse the failure modes: when would this pipeline fail to catch a dangerous error? Use Theorem 15 to quantify the risk.

Historical Note.

The connection between retrieval and verification has ancient roots. The great libraries of antiquity, from Alexandria to Baghdad, served not only as repositories of knowledge but as verification engines: a scholar could check a claim by retrieving the relevant scrolls and comparing. The modern retrieval system, for all its sophistication, performs fundamentally the same function. What has changed is the scale (billions of documents rather than thousands of scrolls), the speed (milliseconds rather than hours of search), and the automation of the final comparison step through natural language inference models. But the core principle, that claims must be checked against documented evidence, is as old as scholarship itself.

Recommendation as Retrieval

Netflix, Spotify, Amazon – recommendation is arguably the most economically impactful retrieval problem in existence. When a user opens a streaming service, the platform must retrieve a handful of relevant items from a catalogue containing millions of movies, songs, or products. Every recommendation is, at its core, a retrieval operation: given the user as a query, find the items most likely to satisfy their needs. The economic stakes are enormous. Netflix has estimated that its recommendation system is worth over one billion dollars per year in retained subscriptions [103]. Amazon attributes roughly 35% of its revenue to recommendations. Spotify's Discover Weekly playlist, a pure retrieval product, reaches over 100 million users.

This section develops the formal connection between recommendation and retrieval, traces the evolution from classical collaborative filtering to modern generative recommendation, and examines how large language models are reshaping the field. Along the way, we will see that the same mathematical abstractions – embeddings, similarity functions, approximate nearest neighbours – appear in both domains, and that advances in one have consistently accelerated the other.

The Recommendation-Retrieval Connection

The architecture of every modern recommendation system reveals the retrieval machinery underneath. The standard two-stage pipeline consists of candidate generation followed by reranking, and these stages map directly to the retrieval-then-rank paradigm that pervades information retrieval.

Candidate generation IS retrieval.

From a catalogue 𝒞 of millions of items, the candidate generation stage selects a manageable set of a few hundred candidates. This is precisely the retrieval problem: given a query (the user context), find the top-k relevant documents (items) from a large corpus. The user context 𝒒d encodes everything the system knows about the user – their history, demographics, current session – and each item 𝒅jd lives in the same embedding space. Candidate generation reduces to approximate nearest-neighbour search: (Candidate Generation)𝒞k(𝒒)=arg max𝒮𝒞,|𝒮|=kj𝒮s(𝒒,𝒅j), where s(,) is a scoring function, typically the inner product or cosine similarity.

Reranking IS ranking.

The reranking stage takes the k candidates and produces a final ordering based on richer, more expensive features. This is the learning-to-rank problem that we develop in detail in Learning to Rank. The reranker may use cross-attention between user and item features, incorporate real-time signals (time of day, device type, recently clicked items), and optimize for business-specific objectives beyond pure relevance – diversity, freshness, revenue.

Definition 64 (Recommendation as Retrieval).

A recommendation system is a retrieval system (𝒬,𝒞,s,k) where:

  1. 𝒬 is the space of user contexts (queries), with each 𝒒𝒬 encoding user identity, history, and session state.

  2. 𝒞={𝒅1,,𝒅N} is the item catalogue (corpus), with N typically in the range 106109.

  3. s:𝒬×𝒞 is the relevance scoring function, decomposed as s=sranksretrieve, where sretrieve is fast (sub-linear in N) and srank is expressive (linear in k).

  4. kN is the number of items presented to the user.

Key Idea.

Recommendation and retrieval share identical computational constraints. Both must serve results in under 100 milliseconds. Both face catalogues too large for exhaustive scoring. Both decompose into a fast, approximate first stage and a slower, precise second stage. Advances in one field transfer directly to the other: approximate nearest-neighbour indices (HNSW, IVF, product quantization) power both web search and recommendation at scale.

Collaborative Filtering as Embedding Retrieval

The oldest and most influential approach to recommendation is collaborative filtering: predict a user's preferences from the collective behaviour of all users. The key insight, formalized by matrix factorization, is that collaborative filtering is embedding-based retrieval.

Matrix factorization.

Let 𝐑M×N be the (sparse) user-item interaction matrix, where Rui records user u's rating (or implicit feedback) for item i. Matrix factorization seeks low-rank embeddings 𝒒ud for each user and 𝒅id for each item such that (Matrix Factorization)Rui𝒒u,𝒅i+bu+bi+μ, where bu, bi are user and item biases and μ is the global mean. The training objective minimizes the regularized squared error over observed entries: (MF Objective)min{𝒒u},{𝒅i},{bu},{bi}(u,i)𝒪(Rui𝒒u,𝒅ibubiμ)2+λ(𝒒u2+𝒅i2+bu2+bi2), where 𝒪 is the set of observed interactions. Once trained, recommendation reduces to retrieving the items with the highest inner products 𝒒u,𝒅i – a standard maximum inner product search (MIPS) problem that can be solved with the same ANN indices used in dense retrieval.

Neural collaborative filtering.

The linearity of the inner product in (Matrix Factorization) limits the expressiveness of matrix factorization. Neural collaborative filtering (NCF) replaces the inner product with a learned scoring function: (NCF)R^ui=f𝜽(𝒒u,𝒅i), where f𝜽 is a multilayer perceptron. While more expressive, this approach sacrifices the decomposability that enables efficient retrieval: scoring each user-item pair requires a forward pass through f𝜽, making exhaustive scoring over millions of items prohibitive at serving time.

Two-tower models.

The two-tower architecture resolves the tension between expressiveness and efficiency. It computes user and item embeddings through separate deep networks (towers) and scores by inner product: (TWO Tower)s(u,i)=g𝜽(u),h𝝓(i), where g𝜽:𝒰d is the user tower and h𝝓:d is the item tower. Each tower can be arbitrarily deep (incorporating transformer layers, attention over the user's history, etc.), yet the final scoring remains a simple inner product. This means item embeddings h𝝓(i) can be precomputed and indexed offline, reducing serving to a single forward pass through the user tower followed by an ANN lookup.

Example 55 (YouTube Deep Candidate Generation).

YouTube's candidate generation system is a two-tower model where the user tower ingests watch history (as a bag of video embeddings), search history, demographic features, and the “example age” (time since upload). The item tower produces embeddings for each video. At serving time, the system retrieves the top few hundred candidates via approximate nearest neighbours from a corpus of billions of videos, achieving sub-50 millisecond latency. The two-tower architecture enables daily re-indexing of the item corpus as new videos are uploaded.

Theorem 16 (Generalization Bound for Two-Tower Recommendation).

Let g𝜽:𝒰d and h𝝓:d be user and item towers with Lipschitz constants Lg and Lh respectively, and let the embeddings be bounded: g𝜽(u)Bu and h𝝓(i)Bi for all u,i. Given n training interactions drawn i.i.d. from a distribution 𝒟 over user-item pairs, the expected risk R of the two-tower model satisfies (TWO Tower GEN Bound)R(g𝜽,h𝝓)R^n(g𝜽,h𝝓)+BuBi2(dlog(LgLhn)+log(2/δ))n with probability at least 1δ, where R^n is the empirical risk on the training set.

Proof sketch.

The hypothesis class of inner-product scores g𝜽(u),h𝝓(i) has Rademacher complexity bounded by BuBid/n when the towers are Lipschitz. The bound follows from standard Rademacher complexity-based generalization results, with the log(LgLhn) term arising from covering number arguments over the Lipschitz function classes.

The generalization bound reveals two important insights. First, the embedding dimension d appears under the square root, suggesting that moderate dimensions (d=64256) suffice for generalization even with large catalogues. Second, the product BuBi controls the effective capacity: regularizing embedding norms (a standard practice) directly tightens the generalization bound.

Remark 60 (Negative Sampling in Two-Tower Training).

Training two-tower models requires negative examples: items the user did not interact with. The choice of negatives profoundly affects the learned embeddings. Random negatives (uniformly sampled from the catalogue) are easy to distinguish and produce embeddings that capture only coarse preferences. Hard negatives (items similar to positive items but not interacted with) force the model to learn fine-grained distinctions. In practice, a curriculum that starts with random negatives and progressively introduces harder negatives – mirroring the training strategy of dense retrieval models – produces the best recommendation quality.

Content-Based Recommendation

Collaborative filtering relies entirely on interaction patterns and fails when those patterns are sparse or absent. Content-based recommendation addresses this by deriving item representations from the items themselves – their text descriptions, images, audio, or metadata.

Item embeddings from content features.

Given an item i with associated content ci (a product description, an image, an audio clip), a content encoder ϕ:𝒳d produces the item embedding 𝒅i=ϕ(ci). The encoder ϕ may be a pretrained language model (BERT, sentence transformers), a vision encoder (CLIP, ViT), or a domain-specific model. The user embedding 𝒒u is then computed as an aggregation of the content embeddings of items the user has interacted with: (Content USER Embedding)𝒒u=1|u|iuαuiϕ(ci), where u is the user's interaction history and αui are attention weights reflecting the recency and relevance of each interaction.

Cross-modal recommendation.

Modern e-commerce items are inherently multimodal: a product has a title (text), images (vision), specifications (structured data), and sometimes video or audio. A winter jacket's appeal depends on its visual design (captured by images), its technical specifications (captured by structured metadata), and user reviews (captured by text). No single modality tells the full story. Cross-modal recommendation fuses these modalities into a unified item embedding. The typical approach uses modality-specific encoders followed by a fusion layer: (Cross Modal)𝒅i=Fuse(ϕtext(citext),ϕimage(ciimage),ϕmeta(cimeta)), where the fusion may be concatenation followed by a projection, cross-attention, or a mixture-of-experts gating mechanism. The quality of the content encoders is critical: systems that use CLIP for vision and a fine-tuned sentence transformer for text consistently outperform those with simpler encoders. The fusion layer must also handle missing modalities gracefully: not every item has images, and not every product has reviews. Dropout-based training, where random modalities are zeroed out during training, produces fusion layers that degrade gracefully when modalities are absent at serving time.

Remark 61 (Content Features as a Regularizer).

Even in settings where collaborative signals are abundant, content features serve as a powerful regularizer. They break the symmetry among items with identical interaction patterns and provide a smooth embedding landscape: items with similar descriptions receive similar embeddings, even if their interaction patterns differ due to exposure bias. Hybrid systems that combine collaborative and content signals consistently outperform either approach alone, with typical improvements of 5–15% in recall@k over the best single-signal baseline.

LLM-Based Recommendation

The emergence of large language models has introduced a radically different approach to recommendation: instead of learning embeddings and computing similarities, simply describe the task in natural language and let the LLM rank items.

Zero-shot ranking with LLMs.

Hou et al. [24] demonstrate that LLMs can serve as zero-shot rankers for recommendation, bypassing the entire embedding-based pipeline. The approach is disarmingly simple: encode the recommendation task as a natural language prompt and let the LLM's world knowledge and reasoning capabilities produce a ranking. Given a user's interaction history and a set of candidate items, the LLM receives a prompt of the form:

The user has previously watched: [Movie A], [Movie B], [Movie C]. Rank the following movies by how likely the user is to enjoy them: 1. [Candidate 1] 2. [Candidate 2] k. [Candidate k]

The LLM produces a permutation of the candidates. Remarkably, this approach – which uses no trained recommendation model and no interaction data beyond what fits in the prompt – achieves competitive performance on standard benchmarks. The LLM implicitly leverages its knowledge of user preferences (absorbed from reviews, forums, and social media during pretraining) and its understanding of item similarities (absorbed from product descriptions and comparisons) to produce reasonable rankings.

Position bias and popularity bias.

LLM-based recommendation inherits biases from the language model's pretraining. Two biases are especially pernicious. Position bias: the LLM's ranking is sensitive to the order in which candidates appear in the prompt. Items presented earlier or later receive disproportionate attention, distorting the ranking. Popularity bias: the LLM has seen popular items more frequently during pretraining and tends to rank them higher regardless of the user's actual preferences. A user who prefers obscure arthouse films will still receive mainstream blockbuster recommendations.

Proposition 38 (Formal Analysis of LLM Recommendation Bias).

Let πLLM denote the ranking produced by an LLM given candidates in prompt order σ, and let π denote the ground-truth relevance ranking. Define the position bias coefficient as (Position BIAS)βpos=1|Σ|σΣπLLM(σ)πLLM1, where Σ is the set of all permutations of candidates and πLLM is the expected ranking averaged over all prompt orderings. For an unbiased ranker, βpos=0. Empirically, βpos for GPT-4 on movie recommendation is 15–25% of the maximum possible value, indicating substantial position sensitivity.

The popularity bias coefficient is (Popularity BIAS)βpop=Corr(rankLLM(i),logfreq(i)), where freq(i) is the frequency of item i in the pretraining corpus. A perfectly calibrated ranker has βpop=0; typical LLMs exhibit βpop[0.4,0.6] (negative because lower rank number means higher position), confirming that popular items are systematically over-ranked.

Caution.

LLM recommendations can be confidently wrong. Because LLMs produce fluent, authoritative text, their recommendations carry an unwarranted air of certainty. A collaborative filtering model that assigns item i a score of 0.51 out of 1.0 communicates its uncertainty through the score. An LLM that places item i at rank 1 with confident explanatory text gives no such signal. This is especially dangerous in high-stakes domains (medical recommendations, financial products) where overconfident suggestions can cause harm.

Generative Recommendation

The most radical departure from the retrieve-then-rank paradigm is generative recommendation: instead of scoring existing items, the model generates the identifier of the recommended item. This is a conceptual leap. Traditional recommendation asks “which of these items is most relevant?” Generative recommendation asks “what item should I construct?” The distinction is analogous to the difference between retrieval and generation in NLP: retrieval selects from a fixed set, generation produces something new. This reframes recommendation as a sequence-to-sequence problem, where the input is the user's history and the output is a sequence of tokens representing the recommended item.

TIGER: Semantic IDs for items.

TIGER (Transformer Index for GEneRative Recommenders) [91] assigns each item a semantic ID – a short sequence of discrete tokens derived from the item's content embedding via residual quantization. Given a user's interaction history (i1,i2,,it), TIGER autoregressively generates the semantic ID of the next item: (Tiger)p(it+1|i1,,it)=l=1Lp(cl(t+1)|c1(t+1),,cl1(t+1),i1,,it), where (c1(t+1),,cL(t+1)) is the L-token semantic ID of item it+1. The semantic ID encodes hierarchical item semantics: the first token captures coarse category (e.g., “action movie”), and subsequent tokens refine to specific items. This hierarchy enables efficient beam search during generation: the model first narrows down to a coarse category (pruning most of the catalogue), then refines within that category, and so on. At each level of the hierarchy, the beam search considers only |𝒱| options, making the total search cost O(L|𝒱|B) where B is the beam width – far more efficient than scoring all N items individually.

IDGenRec: Textual ID learning.

IDGenRec [92] takes a different approach: instead of quantized codes, it generates human-readable textual identifiers. Each item receives a unique textual ID (e.g., “sci-fi_2023_inception-like_7842”) learned jointly with the recommendation model. The advantage is direct compatibility with pretrained language models: the recommendation task becomes a standard text generation task, enabling the use of instruction-tuned LLMs without architectural modification. The textual IDs are also human-interpretable, which aids debugging: when a model generates an incorrect recommendation, developers can read the generated ID and understand which semantic features the model was targeting.

Definition 65 (Generative Recommendation Framework).

A generative recommender is a tuple (𝒱,ID,p𝜽) where:

  1. 𝒱 is a token vocabulary (discrete codes or text tokens).

  2. ID:𝒞𝒱L maps each item in the catalogue to an L-token identifier.

  3. p𝜽 is an autoregressive model that generates item IDs conditioned on user history: p𝜽(ID(it+1)|i1,,it).

The recommender retrieves items by generating their IDs via beam search, with the beam width controlling the trade-off between quality and latency.

The Cold-Start Problem and Generative Solutions

The cold-start problem arises when a new user (with no interaction history) or a new item (with no interactions) enters the system. Collaborative filtering, which relies entirely on interaction patterns, is helpless in this setting: the user's row in the interaction matrix is entirely empty, and no embedding can be learned. Content-based approaches partially mitigate the problem by using item features, but they cannot capture collaborative signals. The cold-start problem is not merely academic – in a typical e-commerce platform, 10–30% of items in the catalogue have fewer than five interactions, and new items enter the catalogue continuously.

Generative recommendation offers a natural solution. Because TIGER and IDGenRec derive item IDs from content features, new items receive meaningful IDs immediately upon entering the catalogue. The model can recommend a new item by generating its semantic ID, even if no user has ever interacted with it. For new users, the generative framework can condition on side information (stated preferences, demographic features, or even a natural language description of the user's interests) rather than requiring an interaction history.

Example 56 (Cold-Start in Music Recommendation).

A new song uploaded to a streaming platform has zero listens. Collaborative filtering cannot recommend it. A generative recommender with semantic IDs derived from the song's audio features (tempo, key, timbre, genre) can immediately place the song in the correct region of the ID space and recommend it to users whose histories include songs with similar semantic IDs. Early experiments with TIGER-style systems show a 23% improvement in cold-start item recall compared to content-based two-tower baselines.

Lemma 13 (Semantic ID Collision Probability).

Let the semantic ID vocabulary have size |𝒱| and the ID length be L. If N items are assigned IDs by residual vector quantization with independent codebook levels, the expected number of ID collisions (distinct items sharing the same ID) is bounded by (Collision Bound)𝔼[collisions]N22|𝒱|L. For N=107 items, |𝒱|=256, and L=4 tokens, this gives 𝔼[collisions]11,641 (since 2564=4.29×109), a collision rate of only about 0.1%, confirming that short semantic IDs suffice for practical catalogue sizes.

Proof.

By the birthday paradox, the probability that at least two items share the same ID is bounded by 1exp(N2/(2|𝒱|L)). The expected number of collisions follows from linearity of expectation over all (N2) pairs, each colliding with probability |𝒱|L under the independence assumption.

Insight.

Generative recommendation eliminates the index. Traditional recommendation requires maintaining an ANN index over all item embeddings – a data structure that must be rebuilt as items are added or removed. Generative recommendation replaces this index with the model's own parameters. Adding a new item requires only computing its semantic ID (a forward pass through the quantizer) and fine-tuning the model on a few examples. This architectural simplification is especially valuable in domains with rapidly changing catalogues, such as news recommendation or job listings.

The two-tower recommendation architecture. The user tower encodes user context (watch history, demographics, session state) into a query embedding 𝒒u. The item tower encodes item features (title, images, metadata) into an item embedding 𝒅i. Item embeddings are precomputed and stored in an ANN index. At serving time, the system computes 𝒒u and retrieves the top-k items by inner product search.
Traditional vs. generative recommendation pipelines. The traditional pipeline performs ANN-based candidate generation followed by cross-encoder reranking. The generative pipeline autoregressively produces item identifiers, collapsing both stages into a single model.

Algorithm 17 (Two-Tower Recommendation Retrieval).

  1. Input: User tower g𝜽, item tower h𝝓, catalogue 𝒞, ANN index 𝒜, number of candidates k
  2. Output: Top-k recommended items for user u
  3. Offline phase:
  4. for each item i𝒞
  5. Compute item embedding 𝒅ih𝝓(i)
  6. Insert (𝒅i,i) into ANN index 𝒜
  7. Online phase (per request):
  8. Construct user context xu from history, demographics, session
  9. Compute user embedding 𝒒ug𝜽(xu)
  10. Retrieve candidates: 𝒞kANN-Search(𝒜,𝒒u,k)
  11. return 𝒞k ranked by 𝒒u,𝒅i
ApproachCold-StartLatencyExpressivenessScalability
Matrix factorizationPoorVery lowLowExcellent
Neural CFPoorModerateHighModerate
Two-towerModerateLowHighExcellent
Content-basedGoodLowModerateExcellent
LLM zero-shotExcellentHighVery highPoor
TIGER (generative)GoodModerateHighGood
IDGenRecGoodModerateVery highGood
Comparison of recommendation approaches. “Cold-start” rates the approach's ability to handle new items or users. “Latency” is serving-time latency for a single request.

Exercise 70 (Diversity in Recommendation Retrieval).

A pure relevance-based retrieval system may return k items that are all very similar to each other (e.g., 10 action movies starring the same actor). Formalize the diversity-relevance trade-off by defining a maximal marginal relevance (MMR) objective: MMR(di)=λs(q,di)(1λ)maxdj𝒮sim(di,dj), where 𝒮 is the set of already-selected items. Prove that the greedy MMR algorithm is a (11/e)-approximation to the optimal diverse set under a submodularity assumption on the diversity function.

Exercise 71 (Matrix Factorization as Two-Tower).

Show that matrix factorization ((Matrix Factorization)) is a special case of the two-tower architecture ((TWO Tower)) where both towers are single embedding lookup tables. What architectural choices in the general two-tower model break this equivalence?

Exercise 72 (Debiasing LLM Recommendations).

Propose and formally analyze a method to reduce position bias in LLM-based recommendation. One approach: generate rankings for m random permutations of the candidate list and aggregate via Borda count. Derive the expected reduction in βpos ((Position BIAS)) as a function of m, assuming the LLM's position bias is symmetric.

Exercise 73 (Semantic ID Granularity).

In TIGER ((Tiger)), the number of tokens L in the semantic ID controls the trade-off between expressiveness and generation cost. Analyze this trade-off: what happens to recommendation accuracy and inference latency as L varies from 2 to 16? What is the minimum L required to uniquely identify N items given a codebook of size |𝒱|?

Learning to Rank

Retrieval finds the candidates; ranking orders them. The learning to rank (LTR) problem is deceptively simple to state: given a query q and a set of candidate documents {d1,,dn}, produce a permutation π:{1,,n}{1,,n} such that dπ(1) is the most relevant document, dπ(2) the second most relevant, and so on. The difficulty lies in the gap between the objective we care about – ranking quality as measured by metrics like nDCG or MAP – and the objectives we can optimize with gradient-based methods. Ranking metrics are discrete, non-differentiable functions of the predicted permutation. This section traces the three classical approaches to bridging this gap (pointwise, pairwise, listwise) and then examines how neural models and LLMs have reshaped the landscape.

Pointwise Approaches

The simplest approach ignores the ranking structure entirely and treats each query-document pair independently.

Regression.

Given a query-document pair (q,d) with a graded relevance label y{0,1,2,3,4} (e.g., from “not relevant” to “perfectly relevant”), pointwise regression learns a scoring function f𝜽(q,d) that minimizes the squared error: (Pointwise Regression)Lpoint=(q,d,y)𝒟(f𝜽(q,d)y)2. The ranking is then induced by sorting documents by their predicted scores. The simplicity of this formulation is appealing, but it ignores the fundamental insight that ranking is a relative task: the absolute score of a document matters far less than its score relative to other documents for the same query.

Classification.

An even simpler variant treats relevance as a binary label y{0,1} and trains a classifier: (Pointwise Classification)Lclass=(q,d,y)𝒟[ylogσ(f𝜽(q,d))+(1y)log(1σ(f𝜽(q,d)))].

Remark 62 (The Flaw of Pointwise Methods).

Pointwise methods optimize for absolute relevance prediction, not relative ordering. A model that assigns scores (3.1,2.9,0.1) to three documents has the same ranking as one that assigns (10,9,1), but the pointwise loss treats them very differently if the true labels are (3,3,0). The first model has lower squared error despite identical ranking quality. This disconnect between optimization objective and evaluation metric motivates pairwise and listwise approaches.

Pairwise Approaches

Pairwise methods reduce ranking to binary classification on pairs of documents: given two documents di and dj for the same query, learn to predict which one should rank higher.

Formal pairwise loss.

Let 𝒫q={(i,j):yi>yj} be the set of pairs where document i is more relevant than document j for query q. The general pairwise loss is (Pairwise LOSS)Lpair=q(i,j)𝒫q(f𝜽(q,di)f𝜽(q,dj),yij), where yij=+1 indicates that di should rank above dj and is a margin-based or logistic loss.

RankSVM.

RankSVM uses a hinge loss: (s,y)=max(0,1ys), treating each pair as a binary classification instance with a margin constraint. This reduces ranking to a standard SVM problem with O(n2) training pairs per query. The margin constraint encourages the model to produce score differences that are large enough to be robust to noise, a property inherited from the SVM tradition.

RankBoost.

RankBoost applies the AdaBoost framework to pairwise ranking, iteratively constructing weak rankers that focus on the most frequently misordered pairs. The boosting weights are updated based on pairwise classification errors.

LambdaRank.

LambdaRank [43] introduces the key insight that unlocked modern neural ranking: instead of defining a loss and deriving its gradient, define the gradient directly. The LambdaRank gradient for a pair (i,j) is (Lambdarank)λij=σ(sisj)|ΔnDCGij|, where si=f𝜽(q,di), σ() is the logistic sigmoid, and |ΔnDCGij| is the absolute change in nDCG that would result from swapping documents i and j in the current ranking. The ΔnDCG weighting ensures that swaps near the top of the ranking (which affect nDCG most) receive larger gradients. This is a form of cost-sensitive learning: the model pays more attention to errors that matter.

The total gradient on the score of document i is (Lambda Gradient)Lsi=j:yjyiλij=j:yj>yiλijj:yj<yiλji. Because λij incorporates the nDCG change, optimizing this “pseudo-loss” approximately optimizes nDCG itself, even though nDCG is a discrete, non-differentiable function of the ranking.

Insight.

Define the gradient, not the loss. LambdaRank's central innovation is philosophical: sometimes the right loss function is hard to write down, but the right gradient is obvious. The gradient should push harder on errors that affect the metric more. This “lambda trick” has influenced loss design well beyond ranking, showing up in generative adversarial networks and reinforcement learning from human feedback.

Listwise Approaches

While pairwise methods are a step up from pointwise, they still decompose the ranking into independent pairs and lose global structure. Listwise methods optimize over the entire ranked list at once.

LambdaMART.

LambdaMART combines the lambda gradients from LambdaRank with the MART (Multiple Additive Regression Trees) gradient boosting framework. At each boosting iteration, a regression tree is fit to the lambda gradients λij summed over all pairs for each document. The tree structure naturally captures feature interactions, and the lambda weighting ensures that the boosting process focuses on the most impactful ranking errors.

LambdaMART has been the dominant non-neural ranking model for over a decade, winning multiple learning-to-rank competitions and forming the backbone of commercial search engines. Its success stems from the combination of three strengths: gradient boosting handles heterogeneous features naturally, the lambda weighting focuses optimization on metric-impactful errors, and the regression tree ensemble is fast enough for online serving (typically under 5 milliseconds for 100 candidates).

ListNet.

ListNet defines a probability distribution over permutations using the Plackett-Luce model: (Plackett LUCE)Ps(π)=j=1nexp(sπ(j))l=jnexp(sπ(l)), where si=f𝜽(q,di) are predicted scores. ListNet minimizes the KL divergence between the predicted permutation distribution and the target distribution (derived from relevance labels). Computing the full permutation distribution is combinatorially expensive (n! permutations), so ListNet uses the “top-one probability” approximation: the probability that document i is ranked first, (Listnet TOP1)Ps(di is top-1)=exp(si)j=1nexp(sj), which is simply a softmax over scores. This approximation reduces the combinatorial Plackett-Luce loss to a standard cross-entropy loss between two softmax distributions – one derived from the predicted scores and one from the true relevance labels. The gradient computation is O(n), making ListNet practical for large candidate sets.

ListMLE.

ListMLE directly maximizes the likelihood of the ground-truth permutation under the Plackett-Luce model: (Listmle)LListMLE=qlogPs(πq), where πq is the ground-truth ranking for query q. This is computationally tractable because the Plackett-Luce likelihood decomposes as a product of n terms, each requiring a softmax over the remaining documents.

The three paradigms of learning to rank. Pointwise methods predict absolute relevance for each document independently. Pairwise methods learn relative preferences between document pairs. Listwise methods optimize the entire ranked list as a single object.

Theorem 17 (Consistency of the Plackett-Luce Estimator).

Let the true relevance scores be {y1,,yn} and let the Plackett-Luce log-likelihood be (PL Loglik)(𝒔)=j=1n[sπ(j)logl=jnexp(sπ(l))], where π is the ground-truth ranking. If the scoring function f𝜽 is from a universal function approximation class and the true scores satisfy yiyj for ij, then the maximum likelihood estimator 𝜽^=arg max𝜽(f𝜽) is consistent: f𝜽^ induces the correct ranking π as the number of training queries Q.

Proof sketch.

The Plackett-Luce log-likelihood is strictly concave in the score differences sisj. The global maximum is achieved when sπ(1)>sπ(2)>>sπ(n) with the score gaps growing without bound. By the universal approximation property, there exists 𝜽 such that f𝜽 induces arbitrary score gaps. The consistency of maximum likelihood estimation for identifiable parametric models (applied to the score parameters) then guarantees convergence to 𝜽 as Q increases.

Example 57 (LambdaMART in Commercial Search).

LambdaMART has been the dominant ranking model in commercial web search for over a decade. Microsoft's Bing search engine used LambdaMART as its primary ranker through at least 2019, with an ensemble of over 10,000 gradient boosted trees operating on hundreds of hand-crafted features. The model processes approximately 100 candidate documents per query, producing a ranked list in under 10 milliseconds. The transition from LambdaMART to neural rankers has been gradual: most production systems now use a hybrid approach, with LambdaMART handling the bulk of queries and neural rerankers applied selectively to high-value queries where the additional latency is justified.

Neural Ranking Models

Classical LTR methods (RankSVM, LambdaMART) operate on hand-crafted features: BM25 scores, PageRank, click-through rates, URL depth, and dozens of other signals. Neural ranking models replace the feature engineering with end-to-end learning from raw text.

BERT as a cross-encoder ranker.

The most direct application of neural models to ranking is the cross-encoder: concatenate the query and document as a single input to BERT and use the [CLS] token representation to predict relevance: (Cross Encoder)s(q,d)=𝐖BERT([q;[𝚂𝙴𝙿];d])+b, where 𝐖d and b are learned parameters. The cross-encoder attends jointly over query and document tokens, enabling rich interaction patterns (exact term matching, paraphrase detection, coreference resolution) that bi-encoder models cannot capture. For example, for the query “Who invented the telephone?” and a passage containing “Bell is credited with patenting the first practical telephone,” the cross-encoder can attend from “invented” to “credited with patenting” and from “Who” to “Bell” – interactions that a bi-encoder, which encodes query and document separately, fundamentally cannot capture.

The cost is inference: every query-document pair requires a full forward pass, making cross-encoders unsuitable for first-stage retrieval but ideal for reranking a small candidate set.

monoT5: Sequence-to-sequence ranking.

Nogueira et al. [84] reframe ranking as a text-to-text problem using T5. The input is “Query: $q$ Document: $d$ Relevant:” and the model generates either “true” or “false.” The relevance score is the log-probability assigned to “true”: (Monot5)s(q,d)=logpT5("𝚝𝚛𝚞𝚎"|"𝚀𝚞𝚎𝚛𝚢: q 𝙳𝚘𝚌𝚞𝚖𝚎𝚗𝚝: d 𝚁𝚎𝚕𝚎𝚟𝚊𝚗𝚝:"). This seemingly wasteful reformulation is surprisingly effective: monoT5 achieves state-of-the-art reranking on MS MARCO with a single unified architecture.

The evolution of LTR.

The trajectory of LTR reveals a consistent pattern: each generation shifts more of the ranking intelligence from features to the model, trading hand-crafted inductive biases for learned representations. The result is systems that are more general but also more data-hungry and more opaque.

  1. Feature-based LTR (2000s): Hand-crafted features + simple models (SVM, boosted trees).

  2. Neural LTR (2015–2019): Learned representations + pairwise/listwise losses.

  3. Pretrained LTR (2019–present): Large pretrained models (BERT, T5) fine-tuned for ranking.

  4. LLM LTR (2023–present): Prompting LLMs for ranking without task-specific fine-tuning.

Historical Note.

The feature engineering era. Before neural ranking, commercial search engines used hundreds of hand-crafted features. Microsoft's Bing reportedly used over 1,000 features in its ranking model as of 2015, including query-document match features (BM25 in title, body, anchor text, URL), document quality features (PageRank, spam score, reading level), and user interaction features (click-through rate, dwell time, bounce rate). Each feature required domain expertise to design and careful engineering to compute at scale. The shift to neural models did not eliminate this work – it transformed it from feature design to data curation, model architecture selection, and training infrastructure.

Definition 66 (Cross-Encoder Scoring).

A cross-encoder ranker is a function s𝜽:𝒬×𝒟 defined by (Cross Encoder DEF)s𝜽(q,d)=𝐖Enc𝜽(Concat(q,d))+b, where Enc𝜽 is a transformer encoder (e.g., BERT) that produces a pooled representation from the concatenated query-document input, 𝐖d is a learned projection, and b is a bias.

The key property is full cross-attention: every query token attends to every document token and vice versa, enabling fine-grained interaction modeling. The cost is quadratic in the combined sequence length: for a query of |q| tokens and a document of |d| tokens, the self-attention cost is O((|q|+|d|)2).

The monoT5 approach deserves further examination. By casting ranking as text generation, it enables a single T5 model to handle multiple tasks (passage ranking, document ranking, question generation) with different input-output templates. The model can also produce natural language explanations for its rankings by extending the output template, providing a form of ranking interpretability that classical LTR models lack entirely.

Remark 63 (Distillation from Cross-Encoders to Bi-Encoders).

A powerful training strategy for bi-encoder retrievers is to distill the knowledge of a cross-encoder ranker into the bi-encoder. The cross-encoder labels a large set of query-document pairs with soft relevance scores. The bi-encoder is then trained to match these scores via inner-product scoring. This knowledge distillation closes much of the gap between cross-encoder and bi-encoder performance while maintaining the bi-encoder's efficiency at serving time. The TAS-B model, for example, achieves cross-encoder-level performance on several BEIR tasks through careful distillation.

LLMs as Rankers

The latest paradigm shift in ranking is the use of large language models as zero-shot or few-shot rankers, with no task-specific training.

Prompting strategies for ranking.

Three prompting strategies have emerged, each mirroring one of the classical LTR paradigms:

  1. Pointwise prompting: Ask the LLM to rate each document's relevance on a scale (e.g., 0–3). Simple but suffers from calibration issues: the LLM may assign different scores to identical documents depending on surrounding context.

  2. Pairwise prompting: Present two documents and ask which is more relevant. More robust to calibration issues but requires O(n2) comparisons, which is expensive at LLM inference costs.

  3. Listwise prompting: Present all candidates and ask the LLM to produce a ranking. Most efficient in terms of API calls but limited by context window length and subject to position bias (the order of candidates in the prompt affects the output ranking).

The choice among these strategies involves a three-way trade-off between cost (number of LLM calls), robustness (sensitivity to prompt formatting), and quality (ranking accuracy).

In-context learning for relevance assessment.

By providing a few examples of query-document-relevance triples in the prompt, LLMs can learn the relevance criteria for a specific domain. This is especially valuable for specialized domains (legal, medical, scientific) where labeled ranking data is scarce. The in-context examples serve as an implicit specification of what “relevance” means in the target domain. For instance, in legal search, “relevance” might mean “cites the same statute,” while in medical search it might mean “describes the same treatment for the same condition.” These nuances are difficult to encode in a training loss but easy to communicate through a few examples in a prompt.

Proposition 39 (When Do LLM Rankers Beat Trained Rankers?).

Let fLLM be an LLM ranker with P parameters and fFT be a fine-tuned ranker with PP parameters trained on n labeled examples. Define the ranking quality as nDCG@10. Under the following conditions, the LLM ranker achieves higher nDCG@10 than the fine-tuned ranker:

  1. Low data regime: n<n, where the critical sample size n scales as n=Ω(P/dlog|𝒱|), with d the embedding dimension and |𝒱| the vocabulary size.

  2. Domain shift: The test domain differs from the training domain, and the LLM has seen relevant text in its pretraining corpus.

  3. Complex relevance criteria: Relevance requires reasoning (e.g., “find papers that contradict this hypothesis”) rather than lexical or semantic matching.

Conversely, the fine-tuned ranker dominates when training data is abundant (nn), the domain is stable, and relevance is well-captured by semantic similarity.

Example 58 (Listwise LLM Ranking in Practice).

Consider a listwise LLM ranker receiving 20 candidate passages for the query “How does photosynthesis work?” The prompt presents all 20 passages (truncated to fit the context window) and asks the LLM to output a permutation. In practice, the LLM's context window limits the number of candidates: with 20 passages of 200 tokens each plus the query and instructions, the total input is approximately 4,500 tokens. For larger candidate sets, a sliding window approach is used: rank the first 20, then the next 20, and merge the results. This introduces inconsistencies at window boundaries that must be resolved by a final global pass.

Research 7.

The convergence of ranking and generation. The boundary between ranking and generation is dissolving. LLM rankers treat ranking as text generation. Generative retrieval treats retrieval as sequence prediction. Generative recommendation treats item selection as token generation. This convergence suggests that the next generation of retrieval systems may not have separate retrieve, rank, and generate stages at all. Instead, a single autoregressive model may ingest a query, generate an internal retrieval plan, retrieve relevant information through its own parameters, and produce a final ranked list or answer – all within a single forward pass. Early evidence for this vision comes from self-RAG [38] and other models that learn to retrieve adaptively.

LambdaMART gradient computation. Document d1 (relevance 3) is ranked below d3 (relevance 2). The lambda gradient for this pair is weighted by |ΔnDCG|, the nDCG change from swapping them. Because this swap occurs near the top of the ranking, |ΔnDCG| is large, producing a strong gradient. The mis-ranked d2 at rank 3 produces smaller gradients because swaps involving low-relevance documents at low ranks have small nDCG impact.

Algorithm 18 (LambdaMART).

  1. Input: Training data {(q,d1,y1),,(q,dn,yn)} for each query q, learning rate η, number of trees T
  2. Output: Ensemble scoring function F(𝒙)=t=1Tht(𝒙)
  3. Initialize F0(𝒙)0 for all 𝒙
  4. for t=1,2,,T
  5. for each query q in training set
  6. Compute current scores siFt1(𝒙i) for all documents di
  7. Sort documents by si to obtain current ranking
  8. for each pair (i,j) with yi>yj
  9. ρijσ(sisj) pairwise probability
  10. Compute |ΔnDCGij| from swapping di,dj
  11. λijσ(si+sj)|ΔnDCGij|
  12. for each document di
  13. λij:yj<yiλijj:yj>yiλji net gradient
  14. wij:yjyi|λij|(1|λij|) Newton weight
  15. Fit regression tree ht to targets λi with weights wi
  16. Ft(𝒙)Ft1(𝒙)+ηht(𝒙)
  17. return FT

Proposition 40 (Pairwise Loss Approximately Optimizes nDCG).

Let σq denote the ranking induced by scores {f𝜽(q,di)}i=1n, and let nDCG(σq) denote the nDCG of this ranking with respect to relevance labels {yi}. Define the weighted pairwise loss (Weighted Pairwise)Lλ(𝜽)=q(i,j)𝒫q|ΔnDCGij|log(1+e(sisj)). Under the following conditions:

  1. The scoring function f𝜽 induces no ties (i.e., sisj for ij almost surely).

  2. The score differences |sisj| are bounded by some constant M>0.

Then at any local minimum 𝜽 of Lλ, the ranking σq correctly orders all pairs weighted by their nDCG impact. Specifically, (NDCG Bound)nDCG(σq)1Lλ(𝜽)(i,j)𝒫q|ΔnDCGij|.

Proof sketch.

At a local minimum, the gradient of Lλ vanishes. The gradient with respect to sisj is |ΔnDCGij|σ(sjsi). For this to be zero when |ΔnDCGij|>0, we need σ(sjsi)=0, which requires sisj. In the bounded-score regime (|sisj|M), the residual σ(sjsi)σ(M) provides the stated bound. The weighted pairwise loss at the optimum is bounded by (i,j)|ΔnDCGij|log(1+eM), and dividing by the total weight yields the nDCG guarantee.

Exercise 74 (Pairwise Complexity).

A query has n candidate documents. Show that the number of ordered pairs in 𝒫q is at most (n2). For the MS MARCO passage ranking task, queries have approximately n=1000 candidates. How many pairwise comparisons does this require? Propose and analyze a sampling strategy that reduces this to O(nlogn) while preserving ranking quality.

Exercise 75 (ListNet Implementation).

Derive the gradient of the ListNet top-one loss ((Listnet TOP1)) with respect to the predicted scores si. Show that this gradient has a particularly simple form involving the difference between two softmax distributions. Discuss why this loss is preferable to cross-entropy when the target distribution is derived from graded relevance labels.

Exercise 76 (Cross-Encoder vs. Bi-Encoder Trade-off).

A search engine receives 10,000 queries per second, each requiring ranking of 1,000 candidates. Compute the required GPU throughput (in forward passes per second) for: (a) a cross-encoder that scores each query-document pair independently, and (b) a bi-encoder where document embeddings are precomputed. Assume each forward pass takes 5,ms on a single GPU. How many GPUs does each approach require?

Exercise 77 (LambdaRank Gradient Derivation).

Starting from the RankNet loss LRankNet=(i,j)𝒫log(1+e(sisj)), derive the LambdaRank gradient in (Lambdarank) by introducing the |ΔnDCGij| weighting factor. Show that the resulting “lambda gradient” cannot be expressed as the gradient of any loss function – that is, there exists no function L such that siL=λi for all score vectors. This demonstrates that LambdaRank optimizes an implicit objective that can only be defined through its gradients.

Exercise 78 (monoT5 vs. BERT Reranker).

The monoT5 approach generates a binary token (“true” or “false”) while a BERT reranker produces a continuous score. Discuss the relative advantages of each approach for: (a) calibration (do the scores reflect true relevance probabilities?), (b) multi-task flexibility (can the same model handle different ranking tasks?), and (c) computational efficiency (how do inference costs compare for ranking n documents?).

Benchmarks and Evaluation

A retrieval system is only as good as the benchmarks used to evaluate it, and a benchmark is only as good as the community's understanding of its limitations. This section surveys the major benchmarks that have shaped retrieval research, introduces evaluation frameworks for the new generation of retrieval-augmented systems, and examines the cracks that are forming as benchmarks age.

BEIR: Heterogeneous Zero-Shot Evaluation

BEIR (Benchmarking IR) [104] assembles 18 diverse retrieval tasks spanning nine domains: bio-medical, financial, scientific, open-domain question answering, fact verification, citation prediction, duplicate question detection, argument retrieval, and entity retrieval. The datasets range from a few hundred to millions of documents, with query styles ranging from keyword queries to natural language questions to complex claims.

The critical design choice is zero-shot evaluation: models are evaluated on each task without any task-specific training data. This reflects the reality of deployed retrieval systems, which encounter new domains constantly. A legal search engine must handle new areas of law; a scientific search engine must index new subfields. A customer support search engine must handle new products. Zero-shot evaluation measures the robustness that matters most in practice: the ability to perform well on tasks the model was never explicitly trained for.

Definition 67 (BEIR Evaluation Protocol).

The BEIR evaluation protocol measures a retrieval model on K=18 tasks. For each task k:

  1. The model indexes the corpus 𝒞k without access to any queries or relevance judgments from task k.

  2. The model retrieves the top-100 documents for each query in the test set.

  3. nDCG@10 is computed against the provided relevance judgments.

The aggregate BEIR score is the average nDCG@10 across all 18 tasks.

BEIR revealed a startling finding: dense retrieval models that achieved state-of-the-art performance on MS MARCO often performed worse than BM25 on out-of-domain tasks. Models that had been celebrated as breakthroughs were, in fact, overfitting to the idiosyncrasies of a single benchmark. This finding catalyzed a shift toward more robust training strategies: harder negative mining, multi-task training, and distillation from cross-encoders.

Example 59 (The BM25 Surprise on BEIR).

When BEIR was introduced in 2021, BM25 – a 27-year-old unsupervised method – outperformed all tested dense retrieval models on 7 out of 18 tasks. On the TREC-COVID dataset (biomedical retrieval), BM25 achieved nDCG@10 of 0.656, while the best dense model (DPR) achieved only 0.332. This gap was not due to a flaw in dense retrieval but rather to domain mismatch: DPR was trained on Natural Questions, a Wikipedia-based QA dataset, and its learned notion of “relevance” did not transfer to biomedical literature.

MS MARCO: The Workhorse of Passage Ranking

The Microsoft MAchine Reading COmprehension dataset [105] is the most widely used benchmark in passage retrieval. It consists of approximately 8.8 million passages from web documents, 500,000 training queries derived from Bing search logs, and sparse relevance judgments (typically one relevant passage per query).

Sparse judgments.

Each query in MS MARCO has, on average, only 1.1 relevant passages marked, despite the corpus containing 8.8 million passages. This means that the vast majority of relevant passages are unlabeled – they appear as negatives in evaluation, even though they may be perfectly relevant. This “false negative” problem biases evaluation: a model that retrieves a truly relevant but unlabeled passage is penalized. The bias is systematic: the better the model, the more unlabeled relevant passages it retrieves, and the more it is unfairly penalized. Re-assessment campaigns (such as TREC Deep Learning Track re-judging) have shown that top-ranked dense retrieval models find 30–50% more relevant passages than the original judgments contain.

Open development.

MS MARCO's open evaluation server has enabled rapid iteration. Over 3,000 submissions have been made to the leaderboard, with MRR@10 improving from 0.187 (BM25 baseline) to over 0.45 (modern dense retrievers with cross-encoder reranking). The open nature of the benchmark has been both its greatest strength (enabling fast progress) and its weakness (enabling overfitting through repeated evaluation).

Remark 64 (MS MARCO's Bing Bias).

Because MS MARCO queries come from Bing search logs, they reflect the search patterns of English-speaking Bing users. This introduces demographic, linguistic, and topical biases. Queries are disproportionately navigational (“facebook login”), health-related (“symptoms of covid”), or how-to oriented (“how to tie a tie”). Models trained and evaluated on MS MARCO may not generalize to other query distributions (e.g., academic search, legal search, or queries in other languages).

Example 60 (The MS MARCO Leaderboard Progression).

The progression of top scores on the MS MARCO passage ranking leaderboard illustrates the rapid advance of neural retrieval:

YearModelMRR@10
2016BM25 (baseline)0.187
2019BERT reranker0.365
2020ANCE (dense retrieval)0.330
2021coCondenser + CE reranker0.407
2023RankLLaMA + retriever0.426
2024Best ensemble0.450+
The most dramatic jump occurred with the introduction of BERT-based reranking (2019), which nearly doubled the BM25 baseline. Subsequent improvements have been incremental, suggesting diminishing returns on this particular benchmark.

KILT: Knowledge-Intensive Language Tasks

KILT [106] unifies five knowledge-intensive task families under a single benchmark and a single knowledge source (Wikipedia):

  1. Fact checking: Given a claim, retrieve evidence and classify as supported, refuted, or not enough info (FEVER).

  2. Entity linking: Given a mention in context, link it to the correct Wikipedia entity (AIDA CoNLL-YAGO).

  3. Slot filling: Given an entity and relation, retrieve passages containing the answer (T-REx, zero-shot RE).

  4. Open-domain QA: Given a question, retrieve passages and extract or generate the answer (Natural Questions, HotpotQA, TriviaQA).

  5. Dialogue: Given a conversation history, retrieve relevant knowledge for the next response (Wizard of Wikipedia).

KILT's value lies in its unification: by using the same knowledge source across all tasks, it enables apples-to-apples comparison of retrieval quality across fundamentally different use cases. A retriever that excels at QA but fails at fact checking has a different failure mode than one that works for both. The unified knowledge source also simplifies experimentation: researchers can test a single retrieval pipeline across all five task families without corpus preprocessing overhead.

The tasks in KILT vary dramatically in their retrieval difficulty. Open-domain QA (Natural Questions) requires finding a single passage containing the answer – a relatively focused retrieval task. Entity linking requires matching a potentially ambiguous mention to the correct Wikipedia page among millions of candidates. Slot filling requires finding passages that contain a specific fact about a specific entity, which may be mentioned only in passing. This diversity makes KILT a stringent test of retrieval robustness.

Remark 65 (KILT and the Provenance Problem).

KILT enforces a strict provenance requirement: systems must identify the specific Wikipedia passages that support their answers. This is more demanding than simply producing a correct answer, because a model that generates correct answers from parametric knowledge alone (without retrieval) receives zero retrieval credit. The provenance requirement aligns with the goals of trustworthy AI: users and auditors need to verify where information comes from, not merely whether the final output is correct. KILT's design thus anticipates the growing demand for attribution in LLM-based systems.

MTEB: Massive Text Embedding Benchmark

MTEB [107] evaluates text embeddings across a comprehensive suite of tasks, extending far beyond retrieval. The benchmark includes eight task categories:

CategoryTasksDescription
Retrieval15Find relevant documents for a query
Classification12Classify text using embedding features
Clustering11Group similar texts by embedding proximity
Pair classification3Predict relationship between text pairs
Reranking4Reorder candidates by relevance
STS10Predict semantic similarity scores
Summarization1Evaluate summary quality via embeddings
Bitext mining3Find parallel sentences across languages
MTEB task categories. Each category evaluates a different aspect of embedding quality.

MTEB has become the de facto leaderboard for text embedding models. Its breadth is its strength: a model that achieves high scores across all eight categories produces genuinely general-purpose embeddings. However, this breadth also means that the aggregate score can mask significant weaknesses. A model with excellent retrieval performance but poor clustering ability may still rank highly overall.

Key Idea.

No single embedding is optimal for all tasks. MTEB consistently shows that the best retrieval embedding is not the best clustering embedding, which is not the best classification embedding. The inductive biases needed for each task differ: retrieval benefits from asymmetric (query-document) embeddings, clustering benefits from isotropic representations, and classification benefits from embeddings that separate class boundaries. This motivates task-specific fine-tuning and adapter-based approaches over monolithic “one embedding to rule them all” models.

Example 61 (The MTEB Leaderboard Dynamics).

The MTEB leaderboard exhibits a distinctive pattern: models with the highest aggregate scores are not necessarily the best on any individual task category. As of early 2025, the top-ranked models (e.g., large instruction-tuned embedding models with 7B+ parameters) achieve high average scores through consistent, above-average performance across all categories, while smaller specialized models (e.g., GTE-base for retrieval, E5-small for classification) often outperform them on specific tasks. This creates a practical dilemma: should practitioners deploy a single large model for all embedding needs, or maintain a portfolio of smaller specialized models? The answer depends on the deployment constraints – a single model simplifies infrastructure, while a portfolio maximizes task-specific performance.

Definition 68 (Embedding Quality Profile).

The embedding quality profile of a model on a multi-task benchmark with K task categories is the vector (Embedding Profile)𝒒=(q1,q2,,qK)[0,1]K, where qk is the normalized score (percentile rank among all evaluated models) of on task category k. A model with 𝒒=(1,1,,1) is the best on every category. The profile variance Var(𝒒) measures specialization: low variance indicates a generalist, high variance indicates a specialist.

Multimodal Retrieval Benchmarks

Retrieval is not limited to text. A growing family of benchmarks evaluates cross-modal retrieval: finding relevant items across modality boundaries. These benchmarks are essential for evaluating the multimodal embedding models (CLIP, ImageBind, and their successors) that power image search, video recommendation, and audio discovery systems.

Image-text retrieval.

MSCOCO [9] and Flickr30k are the standard benchmarks for image-text retrieval. Each image is paired with five human-written captions. Evaluation measures recall at k (R@k) for both image-to-text and text-to-image retrieval. CLIP-based models dominate these benchmarks, with R@1 exceeding 80% on MSCOCO for text-to-image retrieval.

Video-text retrieval.

MSR-VTT [10] contains 10,000 video clips with 200,000 natural language descriptions. Video-text retrieval is substantially harder than image-text retrieval because the model must capture temporal dynamics: a description like “a man walks across the room and picks up a book” requires understanding the sequence of actions, not just individual frames.

Audio-text retrieval.

AudioCaps [13] provides captions for audio clips from the AudioSet ontology. Audio-text retrieval evaluates whether models can match sounds (“birds chirping in a forest”) to their descriptions. This is the least mature of the cross-modal retrieval tasks, with significant room for improvement.

BenchmarkModalityTasksPrimary MetricYear
MS MARCOText1MRR@102016
BEIRText18nDCG@102021
KILTText11R-Precision2021
MTEBText59Various2023
MSCOCOImage-text2R@1, R@52014
Flickr30kImage-text2R@1, R@52014
MSR-VTTVideo-text2R@1, R@52016
AudioCapsAudio-text2R@1, R@102019
Major retrieval benchmarks at a glance.

Example 62 (The Video-Text Gap).

The gap between image-text and video-text retrieval performance is revealing. On MSCOCO, the best models achieve R@1 above 80% for text-to-image retrieval. On MSR-VTT, the best text-to-video R@1 is approximately 50%. This 30+ point gap quantifies the difficulty of temporal understanding: retrieving the right video requires understanding actions, causality, and temporal ordering – aspects that static image-text matching models cannot capture. Closing this gap is one of the major open challenges in multimodal retrieval.

Remark 66 (The Missing Modality: Structured Data Retrieval).

All major retrieval benchmarks focus on unstructured data (text, images, video, audio). Yet a vast amount of the world's information lives in structured databases, spreadsheets, and knowledge graphs. Retrieving relevant structured data given a natural language query (“find all companies with revenue greater than $1B in the healthcare sector”) requires a fundamentally different approach: translating queries to structured query languages (SQL, SPARQL) or embedding structured records alongside text. Benchmarks for this task (Spider, WikiTableQuestions) exist in the NLP community but remain disconnected from the mainstream retrieval benchmarks.

RAG-Specific Evaluation

Retrieval-augmented generation introduces a new evaluation challenge: the quality of the final output depends on both the retrieval component and the generation component, and disentangling their contributions is non-trivial.

RAGAS framework.

The RAGAS framework [95] proposes component-wise evaluation for RAG systems:

  1. Faithfulness: Does the generated answer use only information from the retrieved context? Measured by decomposing the answer into claims and checking each claim against the context.

  2. Answer relevance: Does the answer address the question? Measured by generating synthetic questions from the answer and computing similarity to the original question.

  3. Context precision: Are the retrieved documents relevant to the question? Measured by checking whether the answer can be derived from each retrieved document.

  4. Context recall: Do the retrieved documents contain all information needed to answer? Measured by checking whether each sentence in the ground-truth answer is supported by the context.

Component-wise vs. end-to-end evaluation.

End-to-end evaluation (measuring only the final answer quality) is simpler but hides failure modes. A system might retrieve irrelevant documents but still produce a correct answer from the LLM's parametric knowledge. Conversely, a system might retrieve perfect documents but generate a hallucinated answer. Component-wise evaluation exposes these failure modes, enabling targeted improvement.

Definition 69 (RAG Evaluation Framework).

A RAG evaluation framework decomposes system quality into four orthogonal dimensions:

  1. Retrieval quality QR: measured by standard retrieval metrics (nDCG, recall) on the retriever output.

  2. Context utilization QC: the fraction of retrieved information that the generator actually uses.

  3. Generation faithfulness QF: the fraction of generated claims supported by the retrieved context.

  4. Answer quality QA: end-to-end correctness of the final answer, measured by exact match, F1, or human evaluation.

The overall RAG quality satisfies QAmin(QR,QF): the system cannot produce a faithful, correct answer if the retriever misses relevant documents or the generator hallucinates. In practice, the bottleneck shifts as the system improves: early RAG systems are retrieval-limited (QR<QF), while mature systems with strong retrievers become generation-limited (QF<QR). Identifying the current bottleneck is essential for directing optimization effort.

Example 63 (Faithfulness Failure in Production RAG).

Consider a RAG system answering the question “What is the capital of Australia?” The retriever returns a passage stating “Canberra has been the capital of Australia since 1927.” A faithful generator would answer “Canberra.” However, an unfaithful generator might answer “Sydney” – a common misconception that the LLM has absorbed from its pretraining data. The RAGAS faithfulness score would be 0 for this response (the claim “Sydney is the capital” is not supported by the retrieved context), while the answer relevance score might still be high (the response does address the question). This example illustrates why component-wise evaluation is essential: the end-to-end answer is wrong, but the failure lies entirely in the generator, not the retriever.

Proposition 41 (RAG Quality Decomposition).

Let A denote the event that the RAG system produces a correct answer, R the event that the retriever returns at least one relevant passage, and G the event that the generator produces a correct answer given the retrieved context. Then (RAG Decomp)P(A)=P(A|R,G)P(G|R)P(R)+P(A|Rc)P(Rc), where P(A|R,G)=1 (correct retrieval and correct generation implies correct answer), P(A|Rc) is the probability that the generator produces a correct answer from parametric knowledge alone (without relevant retrieved context), and P(Rc)=1P(R).

This decomposition reveals the “parametric knowledge confound”: when P(A|Rc) is high (the LLM already knows the answer), end-to-end evaluation P(A) gives inflated credit to the retriever. Component-wise evaluation addresses this by measuring P(R) and P(G|R) separately.

The diversity of BEIR tasks. Each colour represents a domain category. The benchmark spans question answering, fact verification, citation prediction, duplicate detection, bio-medical retrieval, and argument retrieval, ensuring that no single retrieval strategy can dominate across all tasks.
Component-wise evaluation framework for RAG systems. Each component is evaluated independently: the retriever by standard IR metrics (QR), context utilization by how much retrieved information the generator uses (QC), generation faithfulness by claim verification (QF), and overall answer quality by end-to-end metrics (QA). The dashed arrow from query to generator indicates that the query is also passed directly to the generator.

A Primer on Retrieval Metrics

Before examining benchmark limitations, we consolidate the evaluation metrics that appear throughout this chapter. The choice of metric encodes assumptions about what constitutes a good ranking, and different metrics can lead to contradictory conclusions about the same system.

Precision and recall at k.

For a ranked list of k documents returned for query q: (PREC Recall)P@k=|relevant docs in top-k|k,R@k=|relevant docs in top-k||all relevant docs|. Precision rewards systems that avoid returning irrelevant documents. Recall rewards systems that find all relevant documents. The tension between the two is fundamental: aggressive retrieval (returning many documents) increases recall at the expense of precision.

Mean reciprocal rank (MRR).

MRR measures how quickly the system returns the first relevant document: (MRR)MRR=1|Q|qQ1rankq, where rankq is the position of the first relevant document for query q. MRR is appropriate when users care primarily about the top result (e.g., navigational queries).

Normalized discounted cumulative gain (nDCG).

nDCG is the dominant metric for graded relevance: (NDCG)nDCG@k=DCG@kIDCG@k,DCG@k=i=1k2yπ(i)1log2(i+1), where yπ(i) is the relevance grade of the document at rank i and IDCG@k is the DCG of the ideal ranking. The logarithmic discount reflects the assumption that users are less likely to examine lower-ranked results. The exponential gain (2y1) gives disproportionate credit to highly relevant documents: a document with relevance 3 contributes 231=7 times as much as a document with relevance 1.

Mean average precision (MAP).

MAP averages the precision at each relevant document position: (MAP)AP(q)=1|Relq|k=1nP@k𝟙[dkRelq],MAP=1|Q|qQAP(q). MAP is appropriate for binary relevance and rewards systems that rank all relevant documents highly, not just the first one.

Caution.

Metric choice changes model rankings. Two systems with nDCG@10 scores of 0.42 and 0.41 may reverse when evaluated by MRR (the second system may place its best result at rank 1 more often, while the first distributes relevant results across ranks 2–5). Always report multiple metrics, and always choose the primary metric based on the specific user behaviour pattern in your application.

Benchmark Limitations

Every benchmark, no matter how carefully constructed, has a shelf life. Three forces conspire to erode the value of retrieval benchmarks over time.

Saturation.

As models improve, the gap between the best and worst models shrinks, and the benchmark ceases to discriminate meaningfully. On MS MARCO passage ranking, the gap between BM25 and the state of the art has narrowed from 28 nDCG@10 points in 2016 to under 10 points in 2024. On MSCOCO text-to-image retrieval, R@1 has exceeded 80%, leaving limited headroom. When benchmarks saturate, the community loses its ability to measure meaningful progress, and papers increasingly report improvements within the noise level of the evaluation methodology.

Contamination.

Training data leaking into test sets is a growing concern, especially for LLM-based systems. An LLM pretrained on the open web may have ingested MS MARCO queries, BEIR passages, or even the relevance judgments themselves. This makes it impossible to distinguish genuine generalization from memorization. The problem is especially acute for zero-shot evaluation: if the model has “seen” the test queries during pretraining, the evaluation is no longer zero-shot in any meaningful sense.

Fine-grained discrimination.

Most retrieval benchmarks use binary or coarsely graded relevance labels, which cannot distinguish between a “somewhat relevant” passage and a “perfectly relevant” one. MS MARCO's binary judgments (relevant vs. not relevant) are particularly limiting: they cannot evaluate whether a model retrieves the best passage or merely an acceptable one. This coarseness masks important quality differences between systems.

Caution.

Benchmark performance is not deployment performance. The conditions under which benchmarks are evaluated – clean queries, static corpora, pre-defined relevance judgments – bear little resemblance to production environments. In production, queries are noisy, misspelled, and ambiguous. Corpora are updated continuously. Relevance is subjective, context-dependent, and changes over time. A model that achieves 0.50 nDCG@10 on BEIR may achieve only 0.35 on a proprietary benchmark derived from real user interactions. Always evaluate on data that reflects your actual deployment conditions.

Remark 67 (The Benchmark Treadmill).

The retrieval community is on a treadmill: each generation of benchmarks is designed to address the limitations of the previous generation, but it inevitably develops its own. MS MARCO addressed the small-scale limitations of TREC ad-hoc retrieval. BEIR addressed MS MARCO's single-domain limitation. MTEB addressed BEIR's retrieval-only focus. The next generation will likely address MTEB's English-only limitation and the contamination problem. The treadmill is not a failure of the community; it is a natural consequence of rapid progress. The lesson is not to avoid benchmarks but to hold them lightly, always aware that they are approximations of the true evaluation we care about: user satisfaction.

Example 64 (Contamination in LLM-Based Retrieval Evaluation).

In 2023, researchers discovered that several LLM-based retrieval systems achieved suspiciously high zero-shot performance on BEIR tasks. Upon investigation, they found that the LLMs' pretraining data included the exact query-passage pairs from multiple BEIR datasets. The models were not “zero-shot” in any meaningful sense – they had memorized the test data. When evaluated on held-out queries not present in the pretraining data, performance dropped by 15–25 nDCG points. This episode underscored the need for dynamic benchmarks with regularly refreshed test sets, and for decontamination protocols in LLM training pipelines.

Historical Note.

From Cranfield to BEIR: 60 years of retrieval evaluation. The history of retrieval evaluation stretches back to the Cranfield experiments of the 1960s, when Cyril Cleverdon evaluated indexing languages on a collection of 1,400 aeronautics abstracts. The TREC conferences, starting in 1992, scaled evaluation to millions of documents and introduced the pooling methodology still used today. The Web Track (2000s) brought web-scale collections and navigational queries. MS MARCO (2016) introduced large-scale neural training data. BEIR (2021) introduced cross-domain zero-shot evaluation. Each transition was driven by the previous generation of benchmarks becoming saturated or misaligned with the evolving capabilities of retrieval systems. The constant thread is the tension between reproducibility (requiring fixed test collections) and ecological validity (requiring benchmarks that reflect real-world conditions).

Exercise 79 (BEIR Domain Transfer Analysis).

Download the BEIR benchmark results for three dense retrieval models (e.g., DPR, ANCE, TAS-B) and compute the correlation between their MS MARCO performance and their average performance on the other 17 BEIR tasks. Is MS MARCO performance a good predictor of zero-shot performance? Identify which BEIR tasks are most and least correlated with MS MARCO and propose explanations.

Exercise 80 (Designing a Contamination Test).

Propose a method to detect whether an LLM's pretraining data contains MS MARCO test queries. One approach: use the LLM to generate completions of partial test queries and measure the completion accuracy. Formalize this as a hypothesis test with null hypothesis “the model has not seen the test queries” and derive the expected completion accuracy under the null.

Exercise 81 (RAG Component Attribution).

A RAG system achieves 72% exact match on a QA benchmark. When the retriever is replaced with a perfect oracle retriever (always returns the gold passage), exact match increases to 89%. When the generator is replaced with a perfect oracle extractor (always extracts the correct span), exact match increases to 81%. Compute the retrieval gap, generation gap, and interaction gap. Which component should be improved first for maximum impact?

Exercise 82 (MTEB Score Decomposition).

The aggregate MTEB score weights all task categories equally. Argue that this weighting is inappropriate for a system intended primarily for retrieval. Propose and justify an alternative weighting scheme. Compute the reranking of the top-5 models on the MTEB leaderboard under your proposed weighting and discuss how the ranking changes.

Exercise 83 (Building a RAG Evaluation Pipeline).

Design an automated evaluation pipeline for a RAG system that answers questions about a company's internal documentation. Your pipeline should: (a) generate synthetic evaluation queries from the document corpus (describe a method for doing this with an LLM), (b) measure all four RAGAS dimensions (QR, QC, QF, QA), and (c) produce a dashboard that identifies the weakest component. Discuss how you would validate that the synthetic queries are representative of real user queries.

Exercise 84 (nDCG vs. MAP Disagreement).

Construct a concrete example where two ranking systems A and B satisfy nDCG@10(A) > nDCG@10(B) but MAP(A) < MAP(B). Explain intuitively why this disagreement occurs and identify the user behaviour assumptions under which each metric gives the “correct” answer. Relate your analysis to the distinction between informational and navigational queries.

Consolidation with Prior Chapters

Throughout this book we have encountered retrieval in many guises, sometimes explicit and sometimes hidden beneath layers of abstraction. In this section we draw together the threads, demonstrating that retrieval is not merely one technique among many but a unifying lens through which the entire landscape of modern AI can be viewed. Every model that stores information and later uses it is, at its core, performing retrieval. The question is never whether a system retrieves, but how.

Generative Models as Retrieval Systems

The generative models surveyed in earlier parts of this book, including variational autoencoders, generative adversarial networks, and diffusion models, are conventionally understood as systems that create new data. We argue that they can equally be understood as systems that retrieve from a learned, continuous index.

VAE latent spaces as retrieval spaces.

A variational autoencoder (15) learns an encoder q𝜽(𝒛|𝒙) that maps data 𝒙 to a latent code 𝒛d and a decoder p𝜽(𝒙|𝒛) that maps codes back to data. Viewed through the retrieval lens, the encoder is a query encoder that transforms an input into a representation, and the decoder is a generative retrieval system that, given a query in latent space, “retrieves” the most probable data point.

Definition 70 (VAE as Retrieval).

Let (𝒳,𝒵,q𝜽,p𝜽) be a trained VAE. Define the latent retrieval function :𝒵𝒳 as (VAE Retrieval)(𝒛)=arg max𝒙𝒳p𝜽(𝒙|𝒛). Then a nearest-neighbour search in 𝒵 followed by decoding is equivalent to a two-stage retrieval pipeline: encode the query, retrieve from the latent index, decode the result.

The ELBO objective that trains the VAE simultaneously optimises two retrieval-relevant properties: reconstruction quality (the retrieved item should match the query) and index regularity (the latent space should support smooth interpolation, analogous to a well-organized index that groups similar items nearby).

Insight.

The KL divergence term in the ELBO, DKL(q𝜽(𝒛|𝒙)p(𝒛)), acts as a regularisation penalty on the index structure. Without it, the encoder would create an index with arbitrarily complex topology, making interpolation (a form of approximate retrieval) impossible. The prior p(𝒛) enforces that the index be navigable.

GAN discriminator features for retrieval.

Generative adversarial networks (9) train a generator G and a discriminator D in a minimax game. While G receives most of the attention in the generation literature, the discriminator learns remarkably powerful feature representations as a byproduct of its training. The intermediate layers of D capture hierarchical features that distinguish real from generated data, and these features transfer effectively to retrieval tasks.

Formally, let ϕD()(𝒙) denote the activation of the -th layer of a trained discriminator. For retrieval, we define the similarity between a query 𝒒 and a document 𝒅 as (GAN SIM)s(𝒒,𝒅)==1Lwcos(ϕD()(𝒒),ϕD()(𝒅)), where w are learned or hand-tuned weights. This multi-scale similarity captures both low-level texture matches (early layers) and high-level semantic similarity (deep layers).

Remark 68.

The adversarial training objective forces the discriminator to learn features that are invariant to the “easy” patterns and sensitive to the “hard” ones: precisely the features that matter for fine-grained retrieval. This explains the empirical observation that GAN-trained features often outperform classification-trained features on retrieval benchmarks for visual similarity.

Diffusion features (DIFT) for retrieval.

Perhaps the most surprising connection comes from diffusion models (19). The denoising process in a diffusion model requires the network to understand the data at every noise level, from coarse global structure (high noise) to fine local detail (low noise). Tang et al. showed that the intermediate features of a diffusion model, which they call DIFfusion FeaTures (DIFT), provide excellent representations for retrieval and correspondence tasks [60].

Proposition 42 (Denoising as Feature Learning).

Let 𝝐𝜽(𝒙t,t) be the noise prediction network of a diffusion model trained with the denoising objective 𝔼t,𝝐[𝝐𝝐𝜽(𝒙t,t)2]. Then the intermediate features ϕt()(𝒙)h()(𝒙t,t), where h() is the hidden activation at layer and time t, form a multi-scale representation hierarchy:

  1. For large t (high noise), ϕt() captures global semantic content.

  2. For small t (low noise), ϕt() captures fine-grained local structure.

This hierarchy arises because the denoising objective at noise level t requires the network to “retrieve” the clean signal from a corrupted version, and the information needed for this retrieval varies systematically with t.

The reason diffusion features work so well for retrieval is deep: denoising IS retrieval. Given a noisy observation 𝒙t, the diffusion model must retrieve the clean data point 𝒙0 from its learned representation of the data distribution. The features learned in service of this implicit retrieval task transfer naturally to explicit retrieval.

Neural Architecture Search for Retrieval

The neural architecture search methods of 30 provide a natural toolkit for designing retrieval models. Rather than hand-crafting encoder architectures, we can search for architectures optimised for retrieval-specific objectives.

Example 65 (NAS for Bi-Encoder Design).

Consider searching for an optimal bi-encoder architecture for dense retrieval. The search space includes:

  • Backbone: transformer depth L{4,6,8,12}, width d{256,384,512,768}, number of heads H{4,8,12}.

  • Pooling: [CLS] token, mean pooling, attention-weighted pooling, or learned projection.

  • Projection head: linear, two-layer MLP, or bottleneck architecture with dimension d{64,128,256}.

The objective is a Pareto combination of retrieval quality (nDCG@10 on a validation set) and inference latency (milliseconds per query on target hardware). Differentiable NAS techniques from 30 can efficiently search this space by relaxing discrete architectural choices into continuous parameters.

A particularly important design choice is the embedding dimension, which controls the trade-off between representational capacity and index size. NAS can discover architectures that achieve high retrieval quality at surprisingly low dimensions by learning to allocate capacity where it matters most.

Evolutionary AI and Retrieval

The evolutionary methods of 31 connect to retrieval in two ways: evolution as a tool for optimising retrieval systems, and retrieval as a component within evolutionary algorithms.

Evolving retrieval strategies.

The AlphaEvolve framework (31) demonstrated that LLM-guided program evolution can discover improvements to hash functions and scheduling algorithms. The same approach applies directly to retrieval: we can evolve scoring functions, index structures, and query expansion strategies.

Example 66 (AlphaEvolve for Index Optimization).

Consider evolving the partitioning strategy for an inverted file index (IVF). The standard approach uses k-means clustering to create partitions, but the optimal partitioning depends on the query distribution as well as the document distribution. An evolutionary approach can:

  1. Represent the partitioning strategy as a program that assigns documents to clusters.

  2. Evaluate fitness as the recall@k achieved by probing a fixed number of partitions, measured on a held-out query set.

  3. Evolve using LLM-guided mutation to discover partitioning strategies that exploit the joint structure of queries and documents.

The evolved strategies may discover non-Voronoi partitions, overlapping clusters, or hierarchical decompositions that standard k-means cannot express.

Retrieval within evolutionary search.

Conversely, retrieval is a critical component within evolutionary AI. Quality-diversity algorithms like MAP-Elites maintain archives of diverse solutions, and finding the most similar archived solution to a new candidate is itself a retrieval problem. As archives grow to millions of entries, efficient approximate nearest-neighbour search becomes essential for scalable evolutionary computation.

Continual Learning and Retrieval

The continual learning methods of 26 face the fundamental challenge of catastrophic forgetting: when a model learns new tasks, it tends to overwrite the knowledge needed for old ones. Retrieval provides one of the most effective defences.

Definition 71 (Experience Replay as Retrieval).

Let ={(𝒙i,yi)}i=1M be an experience replay buffer containing samples from previously learned tasks. When training on a new task 𝒯new, the replay mechanism retrieves a subset 𝒮 and interleaves it with the new data: (Replay)replay(𝜽)=𝔼(𝒙,y)𝒯new[(𝒙,y;𝜽)]+λ𝔼(𝒙,y)𝒮[(𝒙,y;𝜽)]. The choice of retrieval strategy for 𝒮 determines which old knowledge is preserved. Random sampling, diversity-maximising retrieval, and loss-proportional retrieval each produce different continual-learning dynamics.

Remark 69.

The connection between experience replay and biological memory consolidation is not merely metaphorical. During sleep, the hippocampus “replays” recent experiences to the neocortex, a process that neuroscientists believe is essential for long-term memory formation. This biological replay is selective: the hippocampus preferentially replays experiences that are surprising, emotionally salient, or relevant to current goals. Designing artificial replay mechanisms with similar selectivity is an active research direction.

Privacy in Retrieval Systems

The membership inference attacks studied in 29 take on a distinctive character in retrieval systems. In a standard classifier, membership inference asks: “Was this sample in the training set?” In a retrieval system, the question becomes: “Is this document in the index?” and the answer is often trivially “yes” because the system returns it. The deeper privacy questions are more subtle.

Definition 72 (Retrieval Membership Inference).

Given a dense retrieval system with encoder f𝜽 trained on corpus 𝒞, the retrieval membership inference problem asks: given a document 𝒅, determine whether 𝒅 was in the training set 𝒟train used to train f𝜽 (as opposed to merely being present in the retrieval index 𝒞, which may differ from 𝒟train).

The distinction matters because a document can be in the retrieval index without having influenced the encoder's training. If a document was in the training data, the encoder may produce an embedding that is unusually well-separated from non-relevant documents, a signal that an attacker can exploit.

Proposition 43 (Embedding Memorization Signal).

Let 𝒅𝒟train and 𝒅𝒟train be two documents with similar content. If the encoder has memorised training examples, then the embedding f𝜽(𝒅) will exhibit lower average cosine distance to the embeddings of its training-time hard negatives than f𝜽(𝒅) does to analogous candidates: (Memorization Signal)𝔼[min𝒅𝒩(𝒅)f𝜽(𝒅)f𝜽(𝒅)]>𝔼[min𝒅𝒩(𝒅)f𝜽(𝒅)f𝜽(𝒅)], where 𝒩() denotes the set of hard negatives. This gap provides a signal for membership inference.

Caution.

Retrieval-augmented generation introduces a novel privacy surface: the retrieved documents are injected into the LLM's context and may be reflected in the generated output. An adversary who can query a RAG system repeatedly may be able to reconstruct documents in the index through carefully crafted prompts, even if the system does not explicitly return retrieved passages to the user.

Memory and Retrieval: The Duality

The memory architectures studied in 24 are, at their core, retrieval systems. The concepts of engrams, working memory, and long-term consolidation all have direct retrieval-theoretic interpretations.

An engram in neuroscience is the physical trace of a memory in the brain. In a neural retrieval system, the analogue is the embedding of a stored item: a distributed representation that encodes the item's content in a form amenable to similarity-based lookup. Working memory corresponds to the retrieval system's active cache: the small set of items currently in use, maintained in a fast-access buffer (analogous to an LLM's context window). Long-term memory corresponds to the persistent index, vast in capacity but slower to access.

Key Idea.

Memory and retrieval are not separate capabilities but two aspects of a single process. To remember is to encode information in a form that supports later retrieval. To retrieve is to reconstruct a memory from partial cues. Every advance in memory architecture is simultaneously an advance in retrieval, and vice versa. The quality of a memory system is precisely the quality of its retrieval mechanism.

The memory hierarchy as a retrieval hierarchy.

Modern AI systems increasingly employ hierarchical memory, from registers (attention heads), through caches (KV caches), to main memory (external datastores), to disk (web-scale indices). This hierarchy mirrors the memory hierarchy in computer architecture, but the principles are the same: frequently accessed items are kept close (low latency, limited capacity), while the long tail resides in slower but larger stores.

Definition 73 (Retrieval Hierarchy).

A retrieval hierarchy is a sequence of retrieval systems (1,2,,K) with (Hierarchy)|1||2||K|,τ1τ2τK, where |k| is the capacity of the k-th level's index and τk is its access latency. A query is first attempted at level 1; on a miss, it cascades to level 2, and so on. The system's effective latency is τ=k=1Kτkj=1k1(1hj), where hj is the hit rate at level j.

Alignment Through Retrieval

The alignment techniques of 25 can be reframed as retrieval problems. When we train a model to produce helpful, harmless, and honest responses, we are training it to retrieve appropriate responses from the space of all possible continuations.

Example 67 (Safety Through Retrieval Filtering).

A RAG system can enforce safety constraints at the retrieval stage rather than (or in addition to) the generation stage. The retrieval index is curated to exclude harmful content, and a safety classifier re-ranks retrieved documents before they are passed to the generator: (Safety Filter)safe(𝒒)={𝒅(𝒒):Psafe(𝒅)>τsafe}, where Psafe(𝒅) is the probability that document 𝒅 is safe and τsafe is a threshold. This “retrieval firewall” provides a defence in depth: even if the generator is susceptible to jailbreaking, the retrieved context constrains the space of possible outputs.

Remark 70.

Reinforcement learning from human feedback (RLHF) can be viewed as learning a retrieval scoring function over the space of responses. The reward model r(𝒒,𝒚) assigns a score to each query-response pair (𝒒,𝒚), and the aligned model is trained to “retrieve” high-scoring responses: π(𝒚|𝒒)πref(𝒚|𝒒)exp(r(𝒒,𝒚)/β). This is precisely a Boltzmann retrieval distribution over the reference model's output space, temperature-scaled by β.

The Grand Unification: AI as Retrieval

We now arrive at the central claim of this section: all of AI can be viewed through the retrieval lens.

Theorem 18 (The Retrieval View of Learning).

Let f𝜽:𝒳𝒴 be any parameterised model trained on a dataset 𝒟={(𝒙i,yi)}i=1N. Then the forward pass f𝜽(𝒙) can be decomposed as:

  1. Query encoding: 𝒙 is mapped to an internal representation ϕ(𝒙).

  2. Retrieval: the model implicitly retrieves from a “compiled” index 𝜽 that encodes the training data in the parameters 𝜽.

  3. Decoding: the retrieved information is decoded to produce the output y.

Formally, for a model with final-layer weights 𝐖 and features ϕ(𝒙), the output f𝜽(𝒙)=𝐖ϕ(𝒙)=jwj𝒆j,ϕ(𝒙) is a weighted sum of inner products between the query representation and the “keys” stored in the weight matrix, precisely the mechanism of attention-based retrieval.

Sketch.

Consider a linear model f(𝒙)=𝐖𝒙 trained with ridge regression on 𝒟. The closed-form solution is 𝐖=𝐘𝐗(𝐗𝐗+λ𝐈)1, where 𝐗 stacks the training inputs and 𝐘 stacks the targets. For a test input 𝒙, the prediction is f(𝒙)=𝐘𝐗(𝐗𝐗+λ𝐈)1𝒙=i=1Nyiαi(𝒙), where αi(𝒙) is the “retrieval weight” assigned to training example i. This is explicitly a retrieval operation: the model retrieves a weighted combination of training labels, with weights determined by the similarity between 𝒙 and each training input. Deep networks implement the same principle in a transformed feature space.

This theorem reveals a profound truth: learning IS building a retrieval system. The training process takes raw experience and compiles it into an efficient index (the parameters 𝜽) that supports fast retrieval at inference time. Gradient descent is the indexing algorithm. The loss function specifies the retrieval quality metric. Regularisation controls the index's capacity and generalisation properties.

Grand unification: retrieval as the central operation connecting all major topics in this book. Each chapter contributes to and benefits from the retrieval paradigm. Arrows indicate the primary direction of influence: generative models provide retrieval features, NAS and evolutionary AI optimise retrieval architectures, continual learning uses retrieval for replay, privacy concerns arise from index membership, memory systems are retrieval systems, and alignment constrains what is retrieved.
The retrieval view of a forward pass. Each layer in a deep network performs implicit retrieval: the weight matrix 𝐖 stores a “compiled index” of patterns learned from training data, and the matrix-vector product 𝐖ϕ1(𝒙) retrieves relevant patterns via inner-product similarity. This perspective unifies feedforward computation with explicit retrieval mechanisms like attention and nearest-neighbour lookup.

Key Idea.

Retrieval is not a subfield of AI; it is the fundamental operation that underlies all of AI. Classification retrieves a label. Generation retrieves a sequence. Reinforcement learning retrieves an action. Every parameter in every model is a compiled memory trace, and every forward pass is a retrieval query against those traces. The differences between AI paradigms reduce to differences in how the index is built (training), how queries are formed (architecture), and what is retrieved (task).

Open Problems and Future Directions

The preceding sections have traced retrieval from its classical roots in library science through dense embeddings, cross-modal matching, and retrieval-augmented generation. Yet for all the progress, the most ambitious goals remain out of reach. In this section we survey the open problems that define the frontier of retrieval research, ranging from the engineering challenge of real-time updating to the philosophical question of whether retrieval and generation are ultimately the same thing.

Universal Retrieval

Current retrieval systems are specialists. CLIP retrieves images given text. ColBERT retrieves passages given queries. CLAP retrieves audio given descriptions. But no single model retrieves anything from any modality with human-level competence.

Definition 74 (Universal Retrieval Model).

A universal retrieval model is a function f:m𝒳md that maps inputs from any modality m in a modality set ={text,image,audio,video,3D,code,} into a shared embedding space such that, for any query 𝒒 of modality mq and any relevant item 𝒅 of modality md, (Universal)f(𝒒),f(𝒅)>f(𝒒),f(𝒅) for all irrelevant items 𝒅, regardless of the modalities mq and md.

What would a truly universal embedding look like? The challenge is not merely engineering but information-theoretic. Different modalities carry different kinds of information: text is symbolic and compositional, images are spatial and textural, audio is temporal and spectral. Can a single embedding space faithfully represent all these informational structures without destructive interference?

Proposition 44 (Information-Theoretic Limit on Universality).

Let ={1,,M} be a set of modalities with mutual information I(𝒳i;𝒳j)=Iij for all pairs. A universal embedding of dimension d can achieve perfect cross-modal retrieval between modalities i and j only if (Universal Limit)dIijlog2 bits of information can be encoded in the d-dimensional space. Since Iij varies across modality pairs, the minimum dimension for universal retrieval is dmaxi,jIij/log2.

Research 8.

Towards Universal Embeddings. Recent models like Gemini Embedding and ImageBind take steps towards universality by aligning multiple modalities through shared training. Key open questions include:

  1. Does the modality gap (the systematic offset between modality-specific clusters in embedding space) vanish as model size increases, or is it a fundamental geometric constraint?

  2. Can modality-specific adapters (lightweight modules that transform modality-specific features into the shared space) achieve universality more efficiently than end-to-end training?

  3. What is the optimal curriculum for training a universal model: simultaneous multi-modal training, sequential modality addition, or a hierarchical approach that first learns modality-specific representations and then aligns them?

Real-Time Updating

The world changes continuously, but retrieval indices do not. An LLM's knowledge is frozen at its training cutoff. A dense retrieval index must be rebuilt when new documents arrive. This temporal mismatch is one of the most pressing practical problems in retrieval.

The news problem.

Consider a question-answering system asked about an event that occurred one hour ago. The LLM has never seen this event. The retrieval index may not yet contain articles about it. Even if articles exist on the web, the system must crawl, index, and embed them before they become retrievable. The end-to-end latency from event occurrence to retrievability defines the system's temporal resolution.

Definition 75 (Temporal Resolution).

The temporal resolution of a retrieval system is the minimum time Δt between the creation of a document 𝒅 and the first moment at which 𝒅 can be returned in response to a relevant query. Formally, (Temporal Resolution)Δt(𝒅)=inf{ttcreate(𝒅):𝒅(𝒒,t) for some relevant 𝒒}, where (𝒒,t) is the retrieval result set at time t.

Streaming indexing at scale.

Reducing Δt requires streaming indexing: continuously incorporating new documents into the index without full rebuilds. For sparse indices (BM25), this is relatively straightforward because the inverted index supports incremental updates. For dense indices, the challenge is more severe: adding a new document requires computing its embedding (a forward pass through a large model) and inserting it into an ANN index that may need periodic rebalancing.

Example 68 (Streaming Dense Retrieval Pipeline).

A production streaming pipeline might operate as follows:

  1. Ingest: new documents arrive from a message queue (e.g., Kafka) at rates of 104106 documents per second.

  2. Embed: a fleet of GPU workers computes embeddings in batches, achieving throughput of 103 documents per GPU per second.

  3. Insert: embeddings are appended to a buffer index that supports exact search.

  4. Merge: periodically (every minutes to hours), the buffer index is merged into the main ANN index via re-clustering or graph augmentation.

  5. Query: at query time, results from the main index and the buffer index are merged and re-ranked.

The temporal resolution is bounded by the embed latency plus the buffer search latency, typically seconds to minutes.

Compositional Retrieval

Humans naturally compose retrieval queries from multiple concepts: “find me a sunset like this photo but over the ocean” or “a paper that combines the method from Smith et al. with the dataset from Lee et al.” Current retrieval systems struggle with such compositional queries because embeddings capture holistic similarity rather than compositional structure.

Definition 76 (Compositional Query).

A compositional query is a tuple 𝒒=(c1,c2,,cK,r1,r2,,rK) where each ck is a concept (possibly from a different modality or reference item) and each rk{include,exclude,modify} specifies how the concept should relate to the desired result. A retrieval system supports compositional queries if it can find items that satisfy all constraints simultaneously.

Addressing compositional retrieval requires moving beyond single-vector representations. Promising directions include multi-vector representations (like ColBERT's token-level embeddings), set-based retrieval where queries and documents are represented as sets of concept vectors, and neuro-symbolic approaches that decompose the query into a structured program executed against the index.

Causal Retrieval

Standard retrieval optimises for relevance: the retrieved documents should be topically related to the query. But relevance is not causation. In many applications, what we actually want is documents that would cause the right downstream outcome.

Definition 77 (Causal Retrieval).

Given a query 𝒒, a set of candidate documents 𝒞, and a downstream task with outcome Y, the causal retrieval objective is to select documents 𝒅 that maximise the causal effect on Y: (Causal)𝒅=arg max𝒅𝒞𝔼[Y|do(context=𝒅),𝒒]𝔼[Y|do(context=),𝒒], where do() denotes a causal intervention in the sense of Pearl's do-calculus.

The distinction matters enormously for RAG systems. A document may be highly relevant to the query (high cosine similarity) but actually cause the LLM to produce a worse answer, perhaps because it contains plausible-sounding misinformation or because it confuses the model by introducing conflicting evidence. Causal retrieval asks: if we intervene by providing this document as context, does the answer improve?

Research 9.

From Relevance to Causation in RAG. Transitioning from relevance-based to causal retrieval requires:

  1. Counterfactual evaluation: measuring how the answer changes when a document is included versus excluded. This requires evaluating the LLM twice per document, which is expensive but provides a direct estimate of causal effect.

  2. Causal scoring models: training a lightweight model to predict the causal effect of a document without running the full LLM, analogous to a cross-encoder re-ranker but trained on causal rather than relevance labels.

  3. Confounding control: in observational data (logs of past RAG interactions), the retrieved documents are correlated with query difficulty, creating confounding. Causal inference techniques (propensity scoring, instrumental variables) are needed to estimate causal effects from observational data.

Retrieval with Reasoning

Many real-world information needs require multi-step reasoning over multiple retrieved documents. “What is the GDP of the country where the inventor of the telephone was born?” requires retrieving the inventor (Alexander Graham Bell), his birthplace (Edinburgh, Scotland, UK), and the UK's GDP, a chain of three retrieval steps where each step depends on the result of the previous one.

Current multi-hop retrieval systems decompose such queries into sub-queries and retrieve iteratively, but they lack the ability to plan the retrieval strategy in advance or to backtrack when an intermediate retrieval leads to a dead end. Integrating retrieval with the planning and reasoning capabilities of LLMs is a key open challenge.

Example 69 (Retrieval over Knowledge Graphs).

A knowledge graph 𝒢=(𝒱,) with entity nodes 𝒱 and relation edges supports structured multi-hop retrieval. Given a query, the system must find a path (v1,r1,v2,r2,,vk) in the graph that answers the question. Dense retrieval can be combined with graph traversal by embedding both entities and relations in a shared space and using beam search over the graph, with the beam scored by embedding similarity to the query.

Privacy-Preserving Retrieval

Can we search an index without revealing the query? Can we build an index without revealing the documents? These questions define the field of privacy-preserving retrieval, which sits at the intersection of information retrieval and cryptography.

Definition 78 (Private Information Retrieval (PIR)).

A private information retrieval protocol allows a user to retrieve an item from a database without the server learning which item was retrieved. Formally, the server holds a database 𝒟=(d1,,dN) and the user wants to retrieve di for some index i. The protocol satisfies privacy if, for any two indices ij, the server's view is computationally indistinguishable: (PIR)Viewserver(i)cViewserver(j).

Classical PIR protocols work for exact retrieval by index, but extending them to similarity-based retrieval (where the server must compute distances without knowing the query) is extremely challenging. Homomorphic encryption allows computation on encrypted data but incurs orders-of-magnitude overhead. Secure multi-party computation distributes the index across non-colluding servers. Both approaches remain far too slow for web-scale retrieval.

Retrieval for Embodied Agents

A robot operating in a kitchen has accumulated hours of experience: grasping mugs, pouring liquids, opening cabinets. When confronted with a new task (e.g., “make coffee”), it must retrieve relevant past experiences and adapt them to the current situation. This is episodic retrieval in the sense of Tulving [36]: retrieving specific episodes from autobiographical memory, not just semantic facts.

Definition 79 (Episodic Retrieval for Embodied Agents).

Let ={e1,e2,,eT} be an agent's experience buffer, where each episode et=(st(1),at(1),,st(H),at(H),Rt) contains a sequence of states s, actions a, and a cumulative reward Rt. Given a new task specification τ, episodic retrieval selects episodes that maximise the transfer benefit: (Episodic)=arg max𝒮,|𝒮|kJ(π𝒮,τ)J(π,τ), where π𝒮 is the policy conditioned on the retrieved episodes and J(π,τ) is the expected return of policy π on task τ.

The challenges of embodied retrieval include the high dimensionality of experience (video, proprioception, force feedback), the need for temporal alignment (the relevant part of an episode may be a brief sub-sequence), and the requirement for real-time operation (the robot cannot pause for minutes while searching its memory).

Remark 71.

Biological episodic retrieval, as studied by Tulving [36], is characterised by “mental time travel”: the subjective re-experiencing of a past event. Current embodied AI systems lack this phenomenological dimension, but they increasingly replicate its functional role: selecting and replaying past experiences to guide present action. The gap between functional and phenomenological episodic memory remains one of the deepest puzzles at the intersection of AI and cognitive science.

The Generation-Retrieval Spectrum

Is generation just retrieval from an implicit, continuous index? Is retrieval just constrained generation? As models grow more powerful, the boundary between generation and retrieval dissolves.

A generative model like GPT-4 can be viewed as a retrieval system over its training data, where the “retrieval” is mediated by billions of parameters rather than an explicit index. Conversely, a retrieval system that returns a verbatim passage is performing a degenerate form of generation: it “generates” output by copying from its index.

Proposition 45 (Generation-Retrieval Duality).

Let pgen(𝒚|𝒒) be a generative model and pret(𝒚|𝒒)=i=1Nwi(𝒒)δ(𝒚𝒅i) be a retrieval model over a corpus {𝒅1,,𝒅N} with query-dependent weights wi(𝒒). As N with the corpus approaching the support of the true data distribution, and as the retrieval weights converge to the true conditional probabilities, we have pret(𝒚|𝒒)pdata(𝒚|𝒒)pgen(𝒚|𝒒) in distribution. That is, a sufficiently powerful retrieval system and a sufficiently powerful generative model converge to the same distribution.

This duality suggests that the “right” point on the generation-retrieval spectrum depends not on fundamental capability differences but on practical considerations: latency, controllability, attribution, freshness, and privacy.

Example 70 (Points on the Spectrum).

Different systems occupy different positions on the generation-retrieval spectrum:

  • Pure retrieval (BM25 returning a document): pret with N fixed items, zero generation.

  • Extractive QA (highlighting a span in a retrieved passage): mostly retrieval with minimal generation (selecting start/end positions).

  • RAG: retrieval provides context, generation synthesises an answer. The balance depends on the faithfulness constraint: strict faithfulness pushes towards retrieval, creative summarisation pushes towards generation.

  • kNN-LM (interpolating between a language model and nearest-neighbour retrieval): an explicit convex combination of generation and retrieval probabilities.

  • Pure generation (GPT-4 answering from parameters): pgen with no explicit index, all information compiled into weights.

As models and indices both grow, the optimal point on this spectrum shifts dynamically based on the query, the available corpus, and the application's requirements for attribution and freshness.

Frontier Open Problems

We conclude with a collection of open problems that push the boundaries of what retrieval could become.

Predictive retrieval: retrieving from the future.

Can a retrieval system anticipate what information a user will need before they ask for it? This is not as fantastical as it sounds. Predictive caching in web systems pre-fetches pages that users are likely to visit. Extending this to semantic retrieval requires modelling user intent trajectories: given the sequence of past queries, predict the next information need and pre-retrieve relevant documents.

Definition 80 (Predictive Retrieval).

Given a user's query history (𝒒1,𝒒2,,𝒒t), a predictive retrieval system maintains a pre-fetched cache 𝒞t+1 such that (Predictive)P((𝒒t+1)𝒞t+1)1ϵ, where (𝒒t+1) is the result set for the (as yet unknown) next query and ϵ is a target miss probability.

Biological neural retrieval.

Can biological neural networks be queried as retrieval systems? Neuroscientists can now read neural activity patterns with increasing fidelity using fMRI, EEG, and neural probes. If we view the brain's neural code as an embedding space, can we perform nearest-neighbour retrieval against it? That is, given a stimulus, can we find the stored memory whose neural representation is most similar? Early work on neural decoding (reconstructing images from brain activity) suggests that the answer is tentatively “yes,” but the resolution and speed of current measurement techniques remain severe bottlenecks.

Thermodynamic limits of retrieval.

What is the minimum energy required for one retrieval operation? Landauer's principle establishes that erasing one bit of information requires at least kBTln2 joules of energy, where kB is Boltzmann's constant and T is temperature. Retrieval does not erase information, but it does require reading it.

Proposition 46 (Energy Lower Bound for Retrieval).

Consider a retrieval system with an index of N items, each described by b bits. Under the assumption that retrieval requires reading at least log2N bits to identify the correct item (an information-theoretic minimum for selection from N alternatives), the minimum energy per retrieval operation at temperature T is (Landauer)EminkBTln2log2N. At room temperature (T=300K), this gives Emin2.87×1021log2N joules. For a web-scale index with N=1012, Emin1.1×1019 joules per retrieval. Current systems consume roughly 103 joules per retrieval, leaving a gap of 1016 between physical limits and engineering practice.

Self-improving retrieval.

Can we build a retrieval system that improves itself through use? Every query provides implicit feedback about the index structure: queries that return good results validate the current embeddings, while queries that fail reveal deficiencies. A truly self-improving system would use this feedback to continuously refine its embeddings, re-organize its index, and identify gaps in its corpus, all without human intervention.

Research 10.

Top 10 Open Problems in Retrieval. We summarise the frontier in a prioritised list:

  1. Universal embedding: a single model for all modalities and all retrieval tasks.

  2. Real-time dense indexing: sub-second temporal resolution for streaming document corpora.

  3. Compositional retrieval: faithful handling of multi-concept, multi-constraint queries.

  4. Causal retrieval: selecting documents that cause correct downstream outcomes, not just relevant ones.

  5. Privacy-preserving similarity search: efficient protocols for searching encrypted indices.

  6. Self-improving retrieval: systems that learn from every query without explicit supervision.

  7. Retrieval with planning: multi-hop retrieval that plans a search strategy before executing it.

  8. Retrieval for embodied AI: real-time episodic memory for robots and physical agents.

  9. Energy-efficient retrieval: closing the 1016× gap between physical limits and practice.

  10. Retrieval-generation unification: a single architecture that seamlessly interpolates between verbatim retrieval and free-form generation.

Conjecture 4 (The Universality Conjecture).

Let f𝜽:m𝒳md be an embedding model trained on data from all modalities with contrastive learning. As the training data |𝒟| and the embedding dimension d (with d=o(|𝒟|)), the embedding function converges to a universal retrieval function: for any pair of semantically related items (𝒙,𝒙) from any modalities and any pair of unrelated items (𝒙,𝒙), (Universality)f𝜽(𝒙),f𝜽(𝒙)f𝜽(𝒙),f𝜽(𝒙)Δ>0 almost surely, where Δ is a universal separation margin that depends only on the semantic relationship, not on the modalities involved.

If true, this conjecture implies that there exists a “Platonic” embedding space in which all human-meaningful concepts have well-defined locations, and sufficiently powerful models will discover it regardless of training details.

Remark 72.

The universality conjecture connects to the Platonic representation hypothesis: the observation that large models trained on different data and with different objectives tend to converge to similar internal representations. If this convergence extends to retrieval embeddings, it suggests that the structure of human knowledge imposes a unique (up to rotation) geometry on any sufficiently expressive embedding space.

Historical Timeline

The history of retrieval stretches from the clay tablets of ancient Sumeria to the multimodal embedding models of the present day. In this section we trace the key milestones, organised into five eras that reflect fundamental shifts in how humans and machines find information.

Era I: Manual Retrieval (Antiquity–1945)

Historical Note.

c. 3000 BCE – Sumerian clay tablets. The earliest known catalogues: lists of tablets organised by subject, stored in the temple libraries of Nippur and Ur. These proto-indices represent humanity's first systematic attempt to organise recorded knowledge for later retrieval.

Historical Note.

c. 300 BCE – The Library of Alexandria. Callimachus of Cyrene creates the Pinakes, a 120-scroll catalogue of the Library's holdings, organised by genre and author. The Pinakes is the first large-scale bibliographic index: a metadata layer that enables retrieval without exhaustive search through the physical collection.

Historical Note.

1876 – Dewey Decimal Classification. Melvil Dewey publishes his decimal classification system, assigning hierarchical numeric codes to subjects. The system transforms library retrieval from an art (knowing where the librarian shelved a book) into a systematic procedure (look up the code, find the shelf). The Dewey system is, in modern terms, a discrete embedding: each book is mapped to a point in a hierarchical code space, and retrieval is a nearest-code lookup.

Historical Note.

1945 – Vannevar Bush's Memex. In his landmark essay “As We May Think,” Vannevar Bush describes the Memex: a hypothetical desk-sized device that stores a person's books, records, and communications on microfilm and allows associative linking between items. The Memex anticipates hypertext, the web, and modern retrieval-augmented systems. Bush's key insight is that retrieval should follow associative trails rather than rigid hierarchical classifications, an idea that resonates with modern dense retrieval where similarity-based lookup replaces keyword matching.

Era II: Classical Information Retrieval (1945–2000)

Historical Note.

1957 – Luhn's automatic indexing. Hans Peter Luhn at IBM proposes using word frequency statistics for automatic document indexing and retrieval, establishing the statistical approach to IR that would dominate for decades.

Historical Note.

1960 – Maron and Kuhns's probabilistic retrieval. M. E. Maron and J. L. Kuhns publish “On Relevance, Probabilistic Indexing, and Information Retrieval,” introducing the idea that retrieval should be framed as probabilistic inference: given a query, estimate the probability that each document is relevant. This probabilistic framing becomes the foundation of modern retrieval theory [1].

Historical Note.

1972 – Salton's TF-IDF. Gerard Salton and colleagues develop the vector space model and the TF-IDF weighting scheme, representing documents and queries as vectors in a term space. The cosine similarity between these vectors provides a ranking. This is the first embedding-based retrieval system, albeit with sparse, hand-crafted embeddings.

Historical Note.

1977 – Salton's SMART system. The SMART (System for the Mechanical Analysis and Retrieval of Text) system, developed by Salton at Cornell, becomes the standard experimental platform for IR research. SMART introduces many techniques still in use: relevance feedback, query expansion, and systematic evaluation using precision-recall curves.

Historical Note.

1988 – Deerwester et al.'s Latent Semantic Indexing. Scott Deerwester and colleagues introduce LSI, which applies singular value decomposition to the term-document matrix, projecting documents into a low-dimensional “latent semantic” space. LSI is the first dense retrieval method: documents are represented as dense vectors rather than sparse term vectors. The key insight is that dimensionality reduction can capture semantic similarity that keyword matching misses.

Historical Note.

1992 – Robertson and Walker's BM25. Stephen Robertson and colleagues develop the Okapi BM25 ranking function, which refines TF-IDF using probabilistic models of term frequency saturation and document length normalisation. BM25 becomes the most widely used retrieval function in practice and remains competitive with neural methods on many benchmarks three decades later.

Historical Note.

1992 – The TREC evaluation conference. The Text REtrieval Conference (TREC), organised by NIST, establishes standardised benchmarks, relevance judgements, and evaluation metrics for IR. TREC transforms information retrieval from a field of anecdotal system comparisons into a rigorous experimental science.

Historical Note.

1998 – Brin and Page's PageRank. Sergey Brin and Larry Page develop PageRank, which ranks web pages by the structure of the hyperlink graph rather than content alone. PageRank demonstrates that retrieval quality depends not only on query-document matching but on global properties of the corpus, an insight that foreshadows the graph-based reasoning of modern retrieval systems.

Era III: Learning to Rank (2000–2018)

Historical Note.

2002 – Joachims's RankSVM. Thorsten Joachims introduces RankSVM, which learns a ranking function from pairwise preferences using support vector machines. This marks the beginning of the learning-to-rank paradigm: rather than hand-crafting a scoring function, learn it from data.

Historical Note.

2007 – LambdaMART. Christopher Burges and colleagues develop LambdaMART, combining gradient-boosted decision trees with the LambdaRank framework. LambdaMART achieves state-of-the-art results on web search ranking benchmarks and becomes the backbone of commercial search engines for the next decade.

Historical Note.

2013 – Mikolov et al.'s word2vec. Tomas Mikolov and colleagues introduce word2vec, learning dense word embeddings from large text corpora using simple neural networks. Word2vec demonstrates that neural networks can learn meaningful semantic representations: the famous kingman+womanqueen analogy shows that the embedding space captures relational structure. Word2vec embeddings quickly find application in document retrieval as an alternative to sparse TF-IDF vectors.

Historical Note.

2017 – Vaswani et al.'s Transformer. The Transformer architecture, built entirely on self-attention, achieves state-of-the-art results on machine translation and becomes the foundation for all subsequent advances in neural retrieval. The key innovation for retrieval is the attention mechanism itself: a differentiable retrieval operation over key-value pairs [39].

Era IV: Dense Retrieval Revolution (2018–2022)

Historical Note.

2018 – Devlin et al.'s BERT. BERT (Bidirectional Encoder Representations from Transformers) demonstrates that pre-training a transformer on masked language modelling produces representations that transfer to virtually any NLP task, including retrieval. BERT's contextual embeddings capture word sense and semantic nuance that static embeddings like word2vec cannot, enabling a new generation of neural retrieval models.

Historical Note.

2020 – Karpukhin et al.'s DPR. Dense Passage Retrieval (DPR) trains separate BERT encoders for queries and passages using contrastive learning, demonstrating that dense retrieval can outperform BM25 on open-domain question answering. DPR establishes the bi-encoder paradigm that becomes the standard architecture for dense retrieval.

Historical Note.

2020 – Lewis et al.'s RAG. The Retrieval-Augmented Generation (RAG) framework combines a dense retriever with a sequence-to-sequence generator, allowing the model to ground its outputs in retrieved evidence. RAG demonstrates that retrieval can compensate for the limitations of parametric memory, reducing hallucination and enabling knowledge-intensive tasks that pure generative models struggle with.

Historical Note.

2021 – Radford et al.'s CLIP. CLIP (Contrastive Language-Image Pre-training) learns a shared embedding space for text and images by training on 400 million image-text pairs from the web. CLIP enables zero-shot cross-modal retrieval: given a text description, find the matching image, or vice versa. The model demonstrates that contrastive learning at scale can bridge the “modality gap” between vision and language.

Historical Note.

2021 – Khattab and Zaharia's ColBERT. ColBERT introduces late interaction: instead of compressing queries and documents into single vectors, it retains token-level embeddings and computes relevance via MaxSim, the sum of maximum similarities between query tokens and document tokens. This multi-vector approach achieves cross-encoder quality at bi-encoder-like speed.

Historical Note.

2022 – Borgeaud et al.'s RETRO. RETRO (Retrieval-Enhanced Transformer) augments a language model with a frozen retrieval index of trillions of tokens, allowing a smaller model to match the performance of models 25 times its size. RETRO demonstrates that retrieval can substitute for parameters, suggesting a fundamental trade-off between model size and index size.

Era V: Generative Retrieval and Beyond (2022–Present)

Historical Note.

2022 – Tay et al.'s Differentiable Search Index. The Differentiable Search Index (DSI) eliminates the explicit index entirely: given a query, the model directly generates the document identifier using an autoregressive decoder. This “generative retrieval” paradigm stores the entire corpus in the model's parameters, blurring the line between retrieval and generation.

Historical Note.

2023 – The RAG explosion. Following ChatGPT's release, retrieval-augmented generation becomes the dominant paradigm for building knowledge-grounded AI systems. Frameworks like LangChain, LlamaIndex, and Haystack make RAG accessible to practitioners, while research advances including Self-RAG (which teaches models to decide when to retrieve), CRAG (corrective RAG), and Adaptive-RAG push the frontier of retrieval-generation integration.

Historical Note.

2024 – Multimodal retrieval at scale. Models like Gemini and GPT-4V incorporate retrieval capabilities across text, image, audio, and video modalities. Multimodal embedding models (e.g., Nomic Embed Vision, Jina CLIP v2) enable unified cross-modal search. The dream of a universal retrieval system comes closer to reality.

Historical Note.

2024 – Matryoshka representation learning. Kusupati et al. introduce Matryoshka embeddings, where a single model produces embeddings at multiple granularities: the first d dimensions of a d-dimensional embedding form a valid (but less expressive) embedding at dimension d. This enables adaptive retrieval: use low dimensions for fast candidate generation and full dimensions for precise re-ranking.

Historical Note.

2025 – Agentic retrieval and self-improving systems. Retrieval systems become components of autonomous agents that decide what to retrieve, when to retrieve, and how to use the results. Systems like the AI Scientist (31) use retrieval to survey the literature before generating hypotheses. Early self-improving retrieval systems use query logs to continuously refine their embeddings and index structures without human supervision.

A timeline of retrieval milestones, from the Library of Alexandria to agentic retrieval. The five eras reflect fundamental paradigm shifts: from manual cataloguing (Era I) through statistical methods (Era II), machine-learned ranking (Era III), neural dense retrieval (Era IV), to the current generative and agentic era (Era V). Each transition was driven by an increase in the scale of available data and computation.

Exercises

Standard Exercises

Exercise 85 (BM25 by Hand).

Consider a corpus of N=5 documents with the following term frequencies for the query “neural retrieval”:

Doctf(neural)tf(retrieval)|doc|Relevant?
d135120Yes
d20280No
d310150No
d423100Yes
d50090No

  1. Compute the BM25 score for each document using k1=1.2, b=0.75, and the average document length L=108. Use the standard IDF formula IDF(t)=logNn(t)+0.5n(t)+0.5 where n(t) is the number of documents containing term t.

  2. Rank the documents by BM25 score. Does the ranking agree with the relevance labels?

  3. How does the ranking change if you set b=0 (no length normalisation)? Explain intuitively why.

Exercise 86 (nDCG Computation).

A retrieval system returns documents in the following order for a query, with relevance grades on a scale of 0–3:

Position123456789
Relevance320130021

  1. Compute DCG@5 using the formula DCG@k=i=1k2reli1log2(i+1).

  2. Compute the ideal DCG@5 (IDCG@5) and hence nDCG@5.

  3. Prove that nDCG@k[0,1] for any ranking and any k.

  4. A colleague argues that nDCG is flawed because it does not penalise the system for returning irrelevant results. Is this criticism valid? Propose a modified metric that addresses it.

Exercise 87 (Contrastive Loss Derivation).

Consider the InfoNCE loss for dense retrieval: =logexp(f(𝒒),f(𝒅+)/τ)exp(f(𝒒),f(𝒅+)/τ)+j=1Kexp(f(𝒒),f(𝒅j)/τ).

  1. Show that as τ0+, the loss converges to an indicator function: 0 if 𝒅+ has the highest similarity to 𝒒, and otherwise.

  2. Show that as τ, the loss converges to log(K+1) regardless of the similarities. Interpret this result.

  3. Compute the gradient f(𝒒) and show that it pushes the query embedding towards the positive and away from negatives, with forces proportional to the softmax weights.

  4. Derive the connection between InfoNCE and a lower bound on mutual information I(𝒒;𝒅+). Hint: use the variational lower bound on MI from [40].

Exercise 88 (ANN Algorithm Analysis).

Consider a dataset of N=106 vectors in 128.

  1. Brute force: compute the number of floating-point operations required for exact nearest-neighbour search. At a throughput of 1012 FLOPS, what is the query latency?

  2. IVF: suppose we partition the dataset into C=1000 clusters using k-means. If we probe nprobe=10 clusters at query time, what is the expected speedup over brute force? Under what conditions on the data distribution does this speedup come with minimal recall loss?

  3. HNSW: the Hierarchical Navigable Small World graph has an expected search complexity of O(logNd). Compute the expected number of distance computations for our dataset. Compare with brute force and IVF.

  4. Product Quantization: suppose we split each 128-dimensional vector into 16 sub-vectors of 8 dimensions each, and quantize each sub-vector using k=256 centroids. How many bits are needed to store one vector? What is the compression ratio compared to 32-bit floats?

Exercise 89 (Cross-Modal Retrieval Design).

You are designing a cross-modal retrieval system that retrieves relevant audio clips given text queries (e.g., “a dog barking in the rain”).

  1. Describe the architecture of a bi-encoder system for this task. What pre-trained models would you use for the text and audio encoders? How would you handle the different sequence lengths of text (tens of tokens) and audio (thousands of frames)?

  2. Design a training data pipeline. Where would you obtain paired text-audio data? How would you handle noisy or misaligned pairs?

  3. Propose a negative sampling strategy. Why are random negatives insufficient for this task, and how would you mine hard negatives?

  4. Evaluate your system on two metrics: Recall@10 and Median Rank. Explain why both metrics are needed and what each captures.

Exercise 90 (RAG Pipeline Design).

Design a RAG system for answering questions about a company's internal documentation (10,000 documents, ranging from policy manuals to engineering specifications).

  1. Describe the indexing pipeline: document chunking strategy, embedding model selection, and index construction. Justify your chunk size and overlap choices.

  2. Design the query pipeline: query encoding, retrieval (top-k selection), re-ranking, and prompt construction. How many retrieved passages should be included in the LLM's context?

  3. The system must handle two types of queries: (i) factual (“What is the vacation policy?”) and (ii) analytical (“How has our engineering process changed over the past three years?”). How would you adapt the pipeline for each type?

  4. Propose an evaluation framework. Define metrics for retrieval quality, generation quality, and end-to-end system quality. How would you detect and measure hallucination?

Exercise 91 (Information-Theoretic Analysis).

Consider a retrieval system with embedding dimension d and a corpus of N documents [4][37].

  1. If embeddings are unit vectors in d (i.e., they lie on the unit sphere 𝕊d1), what is the maximum number of vectors that can be packed such that all pairwise cosine similarities are at most ϵ? Use the sphere packing bound to derive an upper bound.

  2. Relate your answer to the capacity of the retrieval system: the maximum number of documents it can reliably distinguish. How does capacity scale with d?

  3. Prove that for any retrieval system using d-dimensional embeddings, the mutual information between the query and the retrieved document is bounded by I(𝒒;𝒅^)dlog2(1+SNR) where SNR is the signal-to-noise ratio in the embedding space.

  4. Using the result from (c), compute the minimum embedding dimension needed to reliably retrieve from a corpus of N=109 documents. Assume SNR=10.

Exercise 92 (Embedding Dimension Trade-offs).

You are deploying a dense retrieval system with a corpus of N=108 documents.

  1. Compute the total storage required for the embedding index at dimensions d{64,128,256,512,768,1024} using 32-bit floats. At what dimension does the index exceed 100 GB?

  2. The query latency for brute-force search scales as O(Nd). For an ANN index with O(dlogN) search cost, plot the latency as a function of d for N=108.

  3. Higher dimensions allow more expressive embeddings but require more training data to avoid overfitting. Derive a heuristic for the minimum training set size as a function of d, based on the assumption that we need at least cd training examples per class for c10.

  4. Quantisation can reduce storage: compare the storage and retrieval quality trade-offs for (i) float32, (ii) float16, (iii) int8, and (iv) binary quantisation. For each, compute the compression ratio and discuss the expected impact on recall.

Exercise 93 (Retrieval Evaluation Metrics).

  1. Prove that MAP (Mean Average Precision) is equivalent to the area under the interpolated precision-recall curve.

  2. Show that MRR (Mean Reciprocal Rank) is a special case of nDCG with binary relevance and k=. Hint: this is actually false. Explain why and characterise the precise relationship.

  3. Design a retrieval metric that captures both precision (the retrieved documents are relevant) and diversity (the retrieved documents cover different aspects of the query). Prove that your metric satisfies monotonicity (adding a relevant, diverse document cannot decrease the score).

Exercise 94 (Dense vs. Sparse Retrieval).

  1. Construct a specific query-document pair where BM25 succeeds but dense retrieval (DPR) fails. Explain the failure mode.

  2. Construct a specific query-document pair where DPR succeeds but BM25 fails. Explain what semantic understanding DPR captures that BM25 misses.

  3. A hybrid system combines BM25 and DPR scores: shybrid=αsBM2+(1α)sDPR. Describe how you would tune α and prove that the hybrid system's recall@k is at least max(recallBM2@k,recallDPR@k) when α is optimised.

Exercise 95 (Generative Retrieval).

Consider a Differentiable Search Index (DSI) trained on a corpus of N=100,000 documents, each assigned a unique identifier string.

  1. If document IDs are random 10-digit strings, the model must memorise N arbitrary sequences. Compute the minimum number of parameters needed to store this mapping, assuming each parameter contributes 2 bits of effective capacity.

  2. Propose a semantic ID scheme where similar documents receive similar IDs. How would you construct such IDs using hierarchical clustering?

  3. Analyse the failure modes of generative retrieval: when the model generates an invalid ID, when it generates a valid ID for the wrong document, and when it generates the right document's ID but the document is irrelevant. Which failure mode is most common in practice and why?

  4. Compare the computational cost of generative retrieval (autoregressive decoding of an ID) with dense retrieval (embedding + ANN search) for N{104,106,108}. At what N does dense retrieval become more efficient?

Exercise 96 (Retrieval-Augmented Fine-Tuning).

  1. Explain the difference between RAG (retrieval at inference time) and RAFT (retrieval-augmented fine-tuning, where retrieved documents are included during training). Under what conditions does RAFT outperform RAG?

  2. Design an experiment to measure the “retrieval dependency” of a RAFT-trained model: how much does its performance degrade when the retrieval component is removed at inference time?

  3. Propose a training curriculum that gradually reduces the quality of retrieved documents during fine-tuning, forcing the model to develop robustness to retrieval failures. How would you schedule this curriculum?

Exercise 97 (Multi-Vector Retrieval).

  1. In ColBERT's MaxSim operator, the relevance score is s(𝒒,𝒅)=i=1|𝒒|maxj=1|𝒅|𝒒i,𝒅j. Prove that MaxSim is an upper bound on the single-vector dot product: s(𝒒,𝒅)𝒒,𝒅|𝒒| where 𝒒 and 𝒅 are mean-pooled representations.

  2. Compute the storage overhead of multi-vector retrieval compared to single-vector retrieval. If the average document has 200 tokens and the embedding dimension is 128, what is the ratio of storage for ColBERT vs. a single-vector model?

  3. Propose a compression scheme for multi-vector representations that reduces storage while preserving MaxSim ranking quality.

Exercise 98 (Embedding Space Geometry).

  1. For unit-norm embeddings in d, derive the expected cosine similarity between two random vectors drawn uniformly from 𝕊d1. How does this expectation behave as d?

  2. The modality gap is the distance between the centroids of text and image embeddings in a CLIP model. If the gap is δ, show that the maximum achievable cross-modal recall is bounded by a function of δ and the within-modality variance σ2.

  3. Prove that the uniformity of embeddings on the hypersphere (measured by the log of the average pairwise Gaussian kernel) is maximised when embeddings are uniformly distributed, and interpret this in terms of retrieval capacity.

Exercise 99 (Query Expansion).

  1. Implement pseudo-relevance feedback (PRF): given a query, retrieve the top-k documents, extract the most frequent terms from those documents, and add them to the query. Describe the failure mode where PRF hurts performance (query drift).

  2. An LLM-based query expansion method generates hypothetical answers to the query (HyDE). Explain why embedding the hypothetical answer rather than the query can improve retrieval, using the geometry of the embedding space.

  3. Design an experiment to compare PRF, HyDE, and chain-of-thought query expansion on a benchmark of your choice. What metrics would you use?

Exercise 100 (Retrieval Fairness).

  1. Define two notions of fairness for retrieval systems: exposure fairness (all relevant documents receive proportional exposure) and group fairness (retrieval quality does not vary across demographic groups).

  2. Construct an example where optimising for nDCG leads to unfair exposure: a small number of highly relevant documents monopolise the top positions, while many moderately relevant documents receive no exposure.

  3. Propose a constrained optimisation formulation that maximises nDCG subject to a fairness constraint. Derive the Lagrangian and describe the trade-off between quality and fairness.

Challenge Problems

Challenge 1 (Retrieval for a Novel Modality).

Design a retrieval system for olfactory data (smell). Assume you have access to a dataset of 10,000 molecular structures paired with textual smell descriptions (e.g., “floral with hints of vanilla”).

  1. Propose a molecular encoder architecture. What input representation would you use: SMILES strings, molecular graphs, or 3D conformations? Justify your choice.

  2. Define the embedding space and training objective. Contrastive learning requires negative pairs; how would you sample “hard negatives” for smell (molecules that are structurally similar but smell different)?

  3. The relationship between molecular structure and perceived smell is notoriously complex and poorly understood. Discuss the fundamental limits of your system: what types of smell queries are likely to fail, and why?

  4. Extend your design to support cross-modal retrieval: given a smell description, retrieve a molecular structure, and vice versa. How would you evaluate this system given the subjective nature of smell perception?

Challenge 2 (Tighter Embedding Capacity Bound).

The capacity of an embedding-based retrieval system depends on the embedding dimension d, the number of items N, and the required separation margin γ.

  1. Prove that for unit-norm embeddings in d with cosine similarity, the maximum number of items that can be γ-separated (all pairwise similarities below γ) satisfies Nexp(cd(1γ2)) for a universal constant c>0. Hint: use a volume argument on spherical caps.

  2. Derive a lower bound on N showing that the exponential scaling in d is tight (up to constants in the exponent).

  3. Extend your bounds to the retrieval setting where each query has exactly one relevant document and the system must rank it in the top k. How does the capacity change as a function of k?

  4. Compare your theoretical bounds with the empirical performance of CLIP (dimension 512, trained on 400M pairs) and Gemini Embedding (dimension 3072). Are current models close to the capacity limit?

Challenge 3 (Modality Gap Experiment).

The modality gap is the systematic separation between modality clusters in a shared embedding space.

  1. Design an experiment to measure the modality gap in a pre-trained CLIP model. Define three quantitative measures of the gap: centroid distance, overlap coefficient, and cross-modal nearest-neighbour accuracy.

  2. Hypothesise three possible causes of the modality gap: (i) initialisation, (ii) training dynamics, (iii) inherent information asymmetry. For each, design an ablation experiment that would confirm or refute the hypothesis.

  3. Propose a training modification that reduces the modality gap without sacrificing retrieval quality. Implement and evaluate your proposal on a standard benchmark.

Challenge 4 (RAG Evaluation Metric).

Current RAG evaluation metrics either measure retrieval quality (recall, nDCG) or generation quality (BLEU, ROUGE, factual accuracy) but not both simultaneously.

  1. Propose a unified metric RAG-Score(𝒒,,𝒚)[0,1] that captures retrieval precision, generation faithfulness (the output is supported by retrieved documents), and hallucination rate (the output contains claims not in the documents).

  2. Prove that your metric satisfies the following desirable properties: (i) monotonicity in retrieval quality, (ii) monotonicity in faithfulness, (iii) it equals 1 if and only if the retrieval is perfect and the generation is fully faithful.

  3. Apply your metric to compare three RAG systems on a benchmark of your choice. Does your metric produce different rankings than existing metrics?

Challenge 5 (Computational Limits of Generative Retrieval).

Generative retrieval stores the entire corpus in model parameters.

  1. Derive a lower bound on the number of parameters needed to memorise a corpus of N documents, each of length L tokens from a vocabulary of size V. Use the information-theoretic argument that the model must store at least NLlog2V bits of information.

  2. Compare this lower bound with the actual parameter count of a DSI model for N=106, L=100, V=30,000. Is the DSI model parameter-efficient or parameter-wasteful?

  3. Analyse the scaling behaviour: as N grows, how must the model size grow to maintain constant retrieval accuracy? Compare with dense retrieval, where the model size is fixed and only the index grows.

  4. Prove that there exists a corpus size N beyond which dense retrieval is strictly more compute-efficient than generative retrieval for a given quality target. Estimate N for current model architectures.

Challenge 6 (Self-Improving Retrieval System).

Design a retrieval system that improves itself through use, without any explicit human feedback.

  1. Identify three sources of implicit feedback available from user interactions with a retrieval system: click-through data, dwell time, and reformulation patterns. For each, describe how to convert it into a training signal for the embedding model.

  2. Design a continuous learning loop: the system serves queries, collects implicit feedback, updates its embeddings, and re-indexes, all while maintaining service availability. Address the cold-start problem and the risk of feedback loops (the system reinforces its own biases).

  3. Prove that under certain conditions on the feedback signal, your system converges to a fixed point. Characterise the conditions under which the fixed point corresponds to the optimal retrieval function versus a degenerate solution.

  4. Analyse the alignment risks of a self-improving retrieval system. How could the system's objectives diverge from user interests? Propose safeguards.

Chapter Summary

This chapter has told a story that spans millennia. It began with Plato's doctrine of anamnesis, the idea that all learning is recollection, that to know something is to retrieve it from the soul's prior acquaintance with the Forms. It ends with Gemini's multimodal embeddings, where a single model maps text, images, audio, and video into a shared geometric space in which “retrieval” is a nearest-neighbour lookup and “knowledge” is a point in 3072.

Between Plato and Gemini lies a remarkable intellectual journey. Let us gather the key lessons.

From keywords to meaning.

The first great transition in retrieval was from lexical matching to semantic understanding. TF-IDF and BM25 retrieve documents that share words with the query. Dense retrievers like DPR and ColBERT retrieve documents that share meaning with the query, even when no words overlap. This transition was enabled by the convergence of three forces: large-scale pre-training (BERT), the contrastive learning framework (InfoNCE), and hardware capable of encoding billions of documents into dense vectors.

From unimodal to multimodal.

The second great transition was from text-only retrieval to cross-modal retrieval. CLIP showed that a shared embedding space could bridge vision and language. Subsequent models extended this to audio (CLAP), video, 3D shapes, code, and scientific data. The lesson is that meaning is modality-independent: a sunset looks the same whether you describe it in words, photograph it, or paint it, and a good embedding captures this invariance.

From retrieval to augmented generation.

The third great transition was the fusion of retrieval with generation. RAG showed that a retriever plus a generator is more than the sum of its parts: the retriever provides factual grounding, the generator provides fluent synthesis, and together they produce responses that are both accurate and natural. This fusion is not merely a trick but a reflection of a deep duality: retrieval and generation are two sides of the same coin, two strategies for transforming a query into a response.

From static to dynamic.

The fourth transition, still underway, is from static indices to living, adaptive retrieval systems. Future systems will update their indices in real time, learn from every query, and anticipate information needs before they are expressed. They will be not passive databases but active cognitive agents, reasoning about what to retrieve, when to retrieve it, and how to integrate it with existing knowledge.

The convergence of retrieval and generation.

Perhaps the deepest insight of this chapter is that retrieval and generation are converging. A generative model that has memorised its training data is performing implicit retrieval. A retrieval system that interpolates between stored items is performing implicit generation. The generation-retrieval duality (Proposition 45) makes this precise: as both systems approach the true data distribution, they become indistinguishable.

The practical consequence is that the choice between retrieval and generation is not a matter of fundamental capability but of engineering trade-offs: attribution (retrieval makes provenance explicit), freshness (retrieval accesses current information), efficiency (retrieval avoids redundant computation), and creativity (generation can produce novel combinations). The most powerful systems will seamlessly combine both, operating at whatever point on the retrieval-generation spectrum best serves each query.

Key takeaways by theme.

We organise the chapter's central lessons into five themes:

  1. Representation: the quality of retrieval is determined by the quality of the embedding. Contrastive learning, multi-vector representations, and Matryoshka embeddings represent three strategies for learning better representations, each with distinct trade-offs in capacity, granularity, and computational cost.

  2. Efficiency: web-scale retrieval demands sub-millisecond latency over billions of items. The ANN algorithms (IVF, HNSW, product quantisation) make this possible by trading exact correctness for speed, and the art lies in controlling the recall loss.

  3. Integration: retrieval is most powerful when integrated with generation (RAG), reasoning (multi-hop retrieval), and planning (agentic retrieval). The system that retrieves must also know when to retrieve, what to retrieve, and how to use what it finds.

  4. Evaluation: retrieval metrics (nDCG, MAP, recall) measure different aspects of quality. No single metric suffices, and the choice of metric shapes the system's behaviour through the optimisation objective.

  5. Universality: the boundaries between modalities, between retrieval and generation, and between memory and computation are dissolving. The trajectory of the field points towards universal systems that transcend these distinctions.

A philosophical reflection.

In the age of large language models, what does it mean to “know” something? If a model can retrieve the answer to any factual question, but stores none of the answers in its parameters, does it “know” the facts? Conversely, if a model has memorised a fact in its weights but cannot access it without the right prompt, does it “know” the fact?

Tulving's distinction between semantic memory (knowing that Paris is the capital of France) and episodic memory (remembering learning this fact) [36] offers a useful framework. A generative model has semantic knowledge compiled into its parameters. A retrieval-augmented model has episodic access to a corpus of specific documents. Neither alone captures the full richness of human knowledge, which integrates semantic understanding with episodic memory, contextual reasoning, and the ability to recognise the limits of one's own knowledge.

The retrieval systems of the future will move closer to this integration: not just finding relevant documents but understanding why they are relevant, how they relate to what is already known, and what further information is needed. In this sense, the story of retrieval is the story of intelligence itself: the ongoing quest to bridge the gap between what we know and what we need to know.

Key Idea.

The ultimate insight of this chapter can be stated simply: all intelligence is retrieval. Perception retrieves patterns from sensory input. Memory retrieves experiences from the past. Reasoning retrieves conclusions from premises. Creativity retrieves novel combinations from the space of possibilities. Language retrieves words from meaning. Even consciousness may be, as some philosophers have argued, the retrieval of a model of the self from the stream of experience. To build better retrieval systems is, in the deepest sense, to build better minds.

[heading=subbibliography]

References

  1. Introduction to Information Retrieval

    Christopher D. Manning, Prabhakar Raghavan, Hinrich Schutze

    Cambridge University Press · 2008

    BibTeX
    @book{manning2008ir,
      title        = {Introduction to Information Retrieval},
      author       = {Manning, Christopher D. and Raghavan, Prabhakar and Sch{\"u}tze, Hinrich},
      year         = {2008},
      publisher    = {Cambridge University Press},
      note         = {Available online (official companion site)}
    }

    Book

  2. TREC-8 Question Answering Track Report

    Ellen M. Voorhees

    Proceedings of TREC-8 · 1999

    BibTeX
    @inproceedings{voorhees1999trec8qa,
      title     = {{TREC}-8 Question Answering Track Report},
      author    = {Voorhees, Ellen M.},
      booktitle = {Proceedings of TREC-8},
      year      = {1999},
      note      = {MRR discussed as a scoring metric}
    }

    Conference paper

  3. Cumulated Gain-based Evaluation of IR Techniques

    Kalervo Jarvelin, Jaana Kekalainen

    ACM Transactions on Information Systems, vol. 20, no. 4, pp. 422-446 · 2002

    BibTeX
    @article{jarvelin2002ndcg,
      title   = {Cumulated Gain-based Evaluation of IR Techniques},
      author  = {J{\"a}rvelin, Kalervo and Kek{\"a}l{\"a}inen, Jaana},
      journal = {ACM Transactions on Information Systems},
      volume  = {20},
      number  = {4},
      pages   = {422--446},
      year    = {2002},
      doi     = {10.1145/582415.582418}
    }

    Journal article

  4. A mathematical theory of communication

    Claude Elwood Shannon

    The Bell System Technical Journal, vol. 27, no. 3, pp. 379-423 · 1948

    BibTeX
    @article{shannon1948mathematical,
      title={A mathematical theory of communication},
      author={Shannon, Claude Elwood},
      journal={The Bell System Technical Journal},
      volume={27},
      number={3},
      pages={379--423},
      year={1948},
      publisher={Nokia Bell Labs}
    }

    Journal article

  5. Term-weighting approaches in automatic text retrieval

    Gerard Salton, Christopher Buckley

    Information Processing & Management, vol. 24, no. 5, pp. 513-523 · 1988

    BibTeX
    @article{salton1988tfidf,
      title   = {Term-weighting approaches in automatic text retrieval},
      author  = {Salton, Gerard and Buckley, Christopher},
      journal = {Information Processing \& Management},
      volume  = {24},
      number  = {5},
      pages   = {513--523},
      year    = {1988},
      doi     = {10.1016/0306-4573(88)90021-0}
    }

    Journal article

  6. The Probabilistic Relevance Framework: BM25 and Beyond

    Stephen Robertson, Hugo Zaragoza

    Foundations and Trends in Information Retrieval, vol. 3, no. 4, pp. 333-389 · 2009

    BibTeX
    @article{robertson2009bm25,
      title   = {The Probabilistic Relevance Framework: {BM25} and Beyond},
      author  = {Robertson, Stephen and Zaragoza, Hugo},
      journal = {Foundations and Trends in Information Retrieval},
      volume  = {3},
      number  = {4},
      pages   = {333--389},
      year    = {2009}
    }

    Journal article

  7. Indexing by Latent Semantic Analysis

    Scott Deerwester, Susan T. Dumais, George W. Furnas, Thomas K. Landauer, Richard Harshman

    Journal of the American Society for Information Science, vol. 41, no. 6, pp. 391-407 · 1990

    BibTeX
    @article{deerwester1990lsi,
      title   = {Indexing by Latent Semantic Analysis},
      author  = {Deerwester, Scott and Dumais, Susan T. and Furnas, George W. and Landauer, Thomas K. and Harshman, Richard},
      journal = {Journal of the American Society for Information Science},
      volume  = {41},
      number  = {6},
      pages   = {391--407},
      year    = {1990},
      doi     = {10.1002/(SICI)1097-4571(199009)41:6<391::AID-ASI1>3.0.CO;2-9}
    }

    Journal article

  8. Latent Dirichlet Allocation

    David M. Blei, Andrew Y. Ng, Michael I. Jordan

    Journal of Machine Learning Research, vol. 3, pp. 993-1022 · 2003

    BibTeX
    @article{blei2003lda,
      title   = {Latent Dirichlet Allocation},
      author  = {Blei, David M. and Ng, Andrew Y. and Jordan, Michael I.},
      journal = {Journal of Machine Learning Research},
      volume  = {3},
      pages   = {993--1022},
      year    = {2003}
    }

    Journal article

  9. Learning Transferable Visual Models From Natural Language Supervision

    Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, et al.

    International Conference on Machine Learning · 2021

    BibTeX
    @article{radford2021clip,
      title={Learning Transferable Visual Models From Natural Language Supervision},
      author={Radford, Alec and Kim, Jong Wook and Hallacy, Chris and Ramesh, Aditya and Goh, Gabriel and Agarwal, Sandhini and Sastry, Girish and Askell, Amanda and Mishkin, Pamela and Clark, Jack and others},
      journal={International Conference on Machine Learning},
      year={2021}
    }

    Journal article

  10. MSR-VTT: A Large Video Description Dataset for Bridging Video and Language

    Jun Xu, Tao Mei, Ting Yao, Yong Rui

    Proceedings of CVPR, pp. 5288-5296 · 2016

    BibTeX
    @inproceedings{xu2016msr_vtt,
      title     = {{MSR-VTT}: A Large Video Description Dataset for Bridging Video and Language},
      author    = {Xu, Jun and Mei, Tao and Yao, Ting and Rui, Yong},
      booktitle = {Proceedings of CVPR},
      pages     = {5288--5296},
      year      = {2016}
    }

    Conference paper

  11. Localizing Moments in Video with Natural Language

    Lisa Anne Hendricks, Oliver Wang, Eli Shechtman, Josef Sivic, Trevor Darrell, Bryan Russell

    Proceedings of ICCV, pp. 5803-5812 · 2017

    BibTeX
    @inproceedings{anne2017localizing,
      title     = {Localizing Moments in Video with Natural Language},
      author    = {Hendricks, Lisa Anne and Wang, Oliver and Shechtman, Eli and Sivic, Josef and Darrell, Trevor and Russell, Bryan},
      booktitle = {Proceedings of ICCV},
      pages     = {5803--5812},
      year      = {2017}
    }

    Conference paper

  12. Visual Instruction Tuning

    Haotian Liu, Chunyuan Li, Qingyang Wu, Yong Jae Lee

    Advances in Neural Information Processing Systems (NeurIPS) · 2024

    BibTeX
    @inproceedings{liu2024visual,
      title     = {Visual Instruction Tuning},
      author    = {Liu, Haotian and Li, Chunyuan and Wu, Qingyang and Lee, Yong Jae},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2024},
      note      = {LLaVA; NeurIPS 2023 oral}
    }

    Conference paper

  13. AudioCaps: Generating Captions for Audios in the Wild

    Chris Dongjoo Kim, Byeongchang Kim, Hyunmin Lee, Gunhee Kim

    Proceedings of NAACL-HLT · 2019

    BibTeX
    @inproceedings{audiocaps2019,
      title     = {{AudioCaps}: Generating Captions for Audios in the Wild},
      author    = {Kim, Chris Dongjoo and Kim, Byeongchang and Lee, Hyunmin and Kim, Gunhee},
      booktitle = {Proceedings of NAACL-HLT},
      year      = {2019}
    }

    Conference paper

  14. Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation

    Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Marianna Nezhurina, Taylor Berg-Kirkpatrick, Shlomo Dubnov

    arXiv:2211.06687 · 2022

    BibTeX
    @misc{wu2022laionaudio,
      title        = {Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation},
      author       = {Wu, Yusong and Chen, Ke and Zhang, Tianyu and Hui, Yuchen and Nezhurina, Marianna and Berg-Kirkpatrick, Taylor and Dubnov, Shlomo},
      year         = {2022},
      howpublished = {arXiv:2211.06687},
      note         = {Often cited as ICASSP 2023 in downstream references}
    }

    Reference

  15. ImageBind: One Embedding Space To Bind Them All

    Rohit Girdhar, Alaaeldin El-Nouby, Zhuang Liu, Mannat Singh, Kalyan Vasudev Alwala, Armand Joulin, Ishan Misra

    Proceedings of CVPR · 2023

    BibTeX
    @inproceedings{girdhar2023imagebind,
      title     = {{ImageBind}: One Embedding Space To Bind Them All},
      author    = {Girdhar, Rohit and El-Nouby, Alaaeldin and Liu, Zhuang and Singh, Mannat and Alwala, Kalyan Vasudev and Joulin, Armand and Misra, Ishan},
      booktitle = {Proceedings of CVPR},
      year      = {2023}
    }

    Conference paper

  16. Gemini Embedding 2: Our first natively multimodal embedding model (blog announcement)

    Google

    rlhttps://blog.google/innovation-and-ai/models-and-research/gemini-models/gemini-embedding-2/ · 2026

    BibTeX
    @misc{gemini_embedding2_blog,
      title        = {Gemini Embedding 2: Our first natively multimodal embedding model (blog announcement)},
      author       = {{Google}},
      year         = {2026},
      howpublished = {\url{https://blog.google/innovation-and-ai/models-and-research/gemini-models/gemini-embedding-2/}},
      note         = {Accessed 2026-03-16}
    }

    Reference

  17. Gemini Embedding 2: Vertex AI model documentation

    Google Cloud

    rlhttps://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/embedding-2 · 2026

    BibTeX
    @misc{vertex_gemini_embedding2,
      title        = {Gemini Embedding 2: Vertex AI model documentation},
      author       = {{Google Cloud}},
      year         = {2026},
      howpublished = {\url{https://docs.cloud.google.com/vertex-ai/generative-ai/docs/models/gemini/embedding-2}},
      note         = {Accessed 2026-03-16}
    }

    Reference

  18. Embeddings: Gemini API documentation

    Google

    rlhttps://ai.google.dev/gemini-api/docs/embeddings · 2026

    BibTeX
    @misc{google_gemini_embeddings_doc,
      title        = {Embeddings: Gemini API documentation},
      author       = {{Google}},
      year         = {2026},
      howpublished = {\url{https://ai.google.dev/gemini-api/docs/embeddings}},
      note         = {Accessed 2026-03-16}
    }

    Reference

  19. Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision

    Chao Jia, Yinfei Yang, Ye Xia, Yi-Ting Chen, Zarana Parekh, Hieu Pham, Quoc V. Le, Yunhsuan Sung, et al.

    Proceedings of ICML · 2021

    BibTeX
    @inproceedings{jia2021align,
      title     = {Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision},
      author    = {Jia, Chao and Yang, Yinfei and Xia, Ye and Chen, Yi-Ting and Parekh, Zarana and Pham, Hieu and Le, Quoc V. and Sung, Yunhsuan and Li, Zhen and Duerig, Tom},
      booktitle = {Proceedings of ICML},
      year      = {2021},
      note      = {PMLR v139}
    }

    Conference paper

  20. Sigmoid Loss for Language Image Pre-Training

    Xiaohua Zhai, Basil Mustafa, Alexander Kolesnikov, Lucas Beyer

    Proceedings of ICCV · 2023

    BibTeX
    @inproceedings{zhai2023siglip,
      title     = {Sigmoid Loss for Language Image Pre-Training},
      author    = {Zhai, Xiaohua and Mustafa, Basil and Kolesnikov, Alexander and Beyer, Lucas},
      booktitle = {Proceedings of ICCV},
      year      = {2023}
    }

    Conference paper

  21. BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation

    Junnan Li, Dongxu Li, Caiming Xiong, Steven Hoi

    Proceedings of ICML · 2022

    BibTeX
    @inproceedings{li2022blip,
      title     = {{BLIP}: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation},
      author    = {Li, Junnan and Li, Dongxu and Xiong, Caiming and Hoi, Steven},
      booktitle = {Proceedings of ICML},
      year      = {2022},
      note      = {PMLR v162}
    }

    Conference paper

  22. CLAP: Learning Audio Concepts From Natural Language Supervision

    Benjamin Elizalde, Soham Deshmukh, Mahmoud Al Ismail, Huaming Wang

    arXiv:2206.04769 · 2022

    BibTeX
    @misc{elizalde2022clap,
      title        = {CLAP: Learning Audio Concepts From Natural Language Supervision},
      author       = {Elizalde, Benjamin and Deshmukh, Soham and Al Ismail, Mahmoud and Wang, Huaming},
      year         = {2022},
      howpublished = {arXiv:2206.04769}
    }

    Reference

  23. A Setwise Approach for Effective and Highly Efficient Zero-shot Ranking with Large Language Models

    Shengyao Zhuang, Honglei Zhuang, Bevan Koopman, Guido Zuccon

    SIGIR 2024 (also arXiv:2310.09497) · 2024

    BibTeX
    @misc{zhuang2024setwise,
      title        = {A Setwise Approach for Effective and Highly Efficient Zero-shot Ranking with Large Language Models},
      author       = {Zhuang, Shengyao and Zhuang, Honglei and Koopman, Bevan and Zuccon, Guido},
      year         = {2024},
      howpublished = {SIGIR 2024 (also arXiv:2310.09497)},
      note         = {Conference metadata may be cited via arXiv when ACM access is restricted}
    }

    Reference

  24. Large Language Models are Zero-Shot Rankers for Recommender Systems

    Yupeng Hou, Junjie Zhang, Zihan Lin, Hongyu Lu, Ruobing Xie, Julian McAuley, Wayne Xin Zhao

    ECIR 2024; also arXiv:2305.08845 · 2024

    BibTeX
    @misc{hou2024llmrank,
      title        = {Large Language Models are Zero-Shot Rankers for Recommender Systems},
      author       = {Hou, Yupeng and Zhang, Junjie and Lin, Zihan and Lu, Hongyu and Xie, Ruobing and McAuley, Julian and Zhao, Wayne Xin},
      year         = {2024},
      howpublished = {ECIR 2024; also arXiv:2305.08845}
    }

    Reference

  25. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks

    Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Kuttler, Mike Lewis, et al.

    Advances in Neural Information Processing Systems (NeurIPS) · 2020

    BibTeX
    @inproceedings{lewis2020rag,
      title     = {Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks},
      author    = {Lewis, Patrick and Perez, Ethan and Piktus, Aleksandra and Petroni, Fabio and Karpukhin, Vladimir and Goyal, Naman and K{\"u}ttler, Heinrich and Lewis, Mike and Yih, Wen-tau and Rockt{\"a}schel, Tim and Riedel, Sebastian and Kiela, Douwe},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2020}
    }

    Conference paper

  26. Improving Language Models by Retrieving from Trillions of Tokens

    Sebastian Borgeaud, Arthur Mensch, Jordan Hoffmann, Trevor Cai, Eliza Rutherford, Katie Millican, George Van Den Driessche, Jean-Baptiste Lespiau, et al.

    Proceedings of ICML · 2022

    BibTeX
    @inproceedings{borgeaud2022retro,
      title     = {Improving Language Models by Retrieving from Trillions of Tokens},
      author    = {Borgeaud, Sebastian and Mensch, Arthur and Hoffmann, Jordan and Cai, Trevor and Rutherford, Eliza and Millican, Katie and Van Den Driessche, George and Lespiau, Jean-Baptiste and Damoc, Bogdan and Clark, Aidan and others},
      booktitle = {Proceedings of ICML},
      year      = {2022},
      note      = {PMLR v162; author list abbreviated}
    }

    Conference paper

  27. Leveraging Passage Retrieval with Generative Models for Open Domain Question Answering

    Gautier Izacard, Edouard Grave

    Proceedings of EACL · 2021

    BibTeX
    @inproceedings{izacard2021fid,
      title     = {Leveraging Passage Retrieval with Generative Models for Open Domain Question Answering},
      author    = {Izacard, Gautier and Grave, Edouard},
      booktitle = {Proceedings of EACL},
      year      = {2021},
      note      = {Fusion-in-Decoder style reader}
    }

    Conference paper

  28. Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection

    Akari Asai, Zeqiu Wu, Yizhong Wang, Avirup Sil, Hannaneh Hajishirzi

    Proceedings of ICLR · 2024

    BibTeX
    @inproceedings{asai2024selfrag,
      title     = {{Self-RAG}: Learning to Retrieve, Generate, and Critique through Self-Reflection},
      author    = {Asai, Akari and Wu, Zeqiu and Wang, Yizhong and Sil, Avirup and Hajishirzi, Hannaneh},
      booktitle = {Proceedings of ICLR},
      year      = {2024}
    }

    Conference paper

  29. VDocRAG: Retrieval-Augmented Generation over Visually-Rich Documents

    R. Tanaka, others

    Proceedings of CVPR · 2025

    BibTeX
    @inproceedings{tanaka2025vdocrag,
      title     = {{VDocRAG}: Retrieval-Augmented Generation over Visually-Rich Documents},
      author    = {Tanaka, R. and others},
      booktitle = {Proceedings of CVPR},
      year      = {2025},
      note      = {Author list abbreviated}
    }

    Conference paper

  30. Retrieval Augmented End-to-End Spoken Dialog Models

    Mingqiu Wang, Izhak Shafran, Hagen Soltau, Wei Han, Yuan Cao, Dian Yu, Laurent El Shafey

    arXiv:2402.01828; ICASSP 2024 · 2024

    BibTeX
    @misc{wang2024reslm,
      title        = {Retrieval Augmented End-to-End Spoken Dialog Models},
      author       = {Wang, Mingqiu and Shafran, Izhak and Soltau, Hagen and Han, Wei and Cao, Yuan and Yu, Dian and El Shafey, Laurent},
      year         = {2024},
      howpublished = {arXiv:2402.01828; ICASSP 2024}
    }

    Reference

  31. WavRAG: Audio-Integrated Retrieval Augmented Generation for Spoken Dialogue Models

    Yifu Chen, Shengpeng Ji, Haoxiao Wang, Ziqing Wang, Siyu Chen, Jinzheng He, Jin Xu, Zhou Zhao

    arXiv:2502.14727 · 2025

    BibTeX
    @misc{chen2025wavrag,
      title        = {{WavRAG}: Audio-Integrated Retrieval Augmented Generation for Spoken Dialogue Models},
      author       = {Chen, Yifu and Ji, Shengpeng and Wang, Haoxiao and Wang, Ziqing and Chen, Siyu and He, Jinzheng and Xu, Jin and Zhao, Zhou},
      year         = {2025},
      howpublished = {arXiv:2502.14727}
    }

    Reference

  32. Retrieval-Augmented Text-to-Audio Generation

    Yi Yuan, Haohe Liu, Xubo Liu, Qiushi Huang, Mark D. Plumbley, Wenwu Wang

    Proceedings of ICASSP · 2024

    BibTeX
    @inproceedings{yuan2024reaudioldm,
      title     = {Retrieval-Augmented Text-to-Audio Generation},
      author    = {Yuan, Yi and Liu, Haohe and Liu, Xubo and Huang, Qiushi and Plumbley, Mark D. and Wang, Wenwu},
      booktitle = {Proceedings of ICASSP},
      year      = {2024},
      note      = {Also on arXiv:2309.08051}
    }

    Conference paper

  33. RECAP: Retrieval-Augmented Audio Captioning

    Sreyan Ghosh, others

    ICASSP 2024 (also arXiv:2309.09836) · 2024

    BibTeX
    @misc{ghosh2024recap,
      title        = {{RECAP}: Retrieval-Augmented Audio Captioning},
      author       = {Ghosh, Sreyan and others},
      year         = {2024},
      howpublished = {ICASSP 2024 (also arXiv:2309.09836)},
      note         = {Author list abbreviated}
    }

    Reference

  34. Memory Engram Storage and Retrieval

    Susumu Tonegawa, Xu Liu, Steve Ramirez, Roger Redondo

    Current Opinion in Neurobiology, vol. 35, pp. 101-109 · 2015

    BibTeX
    @article{tonegawa2015engram,
      title   = {Memory Engram Storage and Retrieval},
      author  = {Tonegawa, Susumu and Liu, Xu and Ramirez, Steve and Redondo, Roger},
      journal = {Current Opinion in Neurobiology},
      volume  = {35},
      pages   = {101--109},
      year    = {2015},
      doi     = {10.1016/j.conb.2015.07.009}
    }

    Journal article

  35. A Cortical--Hippocampal System for Declarative Memory

    Howard Eichenbaum

    Nature Reviews Neuroscience, vol. 1, no. 1, pp. 41-50 · 2000

    BibTeX
    @article{eichenbaum2000hippocampus,
      title   = {A Cortical--Hippocampal System for Declarative Memory},
      author  = {Eichenbaum, Howard},
      journal = {Nature Reviews Neuroscience},
      volume  = {1},
      number  = {1},
      pages   = {41--50},
      year    = {2000},
      doi     = {10.1038/35036213}
    }

    Journal article

  36. Episodic and Semantic Memory

    Endel Tulving

    Organization of Memory, pp. 381-403 · 1972

    BibTeX
    @article{tulving1972episodic,
      title={Episodic and Semantic Memory},
      author={Tulving, Endel},
      journal={Organization of Memory},
      pages={381--403},
      year={1972},
      publisher={Academic Press}
    }

    Journal article

  37. Elements of Information Theory

    Thomas M. Cover, Joy A. Thomas

    Wiley-Interscience · 2006

    BibTeX
    @book{cover2006elements,
      title     = {Elements of Information Theory},
      author    = {Cover, Thomas M. and Thomas, Joy A.},
      edition   = {2nd},
      publisher = {Wiley-Interscience},
      year      = {2006}
    }

    Book

  38. Rethinking Benchmarks for Cross-modal Image-text Retrieval

    Weijing Chen, Linli Yao, Qin Jin

    arXiv:2304.10824 · 2023

    BibTeX
    @misc{chen2023rethinking,
      title        = {Rethinking Benchmarks for Cross-modal Image-text Retrieval},
      author       = {Chen, Weijing and Yao, Linli and Jin, Qin},
      year         = {2023},
      howpublished = {arXiv:2304.10824}
    }

    Reference

  39. Attention is all you need

    Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, Illia Polosukhin

    Advances in neural information processing systems, pp. 5998-6008 · 2017

    BibTeX
    @inproceedings{vaswani2017attention,
    title={Attention is all you need},
    author={Vaswani, Ashish and Shazeer, Noam and Parmar, Niki and Uszkoreit, Jakob and Jones, Llion and Gomez, Aidan N and Kaiser, {\L}ukasz and Polosukhin, Illia},
    booktitle={Advances in neural information processing systems},
    pages={5998--6008},
    year={2017}
    }

    Conference paper

  40. Representation Learning with Contrastive Predictive Coding

    Aaron van den Oord, Yazhe Li, Oriol Vinyals

    arXiv preprint arXiv:1807.03748 · 2018

    BibTeX
    @article{oord2018representation,
      author    = {Oord, Aaron van den and Li, Yazhe and Vinyals, Oriol},
      title     = {Representation Learning with Contrastive Predictive Coding},
      journal   = {arXiv preprint arXiv:1807.03748},
      year      = {2018}
    }

    Journal article

  41. Memory Systems of the Brain: A Brief History and Current Perspective

    Larry R. Squire

    Neurobiology of Learning and Memory, vol. 82, no. 3, pp. 171-177 · 2004

    BibTeX
    @article{squire2004memory,
      title   = {Memory Systems of the Brain: A Brief History and Current Perspective},
      author  = {Squire, Larry R.},
      journal = {Neurobiology of Learning and Memory},
      volume  = {82},
      number  = {3},
      pages   = {171--177},
      year    = {2004},
      doi     = {10.1016/j.nlm.2004.06.005}
    }

    Journal article

  42. Some Simple Effective Approximations to the 2--Poisson Model for Probabilistic Weighted Retrieval

    Stephen E. Robertson, Steve Walker

    Proceedings of SIGIR · 1994

    BibTeX
    @inproceedings{robertson1994poisson,
      title     = {Some Simple Effective Approximations to the 2--Poisson Model for Probabilistic Weighted Retrieval},
      author    = {Robertson, Stephen E. and Walker, Steve},
      booktitle = {Proceedings of SIGIR},
      year      = {1994},
      note      = {Venue/pages unspecified in this bib (see PDF source)}
    }

    Conference paper

  43. Learning to Rank for Information Retrieval

    Tie-Yan Liu

    Springer · 2009

    BibTeX
    @book{liu2009ltr,
      title     = {Learning to Rank for Information Retrieval},
      author    = {Liu, Tie-Yan},
      publisher = {Springer},
      year      = {2009}
    }

    Book

  44. The Vocabulary Problem in Human-System Communication

    George W. Furnas, Thomas K. Landauer, Louis M. Gomez, Susan T. Dumais

    Communications of the ACM, vol. 30, no. 11, pp. 964-971 · 1987

    BibTeX
    @article{furnas1987vocabulary,
      author    = {Furnas, George W. and Landauer, Thomas K. and Gomez, Louis M. and Dumais, Susan T.},
      title     = {The Vocabulary Problem in Human-System Communication},
      journal   = {Communications of the ACM},
      volume    = {30},
      number    = {11},
      pages     = {964--971},
      year      = {1987}
    }

    Journal article

  45. Dense Passage Retrieval for Open-Domain Question Answering

    Vladimir Karpukhin, Barlas Oguz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen-tau Yih

    arXiv preprint arXiv:2004.04906 · 2020

    BibTeX
    @article{karpukhin2020dense,
      author    = {Karpukhin, Vladimir and Oguz, Barlas and Min, Sewon and Lewis, Patrick and Wu, Ledell and Edunov, Sergey and Chen, Danqi and Yih, Wen-tau},
      title     = {Dense Passage Retrieval for Open-Domain Question Answering},
      journal   = {arXiv preprint arXiv:2004.04906},
      year      = {2020}
    }

    Journal article

  46. ColBERT: Efficient and Effective Passage Search via Contextualized Late Interaction over BERT

    Omar Khattab, Matei Zaharia

    Proceedings of SIGIR, pp. 39-48 · 2020

    BibTeX
    @inproceedings{khattab2020colbert,
      title     = {{ColBERT}: Efficient and Effective Passage Search via Contextualized Late Interaction over {BERT}},
      author    = {Khattab, Omar and Zaharia, Matei},
      booktitle = {Proceedings of SIGIR},
      pages     = {39--48},
      year      = {2020}
    }

    Conference paper

  47. SPLADE: Sparse Lexical and Expansion Model for First Stage Ranking

    Thibault Formal, Benjamin Piwowarski, Stephane Clinchant

    Proceedings of SIGIR · 2021

    BibTeX
    @article{formal2021splade,
      author    = {Formal, Thibault and Piwowarski, Benjamin and Clinchant, St{\'e}phane},
      title     = {{SPLADE}: Sparse Lexical and Expansion Model for First Stage Ranking},
      journal   = {Proceedings of SIGIR},
      year      = {2021}
    }

    Journal article

  48. Product Quantization for Nearest Neighbor Search

    Herve Jegou, Matthijs Douze, Cordelia Schmid

    IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 33, no. 1, pp. 117-128 · 2011

    BibTeX
    @article{jegou2011product,
      author    = {J{\'e}gou, Herv{\'e} and Douze, Matthijs and Schmid, Cordelia},
      title     = {Product Quantization for Nearest Neighbor Search},
      journal   = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
      volume    = {33},
      number    = {1},
      pages     = {117--128},
      year      = {2011}
    }

    Journal article

  49. Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs

    Yu A. Malkov, D. A. Yashunin

    IEEE Transactions on Pattern Analysis and Machine Intelligence · 2018

    BibTeX
    @article{malkov2018efficient,
      author    = {Malkov, Yu A. and Yashunin, D. A.},
      title     = {Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs},
      journal   = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
      year      = {2018}
    }

    Journal article

  50. Accelerating Large-Scale Inference with Anisotropic Vector Quantization

    Ruiqi Guo, Philip Sun, Erik Lindgren, Quan Geng, David Simcha, Felix Chern, Sanjiv Kumar

    Proceedings of ICML · 2020

    BibTeX
    @article{guo2020accelerating,
      author    = {Guo, Ruiqi and Sun, Philip and Lindgren, Erik and Geng, Quan and Simcha, David and Chern, Felix and Kumar, Sanjiv},
      title     = {Accelerating Large-Scale Inference with Anisotropic Vector Quantization},
      journal   = {Proceedings of ICML},
      year      = {2020}
    }

    Journal article

  51. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks

    Nils Reimers, Iryna Gurevych

    Proceedings of EMNLP · 2019

    BibTeX
    @article{reimers2019sentence,
      author    = {Reimers, Nils and Gurevych, Iryna},
      title     = {Sentence-{BERT}: Sentence Embeddings using Siamese {BERT}-Networks},
      journal   = {Proceedings of EMNLP},
      year      = {2019}
    }

    Journal article

  52. One Embedder, Any Task: Instruction-Finetuned Text Embeddings

    Hongjin Su, Weijia Shi, Jungo Kasai, Yizhong Wang, Yushi Hu, Mari Ostendorf, Wen-tau Yih, Noah A. Smith, et al.

    arXiv preprint arXiv:2212.09741 · 2022

    BibTeX
    @article{su2022instructor,
      author    = {Su, Hongjin and Shi, Weijia and Kasai, Jungo and Wang, Yizhong and Hu, Yushi and Ostendorf, Mari and Yih, Wen-tau and Smith, Noah A. and Zettlemoyer, Luke and Yu, Tao},
      title     = {One Embedder, Any Task: Instruction-Finetuned Text Embeddings},
      journal   = {arXiv preprint arXiv:2212.09741},
      year      = {2022}
    }

    Journal article

  53. Improving Text Embeddings with Large Language Models

    Liang Wang, Nan Yang, Xiaolong Huang, Linjun Yang, Rangan Majumder, Furu Wei

    arXiv preprint arXiv:2401.00368 · 2024

    BibTeX
    @article{wang2024text,
      author    = {Wang, Liang and Yang, Nan and Huang, Xiaolong and Yang, Linjun and Majumder, Rangan and Wei, Furu},
      title     = {Improving Text Embeddings with Large Language Models},
      journal   = {arXiv preprint arXiv:2401.00368},
      year      = {2024}
    }

    Journal article

  54. Matryoshka Representation Learning

    Aditya Kusupati, Gantavya Bhatt, Aniket Rege, Matthew Wallingford, Aditya Sber, Prateek Jain, Sham Kakade, Prateek Jain

    Advances in Neural Information Processing Systems · 2022

    BibTeX
    @article{kusupati2022matryoshka,
      author    = {Kusupati, Aditya and Bhatt, Gantavya and Rege, Aniket and Wallingford, Matthew and Sber, Aditya and Jain, Prateek and Kakade, Sham and Jain, Prateek},
      title     = {Matryoshka Representation Learning},
      journal   = {Advances in Neural Information Processing Systems},
      year      = {2022}
    }

    Journal article

  55. Distinctive Image Features from Scale-Invariant Keypoints

    David G. Lowe

    International Journal of Computer Vision, vol. 60, no. 2, pp. 91-110 · 2004

    BibTeX
    @article{lowe2004sift,
      title   = {Distinctive Image Features from Scale-Invariant Keypoints},
      author  = {Lowe, David G.},
      journal = {International Journal of Computer Vision},
      volume  = {60},
      number  = {2},
      pages   = {91--110},
      year    = {2004},
      doi     = {10.1023/B:VISI.0000029664.99615.94}
    }

    Journal article

  56. Visual Categorization with Bags of Keypoints

    Gabriella Csurka, Christopher Dance, Lixin Fan, Jorg Willamowski, Cedric Bray

    Workshop on Statistical Learning in Computer Vision (ECCV workshops) · 2004

    BibTeX
    @inproceedings{csurka2004bow,
      title     = {Visual Categorization with Bags of Keypoints},
      author    = {Csurka, Gabriella and Dance, Christopher and Fan, Lixin and Willamowski, J{\"o}rg and Bray, C{\'e}dric},
      booktitle = {Workshop on Statistical Learning in Computer Vision (ECCV workshops)},
      year      = {2004},
      note      = {Venue/pages sometimes listed as ECCV workshop; metadata may vary}
    }

    Conference paper

  57. Video Google: A Text Retrieval Approach to Object Matching in Videos

    Josef Sivic, Andrew Zisserman

    Proceedings of ICCV · 2003

    BibTeX
    @inproceedings{sivic2003videogoogle,
      title     = {Video Google: A Text Retrieval Approach to Object Matching in Videos},
      author    = {Sivic, Josef and Zisserman, Andrew},
      booktitle = {Proceedings of ICCV},
      year      = {2003},
      note      = {Pages unspecified}
    }

    Conference paper

  58. Aggregating local descriptors into a compact image representation

    Herve Jegou, Matthijs Douze, Cordelia Schmid

    Proceedings of CVPR · 2010

    BibTeX
    @inproceedings{jegou2010vlad,
      title     = {Aggregating local descriptors into a compact image representation},
      author    = {J{\'e}gou, Herv{\'e} and Douze, Matthijs and Schmid, Cordelia},
      booktitle = {Proceedings of CVPR},
      year      = {2010},
      note      = {Pages unspecified}
    }

    Conference paper

  59. BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models

    Junnan Li, Dongxu Li, Silvio Savarese, Steven Hoi

    Proceedings of ICML · 2023

    BibTeX
    @inproceedings{li2023blip2,
      title     = {{BLIP-2}: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models},
      author    = {Li, Junnan and Li, Dongxu and Savarese, Silvio and Hoi, Steven},
      booktitle = {Proceedings of ICML},
      year      = {2023},
      note      = {PMLR v202}
    }

    Conference paper

  60. Emergent Correspondence from Image Diffusion

    Luming Tang, Menglin Jia, Qianqian Wang, Cheng Perng Phoo, Bharath Hariharan

    Advances in Neural Information Processing Systems (NeurIPS) · 2023

    BibTeX
    @inproceedings{tang2023dift,
      title     = {Emergent Correspondence from Image Diffusion},
      author    = {Tang, Luming and Jia, Menglin and Wang, Qianqian and Phoo, Cheng Perng and Hariharan, Bharath},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2023},
      note      = {DIFT paper}
    }

    Conference paper

  61. Diffusion Features for Personalized Segmentation and Retrieval

    D. Samuel, others

    Advances in Neural Information Processing Systems (NeurIPS) · 2024

    BibTeX
    @inproceedings{samuel2024pdm,
      title     = {Diffusion Features for Personalized Segmentation and Retrieval},
      author    = {Samuel, D. and others},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2024},
      note      = {Author list abbreviated; see NeurIPS 2024 paper PDF for full metadata}
    }

    Conference paper

  62. Text-to-Image Diffusion Models are Great Sketch-Photo Matchmakers

    S. Koley, others

    Proceedings of CVPR · 2024

    BibTeX
    @inproceedings{koley2024sketchphoto,
      title     = {Text-to-Image Diffusion Models are Great Sketch-Photo Matchmakers},
      author    = {Koley, S. and others},
      booktitle = {Proceedings of CVPR},
      year      = {2024},
      note      = {Author list abbreviated}
    }

    Conference paper

  63. CLIP4Clip: An Empirical Study of CLIP for End to End Video Clip Retrieval and Captioning

    Huaishao Luo, Lei Ji, Ming Zhong, Yang Chen, Wen Lei, Nan Duan, Tianrui Li

    Neurocomputing, vol. 508, pp. 293-304 · 2022

    BibTeX
    @inproceedings{luo2022clip4clip,
      title     = {{CLIP4Clip}: An Empirical Study of {CLIP} for End to End Video Clip Retrieval and Captioning},
      author    = {Luo, Huaishao and Ji, Lei and Zhong, Ming and Chen, Yang and Lei, Wen and Duan, Nan and Li, Tianrui},
      journal   = {Neurocomputing},
      volume    = {508},
      pages     = {293--304},
      year      = {2022}
    }

    Conference paper

  64. Less is More: ClipBERT for Video-and-Language Learning via Sparse Sampling

    Jie Lei, Linjie Li, Luowei Zhou, Zhe Gan, Tamara L. Berg, Mohit Bansal, Jingjing Liu

    Proceedings of CVPR, pp. 7331-7341 · 2021

    BibTeX
    @inproceedings{lei2021clipbert,
      title     = {Less is More: {ClipBERT} for Video-and-Language Learning via Sparse Sampling},
      author    = {Lei, Jie and Li, Linjie and Zhou, Luowei and Gan, Zhe and Berg, Tamara L. and Bansal, Mohit and Liu, Jingjing},
      booktitle = {Proceedings of CVPR},
      pages     = {7331--7341},
      year      = {2021}
    }

    Conference paper

  65. TALL: Temporal Activity Localization via Language Query

    Jiyang Gao, Chen Sun, Zhenheng Yang, Ram Nevatia

    Proceedings of ICCV, pp. 5267-5275 · 2017

    BibTeX
    @inproceedings{gao2017tall,
      title     = {{TALL}: Temporal Activity Localization via Language Query},
      author    = {Gao, Jiyang and Sun, Chen and Yang, Zhenheng and Nevatia, Ram},
      booktitle = {Proceedings of ICCV},
      pages     = {5267--5275},
      year      = {2017}
    }

    Conference paper

  66. Flamingo: a Visual Language Model for Few-Shot Learning

    Jean-Baptiste Alayrac, Jeff Donahue, Pauline Luc, Antoine Miech, Iain Barr, Yana Hasson, Karel Lenc, Arthur Mensch, et al.

    Advances in Neural Information Processing Systems (NeurIPS) · 2022

    BibTeX
    @inproceedings{alayrac2022flamingo,
      title     = {Flamingo: a Visual Language Model for Few-Shot Learning},
      author    = {Alayrac, Jean-Baptiste and Donahue, Jeff and Luc, Pauline and Miech, Antoine and Barr, Iain and Hasson, Yana and Lenc, Karel and Mensch, Arthur and Millican, Katherine and Reynolds, Malcolm and others},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2022},
      note      = {Author list abbreviated}
    }

    Conference paper

  67. Dynamic Programming Algorithm Optimization for Spoken Word Recognition

    Hiroaki Sakoe, Seibi Chiba

    IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 26, no. 1, pp. 43-49 · 1978

    BibTeX
    @article{sakoe1978dtw,
      title   = {Dynamic Programming Algorithm Optimization for Spoken Word Recognition},
      author  = {Sakoe, Hiroaki and Chiba, Seibi},
      journal = {IEEE Transactions on Acoustics, Speech, and Signal Processing},
      volume  = {26},
      number  = {1},
      pages   = {43--49},
      year    = {1978},
      doi     = {10.1109/TASSP.1978.1163055}
    }

    Journal article

  68. A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition

    Lawrence R. Rabiner

    Proceedings of the IEEE, vol. 77, no. 2, pp. 257-286 · 1989

    BibTeX
    @article{rabiner1989hmm,
      title   = {A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition},
      author  = {Rabiner, Lawrence R.},
      journal = {Proceedings of the IEEE},
      volume  = {77},
      number  = {2},
      pages   = {257--286},
      year    = {1989},
      doi     = {10.1109/5.18626}
    }

    Journal article

  69. Automatic recognition of keywords in unconstrained speech using hidden Markov models

    Jay G. Wilpon, Lawrence R. Rabiner, Chong M. Lee, Biing-Hwang Juang

    unspecified · 1990

    BibTeX
    @article{wilpon1990keyword,
      title   = {Automatic recognition of keywords in unconstrained speech using hidden Markov models},
      author  = {Wilpon, Jay G. and Rabiner, Lawrence R. and Lee, Chong M. and Juang, Biing-Hwang},
      journal = {unspecified},
      year    = {1990},
      note    = {Exact venue/pages unspecified in this bib; see keyword-spotting sources}
    }

    Journal article

  70. wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations

    Alexei Baevski, Henry Zhou, Abdelrahman Mohamed, Michael Auli

    Advances in Neural Information Processing Systems (NeurIPS) · 2020

    BibTeX
    @inproceedings{baevski2020wav2vec2,
      title     = {wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations},
      author    = {Baevski, Alexei and Zhou, Henry and Mohamed, Abdelrahman and Auli, Michael},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2020}
    }

    Conference paper

  71. HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units

    Wei-Ning Hsu, Benjamin Bolte, Yao-Hung Hubert Tsai, Kushal Lakhotia, Ruslan Salakhutdinov, Abdelrahman Mohamed

    arXiv:2106.07447 · 2021

    BibTeX
    @misc{hsu2021hubert,
      title        = {HuBERT: Self-Supervised Speech Representation Learning by Masked Prediction of Hidden Units},
      author       = {Hsu, Wei-Ning and Bolte, Benjamin and Tsai, Yao-Hung Hubert and Lakhotia, Kushal and Salakhutdinov, Ruslan and Mohamed, Abdelrahman},
      year         = {2021},
      howpublished = {arXiv:2106.07447}
    }

    Reference

  72. WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing

    Sanyuan Chen, Chengyi Wang, Zhengyang Chen, Yu Wu, Shujie Liu, Zhuo Chen, Jinyu Li, Naoyuki Kanda, et al.

    arXiv:2110.13900 · 2021

    BibTeX
    @misc{chen2021wavlm,
      title        = {WavLM: Large-Scale Self-Supervised Pre-Training for Full Stack Speech Processing},
      author       = {Chen, Sanyuan and Wang, Chengyi and Chen, Zhengyang and Wu, Yu and Liu, Shujie and Chen, Zhuo and Li, Jinyu and Kanda, Naoyuki and Yoshioka, Takuya and Xiao, Xiong and others},
      year         = {2021},
      howpublished = {arXiv:2110.13900},
      note         = {Author list abbreviated}
    }

    Reference

  73. Robust Speech Recognition via Large-Scale Weak Supervision

    Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever

    International Conference on Machine Learning · 2023

    BibTeX
    @inproceedings{radford2023whisper,
      title={Robust Speech Recognition via Large-Scale Weak Supervision},
      author={Radford, Alec and Kim, Jong Wook and Xu, Tao and Brockman, Greg and McLeavey, Christine and Sutskever, Ilya},
      booktitle={International Conference on Machine Learning},
      year={2023}
    }

    Conference paper

  74. An Industrial-Strength Audio Search Algorithm

    Avery Wang

    Proceedings of the International Society for Music Information Retrieval Conference (ISMIR), pp. 7-13 · 2003

    BibTeX
    @inproceedings{wang2003shazam,
      title     = {An Industrial-Strength Audio Search Algorithm},
      author    = {Wang, Avery},
      booktitle = {Proceedings of the International Society for Music Information Retrieval Conference (ISMIR)},
      pages     = {7--13},
      year      = {2003}
    }

    Conference paper

  75. Content-Based Music Information Retrieval: Current Directions and Future Challenges

    Michael A. Casey, Remco Veltkamp, Masataka Goto, Marc Leman, Christophe Rhodes, Malcolm Slaney

    Proceedings of the IEEE, vol. 96, no. 4, pp. 668-696 · 2008

    BibTeX
    @article{casey2008content,
      title   = {Content-Based Music Information Retrieval: Current Directions and Future Challenges},
      author  = {Casey, Michael A. and Veltkamp, Remco and Goto, Masataka and Leman, Marc and Rhodes, Christophe and Slaney, Malcolm},
      journal = {Proceedings of the IEEE},
      volume  = {96},
      number  = {4},
      pages   = {668--696},
      year    = {2008},
      doi     = {10.1109/JPROC.2008.916370}
    }

    Journal article

  76. Music Information Retrieval

    J. Stephen Downie

    Annual Review of Information Science and Technology, vol. 37, no. 1, pp. 295-340 · 2003

    BibTeX
    @article{downie2003mir,
      title   = {Music Information Retrieval},
      author  = {Downie, J. Stephen},
      journal = {Annual Review of Information Science and Technology},
      volume  = {37},
      number  = {1},
      pages   = {295--340},
      year    = {2003},
      doi     = {10.1002/aris.1440370108}
    }

    Journal article

  77. Locality-Sensitive Hashing for Finding Nearest Neighbors

    Malcolm Slaney, Michael Casey

    IEEE Signal Processing Magazine, vol. 25, no. 2, pp. 128-131 · 2008

    BibTeX
    @article{slaney2008locality,
      title   = {Locality-Sensitive Hashing for Finding Nearest Neighbors},
      author  = {Slaney, Malcolm and Casey, Michael},
      journal = {IEEE Signal Processing Magazine},
      volume  = {25},
      number  = {2},
      pages   = {128--131},
      year    = {2008},
      doi     = {10.1109/MSP.2007.914237}
    }

    Journal article

  78. Simple and Controllable Music Generation

    Jade Copet, Felix Kreuk, Itai Gat, Tal Remez, David Kant, Gabriel Synnaeve, Yossi Adi, Alexandre Defossez

    Advances in Neural Information Processing Systems (NeurIPS) · 2023

    BibTeX
    @article{defossez2023musicgen,
      title   = {Simple and Controllable Music Generation},
      author  = {Copet, Jade and Kreuk, Felix and Gat, Itai and Remez, Tal and Kant, David and Synnaeve, Gabriel and Adi, Yossi and D{\'e}fossez, Alexandre},
      journal = {Advances in Neural Information Processing Systems (NeurIPS)},
      year    = {2023},
      note    = {MusicGen; arXiv:2306.05284}
    }

    Journal article

  79. MusicLM: Generating Music From Text

    Andrea Agostinelli, Timo I. Denk, Zalan Borsos, Jesse Engel, Mauro Verzetti, Antoine Caillon, Qingqing Huang, Aren Jansen, et al.

    arXiv preprint arXiv:2301.11325 · 2023

    BibTeX
    @article{agostinelli2023musiclm,
      title={{MusicLM}: Generating Music From Text},
      author={Agostinelli, Andrea and Denk, Timo I. and Borsos, Zal{\'a}n and Engel, Jesse and Verzetti, Mauro and Caillon, Antoine and Huang, Qingqing and Jansen, Aren and Roberts, Adam and Tagliasacchi, Marco and Sharifi, Matt and Zeghidour, Neil and Frank, Christian},
      journal={arXiv preprint arXiv:2301.11325},
      year={2023}
    }

    Journal article

  80. AudioLDM: Text-to-Audio Generation with Latent Diffusion Models

    Haohe Liu, Zehua Chen, Yi Yuan, Xinhao Mei, Xubo Liu, Danilo Mandic, Wenwu Wang, Mark D. Plumbley

    arXiv:2301.12503 · 2023

    BibTeX
    @misc{audioldm2023,
      title        = {AudioLDM: Text-to-Audio Generation with Latent Diffusion Models},
      author       = {Liu, Haohe and Chen, Zehua and Yuan, Yi and Mei, Xinhao and Liu, Xubo and Mandic, Danilo and Wang, Wenwu and Plumbley, Mark D.},
      year         = {2023},
      howpublished = {arXiv:2301.12503}
    }

    Reference

  81. Get multimodal embeddings: Vertex AI documentation

    Google Cloud

    rlhttps://docs.cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-multimodal-embeddings · 2026

    BibTeX
    @misc{vertex_multimodal_embeddings,
      title        = {Get multimodal embeddings: Vertex AI documentation},
      author       = {{Google Cloud}},
      year         = {2026},
      howpublished = {\url{https://docs.cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-multimodal-embeddings}},
      note         = {Accessed 2026-03-16}
    }

    Reference

  82. Model versions and lifecycle: Vertex AI documentation

    Google Cloud

    rlhttps://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions · 2026

    BibTeX
    @misc{vertex_model_versions,
      title        = {Model versions and lifecycle: Vertex AI documentation},
      author       = {{Google Cloud}},
      year         = {2026},
      howpublished = {\url{https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions}},
      note         = {Accessed 2026-03-16}
    }

    Reference

  83. BERT: Pre-training of deep bidirectional transformers for language understanding

    Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova

    Proceedings of NAACL-HLT, pp. 4171-4186 · 2019

    BibTeX
    @article{devlin2019bert,
      title={{BERT}: Pre-training of deep bidirectional transformers for language understanding},
      author={Devlin, Jacob and Chang, Ming-Wei and Lee, Kenton and Toutanova, Kristina},
      journal={Proceedings of NAACL-HLT},
      pages={4171--4186},
      year={2019}
    }

    Journal article

  84. Document Ranking with a Pretrained Sequence-to-Sequence Model

    Rodrigo Nogueira, Zhiying Jiang, Ronak Pradeep, Jimmy Lin

    Findings of EMNLP · 2020

    BibTeX
    @inproceedings{nogueira2020monot5,
      title     = {Document Ranking with a Pretrained Sequence-to-Sequence Model},
      author    = {Nogueira, Rodrigo and Jiang, Zhiying and Pradeep, Ronak and Lin, Jimmy},
      booktitle = {Findings of EMNLP},
      year      = {2020}
    }

    Conference paper

  85. Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer

    Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, et al.

    Journal of Machine Learning Research, vol. 21, no. 140, pp. 1-67 · 2020

    BibTeX
    @article{raffel2020t5,
      title={Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer},
      author={Raffel, Colin and Shazeer, Noam and Roberts, Adam and Lee, Katherine and Narang, Sharan and Matena, Michael and Zhou, Yanqi and Li, Wei and Liu, Peter J.},
      journal={Journal of Machine Learning Research},
      volume={21},
      number={140},
      pages={1--67},
      year={2020}
    }

    Journal article

  86. FIRST: Faster Improved Listwise Reranking with Single Token Decoding

    Revanth Gangi Reddy, JaeHyeok Doo, Yifei Xu, Md Arafat Sultan, Deevya Swain, Avirup Sil, Heng Ji

    Proceedings of EMNLP · 2024

    BibTeX
    @inproceedings{reddy2024first,
      title     = {{FIRST}: Faster Improved Listwise Reranking with Single Token Decoding},
      author    = {Reddy, Revanth Gangi and Doo, JaeHyeok and Xu, Yifei and Sultan, Md Arafat and Swain, Deevya and Sil, Avirup and Ji, Heng},
      booktitle = {Proceedings of EMNLP},
      year      = {2024}
    }

    Conference paper

  87. Unsupervised Large Language Model Alignment for Information Retrieval via Contrastive Feedback

    Qian Dong, Yiding Liu, Qingyao Ai, Zhijing Wu, Haitao Li, Yiqun Liu, Shuaiqiang Wang, Dawei Yin, et al.

    SIGIR-era preprint (arXiv:2309.17078) · 2024

    BibTeX
    @misc{dong2024rlcf,
      title        = {Unsupervised Large Language Model Alignment for Information Retrieval via Contrastive Feedback},
      author       = {Dong, Qian and Liu, Yiding and Ai, Qingyao and Wu, Zhijing and Li, Haitao and Liu, Yiqun and Wang, Shuaiqiang and Yin, Dawei and Ma, Shaoping},
      year         = {2024},
      howpublished = {SIGIR-era preprint (arXiv:2309.17078)},
      note         = {Check venue in final camera-ready if needed}
    }

    Reference

  88. InPars: Data Augmentation for Information Retrieval using Large Language Models

    Luiz Bonifacio, Hugo Abonizio, Marzieh Fadaee, Rodrigo Nogueira

    arXiv:2202.05144 · 2022

    BibTeX
    @misc{bonifacio2022inpars,
      title        = {InPars: Data Augmentation for Information Retrieval using Large Language Models},
      author       = {Bonifacio, Luiz and Abonizio, Hugo and Fadaee, Marzieh and Nogueira, Rodrigo},
      year         = {2022},
      howpublished = {arXiv:2202.05144}
    }

    Reference

  89. Precise Zero-Shot Dense Retrieval without Relevance Labels

    Luyu Gao, Xueguang Ma, Jimmy Lin, Jamie Callan

    Proceedings of ACL · 2023

    BibTeX
    @inproceedings{gao2023hyde,
      title     = {Precise Zero-Shot Dense Retrieval without Relevance Labels},
      author    = {Gao, Luyu and Ma, Xueguang and Lin, Jimmy and Callan, Jamie},
      booktitle = {Proceedings of ACL},
      year      = {2023},
      note      = {HyDE}
    }

    Conference paper

  90. Transformer Memory as a Differentiable Search Index

    Yi Tay, Vinh Tran, Mostafa Dehghani, Jianmo Ni, Dara Bahri, Harsh Mehta, Zhen Qin, Kai Hui, et al.

    Advances in Neural Information Processing Systems (NeurIPS) · 2022

    BibTeX
    @inproceedings{tay2022dsi,
      title     = {Transformer Memory as a Differentiable Search Index},
      author    = {Tay, Yi and Tran, Vinh and Dehghani, Mostafa and Ni, Jianmo and Bahri, Dara and Mehta, Harsh and Qin, Zhen and Hui, Kai and Zhao, Zhe and Gupta, Jay and Schuster, Tal and others},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2022}
    }

    Conference paper

  91. Recommender Systems with Generative Retrieval

    Shashank Rajput, Nikhil Mehta, Anima Singh, Raghunandan Hulikal Keshavan, Trung Vu, Lukasz Heldt, Lichan Hong, Yi Tay, et al.

    Advances in Neural Information Processing Systems (NeurIPS) · 2023

    BibTeX
    @inproceedings{rajput2023tiger,
      title     = {Recommender Systems with Generative Retrieval},
      author    = {Rajput, Shashank and Mehta, Nikhil and Singh, Anima and Keshavan, Raghunandan Hulikal and Vu, Trung and Heldt, Lukasz and Hong, Lichan and Tay, Yi and Tran, Vinh and Samost, Jonah and Kula, Maciej and Chi, Ed and Sathiamoorthy, Maheswaran},
      booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
      year      = {2023},
      note      = {TIGER / semantic IDs}
    }

    Conference paper

  92. IDGenRec: LLM-RecSys Alignment with Textual ID Learning

    Juntao Tan, Shuyuan Xu, Wenyue Hua, Yingqiang Ge, Zelong Li, Yongfeng Zhang

    Proceedings of SIGIR · 2024

    BibTeX
    @inproceedings{tan2024idgenrec,
      title     = {{IDGenRec}: LLM-RecSys Alignment with Textual ID Learning},
      author    = {Tan, Juntao and Xu, Shuyuan and Hua, Wenyue and Ge, Yingqiang and Li, Zelong and Zhang, Yongfeng},
      booktitle = {Proceedings of SIGIR},
      year      = {2024},
      note      = {Also on arXiv:2403.19021}
    }

    Conference paper

  93. CorpusLM: Towards a Unified Language Model on Corpus for Knowledge-Intensive Tasks

    Xiaoxi Li, Zhicheng Dou, Yujia Zhou, Fangchao Liu

    Proceedings of SIGIR · 2024

    BibTeX
    @inproceedings{li2024corpuslm,
      title        = {{CorpusLM}: Towards a Unified Language Model on Corpus for Knowledge-Intensive Tasks},
      author       = {Li, Xiaoxi and Dou, Zhicheng and Zhou, Yujia and Liu, Fangchao},
      booktitle    = {Proceedings of SIGIR},
      year         = {2024},
      note         = {Also on arXiv:2402.01176}
    }

    Conference paper

  94. A Survey on Retrieval-Augmented Text Generation

    Huayang Li, Yixuan Su, Deng Cai, Yan Wang, Lemao Liu

    arXiv:2202.01110 · 2022

    BibTeX
    @misc{li2022ragtg,
      title        = {A Survey on Retrieval-Augmented Text Generation},
      author       = {Li, Huayang and Su, Yixuan and Cai, Deng and Wang, Yan and Liu, Lemao},
      year         = {2022},
      howpublished = {arXiv:2202.01110}
    }

    Reference

  95. RAGAs: Automated Evaluation of Retrieval Augmented Generation

    Shayan Es, others

    Proceedings of EACL (Demos) · 2024

    BibTeX
    @inproceedings{es2024ragas,
      title     = {RAGAs: Automated Evaluation of Retrieval Augmented Generation},
      author    = {Es, Shayan and others},
      booktitle = {Proceedings of EACL (Demos)},
      year      = {2024},
      note      = {See ACL Anthology entry for full author list}
    }

    Conference paper

  96. Evaluation of Retrieval-Augmented Generation: A Survey

    Hao Yu, others

    arXiv:2405.07437 · 2024

    BibTeX
    @misc{yu2024rageval,
      title        = {Evaluation of Retrieval-Augmented Generation: A Survey},
      author       = {Yu, Hao and others},
      year         = {2024},
      howpublished = {arXiv:2405.07437}
    }

    Reference

  97. The Lean Theorem Prover (System Description)

    Leonardo de Moura, Soonho Kong, Jeremy Avigad, Floris van Doorn, Jakob von Raumer

    International Conference on Automated Deduction, pp. 378-388 · 2015

    BibTeX
    @inproceedings{demoura2015lean,
      author    = {de Moura, Leonardo and Kong, Soonho and Avigad, Jeremy and van Doorn, Floris and von Raumer, Jakob},
      title     = {The {Lean} Theorem Prover (System Description)},
      booktitle = {International Conference on Automated Deduction},
      pages     = {378--388},
      year      = {2015}
    }

    Conference paper

  98. AlphaProof: AI Achieves Silver-Medal Standard Solving IMO Problems

    Google DeepMind

    Google DeepMind Blog · 2024

    BibTeX
    @article{alphaproof2024,
      author    = {{Google DeepMind}},
      title     = {{AlphaProof}: {AI} Achieves Silver-Medal Standard Solving {IMO} Problems},
      journal   = {Google DeepMind Blog},
      year      = {2024}
    }

    Journal article

  99. Multi-Level Information Retrieval Augmented Generation for Knowledge-based Visual Question Answering

    Omar Adjali, Olivier Ferret, Sahar Ghannay, Herve Le Borgne

    Proceedings of EMNLP · 2024

    BibTeX
    @inproceedings{adjali2024multilevelvqa,
      title     = {Multi-Level Information Retrieval Augmented Generation for Knowledge-based Visual Question Answering},
      author    = {Adjali, Omar and Ferret, Olivier and Ghannay, Sahar and Le Borgne, Herv{\'e}},
      booktitle = {Proceedings of EMNLP},
      year      = {2024}
    }

    Conference paper

  100. MemoryBank: Enhancing Large Language Models with Long-Term Memory

    Wanjun Zhong, Lianghong Guo, Qiqi Gao, He Ye, Yanlin Wang

    Proceedings of AAAI · 2024

    BibTeX
    @article{zhong2024memorybank,
      author    = {Zhong, Wanjun and Guo, Lianghong and Gao, Qiqi and Ye, He and Wang, Yanlin},
      title     = {{MemoryBank}: Enhancing Large Language Models with Long-Term Memory},
      journal   = {Proceedings of AAAI},
      year      = {2024}
    }

    Journal article

  101. Memorizing Transformers

    Yuhuai Wu, Markus N. Rabe, DeLesley Hutchins, Christian Szegedy

    Proceedings of ICLR · 2022

    BibTeX
    @article{wu2022memorizing,
      author    = {Wu, Yuhuai and Rabe, Markus N. and Hutchins, DeLesley and Szegedy, Christian},
      title     = {Memorizing Transformers},
      journal   = {Proceedings of ICLR},
      year      = {2022}
    }

    Journal article

  102. The Information Bottleneck Method

    Naftali Tishby, Fernando C. Pereira, William Bialek

    arXiv preprint physics/0004057 · 2000

    BibTeX
    @article{tishby2000information,
      title={The Information Bottleneck Method},
      author={Tishby, Naftali and Pereira, Fernando C. and Bialek, William},
      journal={arXiv preprint physics/0004057},
      year={2000}
    }

    Journal article

  103. Evaluating Recommender Systems

    Asela Gunawardana, Guy Shani

    Recommender Systems Handbook (chapter) / technical report versions exist · 2015

    BibTeX
    @article{gunawardana2015evalrecsys,
      title   = {Evaluating Recommender Systems},
      author  = {Gunawardana, Asela and Shani, Guy},
      journal = {Recommender Systems Handbook (chapter) / technical report versions exist},
      year    = {2015},
      note    = {See Microsoft Research PDF for detailed metrics discussion}
    }

    Journal article

  104. BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models

    Nandan Thakur, Nils Reimers, Andreas Ruckle, Abhishek Srivastava, Iryna Gurevych

    NeurIPS Datasets and Benchmarks Track · 2021

    BibTeX
    @inproceedings{thakur2021beir,
      title     = {{BEIR}: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models},
      author    = {Thakur, Nandan and Reimers, Nils and R{\"u}ckl{\'e}, Andreas and Srivastava, Abhishek and Gurevych, Iryna},
      booktitle = {NeurIPS Datasets and Benchmarks Track},
      year      = {2021},
      note      = {Also on arXiv:2104.08663}
    }

    Conference paper

  105. MS MARCO: A Human Generated MAchine Reading COmprehension Dataset

    Payal Bajaj, Daniel Campos, Nick Craswell, Li Deng, Jianfeng Gao, Xiaodong Liu, Rangan Majumder, Andrew McNamara, et al.

    arXiv:1611.09268 · 2016

    BibTeX
    @misc{bajaj2016msmarco,
      title        = {{MS MARCO}: A Human Generated MAchine Reading COmprehension Dataset},
      author       = {Bajaj, Payal and Campos, Daniel and Craswell, Nick and Deng, Li and Gao, Jianfeng and Liu, Xiaodong and Majumder, Rangan and McNamara, Andrew and Mitra, Bhaskar and Nguyen, Tri and Rosenberg, Michael and Song, Xia and Wang, Alina and others},
      year         = {2016},
      howpublished = {arXiv:1611.09268},
      note         = {Author list abbreviated}
    }

    Reference

  106. KILT: a Benchmark for Knowledge Intensive Language Tasks

    Fabio Petroni, Aleksandra Piktus, Angela Fan, Patrick Lewis, Majid Yazdani, Nicola De Cao, James Thorne, Yacine Jernite, et al.

    Proceedings of NAACL · 2021

    BibTeX
    @inproceedings{petroni2021kilt,
      title     = {{KILT}: a Benchmark for Knowledge Intensive Language Tasks},
      author    = {Petroni, Fabio and Piktus, Aleksandra and Fan, Angela and Lewis, Patrick and Yazdani, Majid and De Cao, Nicola and Thorne, James and Jernite, Yacine and Karpukhin, Vladimir and Maillard, Jean and Plachouras, Vassilis and Rockt{\"a}schel, Tim and Riedel, Sebastian},
      booktitle = {Proceedings of NAACL},
      year      = {2021},
      note      = {Also on arXiv:2009.02252}
    }

    Conference paper

  107. MTEB: Massive Text Embedding Benchmark

    Niklas Muennighoff, Nouamane Tazi, Loic Magne, Nils Reimers

    Proceedings of EACL, pp. 2014-2037 · 2023

    BibTeX
    @inproceedings{muennighoff2023mteb,
      title     = {{MTEB}: Massive Text Embedding Benchmark},
      author    = {Muennighoff, Niklas and Tazi, Nouamane and Magne, Lo{\"i}c and Reimers, Nils},
      booktitle = {Proceedings of EACL},
      pages     = {2014--2037},
      year      = {2023}
    }

    Conference paper