Article

What is Retrieval-Augmented Generation (RAG)?

VishalPublished·12 min read

Introduction

This article presents the Retrieval-Augmented Generation (RAG) model as introduced by Patrick Lewis et al. (referred to as "the authors" moving forward) in Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Facebook AI, 2020). RAG is a consequential model that improved the state of the art performance in knowledge intensive natural language tasks - Open Domain Question Answering, Jeopardy Question Generation, and Fact Verification.

The high level goal is to enable machines to generate text rooted in knowledge. Prior to RAG, we had parametric models (LLMs) that were trained on large datasets and implicitly stored that knowledge within their parameters. These models were then able to generate text from their learned knowledge. However, such models had some notable drawbacks: it was not possible to know the source of their information and updating or adding to their knowledge required expensive re-training. RAG combines parametric models with data at runtime to improve on knowledge based generation and overcome the drawbacks of the prior models.

RAG is made up of two components: the retriever and the generator. The retriever takes the input query and retrieves relevant knowledge from the available data. Then, the input query and the relevant data (as returned by the retriever) are passed to the generator which outputs more reliable and relevant text.

Before looking at the details of RAG, let's walk through a couple examples:

Prior to RAG:

What are proofs? -> LLM -> Proofs are ...

Note that the output depends on the training data and the training process the LLM underwent and that the model has no way to present the source of its output.

With RAG:

What are proofs? -> retriever -> what are proofs? + wikipedia page for proofs -> LLM -> Proofs are ...

The authors show that RAG outperforms only having parametric models and hopefully this gives an intuition for that result.

P.S. This is how the AI Tutor on Turing Notes knows about all the articles on the site! If you're curious to see an implementation, view my simple LlamaIndex based RAG agent on GitHub.

What does this technology build on?

RAG builds on several key transformer based models. I will try to build intuition for why we need them and what they do at a high level, but we will take them to be black boxes for the purposes of understanding RAG.

Let's state our goal again: given an input sentence/question, we want to generate relevant and knowledge grounded output sentence(s).

  • The first question then is how do we represent the input and its meaning?

Bidirectional Encoder Representations from Transformers (BERT) encodes the semantic meaning of text into dense vectors by considering the left and right context (bidirectional) for a given token.

So, given an input sentence ss, we can retrieve a vector representation that encodes the semantic meaning of ss, as learned by the model through its training.

  • How do we retrieve semantically relevant data from a dataset given the semantic vector representation of our input?

Maybe you guessed it! We can represent the semantic meaning of all our data as vectors using BERT and perform a search.

Dense Passage Retrieval (DPR) retrieves the top kk semantically relevant (positive) documents to a query qq. It is built on a bi-encoder model - one encoder (EqE_q) for queries and another (EpE_p) for passages. All passages are pre-encoded and stored in a vector database like Facebook AI Similarity Search (FAISS). At runtime, the query is encoded and the nearest kk neighbours in the embedding space are retrieved.

DPR is trained using contrastive learning on (query, positive passage, negative passage) triplets - fine tuning the encoders to minimize the distance between queries and positive passages, and maximizing it for negative ones.

That is, DPR uses BERT embeddings along with an algorithm to find the closest neighbours in a vector space to find the most relevant documents to a given query.

  • How do we generate text?

Generative Pre-trained Transformer (GPT) is a decoder-only model that generates human-like text in an autoregressive manner - predicting the next token based on all prior ones. The model uses the stored semantic meaning in its parameters, learned through training, to predict tokens.

This is arguably the most popular model in use today. You likely used it to write emails among other things.

It is beneficial to note a detail about decoder models to understand how RAG decodes:

Beam decoding/search is a common decoding algorithm autoregressive models such as GPT use to produce sequences. The idea is to keep track of the top kk (beam width) partial sequences of length nn with the highest probability. At each step, all possible following tokens are explored for each of the top kk sequences, the probabilities are calculated for each of the new sequences of length n+1n+1, and the top kk sequences are kept. The sequence with the highest probability at the end is the final output.

Given transition probabilities p(yi∣x,y1:i−1)p(y_i|x, y_{1:i-1}), we can run beam decoding to retrieve an output sequence.

  • How do we generate semantically relevant text given some input text?

Bidirectional and Auto-Regressive Transformers (BART) combines BERT’s bidirectional encoder with GPT’s autoregressive decoder, forming a sequence-to-sequence model for tasks like summarization, translation, and knowledge-grounded text generation - the exact capability leveraged in RAG.

That is, given a sentence ss, we can encode it in vector vv and ultimately output a semantically relevant sentence pp.

Now let's look at how RAG achieves the goal given these models.

The technology

Architecture

The RAG pipeline combines a retriever that finds relevant information (from a defined dataset) with a generator that conditions on that information to produce responses.

The retriever

The authors use Wikipedia pages as data for their experiments. Pages are broken down into disjoint documents and represented as vectors that encode their meaning. The collection of the vectors is referred to as the vector index of Wikipedia.

The retriever is a DPR model that encodes the meaning of a query xx into a vector and retrieves the top kk semantically relevant documents from the vector index.

So how do we denote semantically relevant documents? Vectors closer to each other (higher dot product) are said to have higher semantic similarity. This is an (magical?) output of encoder models like BERT.

Formally, we represent the probability of retrieving document zz given query xx with pη(z∣x)p_\eta(z|x) where

pη(z∣x)∝exp⁡(d(z)Tq(x));d(z)=BERTd(z);q(x)=BERTq(x)p_\eta(z|x) \propto \exp(d(z)^T q(x)) ; \quad d(z) = BERT_d (z) ; \quad q(x) = BERT_q(x)

η\eta denotes the model parameters, d(z)d(z) is the document vector embedding, and q(x)q(x) is the query vector embedding. The top kk documents are the documents for which pη(zi∣x)p_\eta(z_i|x) is the highest.

Given a query xx, we encode the query as a vector q(x)q(x) and find the top kk documents using Maximum Inner Product Search (MIPS) which can be approximately solved in sub-linear time. More simply, documents whose vector embeddings d(zi)d(z_i) are closer to that of the query are returned.

The generator

The generator is a sequence to sequence (encoder-decoder) model that generates semantically relevant output yy given input xx.

The authors use BART-large, which is a pre-trained model with 400M parameters, and concatenate the query xx with the retrieved document zz as input to the model.

Formally, the probability of next token yiy_i given query xx, document zz, and output tokens y1,…,yi−1y_1, \dots, y_{i-1} is pθ(yi∣x,z,y1:i−1)p_\theta(y_i|x, z, y_{1:i-1}) where θ\theta represents the model parameters.

Similar to the generator, the sequence with the highest probability is the final output. The details of the generation depends on the RAG model and is presented in the following section.

Models

The authors present and compare two RAG models:

RAG-Sequence

In theory, we can think of each retrieved document ziz_i being used to generate a complete output sequence yiy_i and the most relevant output sequence being the final output y.

In practice, the retriever retrieves the top kk documents for input xx and the generator calculates the probability for each output sequence which is then marginalized over the documents.

pRAG-Sequence(y∣x)≈∑z∈top-k(p(⋅∣x))pη(z∣x)pθ(y∣x,z)=∑z∈top-k(p(⋅∣x))pη(z∣x)∏iNpθ(yi∣x,z,y1:i−1)p_{\text{RAG-Sequence}}(y|x) \approx \sum_{z \in \text{top-}k(p(\cdot|x))} p_\eta(z|x) p_\theta(y|x, z) = \sum_{z \in \text{top-}k(p(\cdot|x))} p_\eta(z|x) \prod_{i}^{N} p_\theta(y_i|x, z, y_{1:i-1})

pn(z/x)p_n(z/x) is the probability of retrieving document zz given query xx and pθ(y,x,z)p_\theta(y, x, z) is the probability of generating yy given x,zx, z which can be expanded to the products of the probabilities of generating each token yiy_i.

The authors introduce the concept of "Thorough Decoding" to decode the probabilities and retrieve the output sequence. The idea is to run beam search to find the sequence of highest probability for each document, let's call this set YY. For each sequence y∈Y,z∈top-k(p(⋅∣x))y \in Y, z \in \text{top-}k(p(\cdot|x)), pθ(y∣x,zi)p_\theta(y|x, z_i) is calculated. Multiplying with pη(zi∣x)p_\eta(z_i|x) and summing over all the documents, we can find p(y∣x)p(y|x). The sequence with the highest probability is the final output sequence.

For large ∣Y∣|Y|, the authors propose an approximation: pθ(y∣x,z)≈0p_\theta(y|x, z) \approx 0 if yy was not returned as the output for beam search on x,zx, z. They refer to this process as "Fast Decoding" which is more efficient by removing the passes needed to calculate pθ(y∣x,z)p_\theta(y|x, z) after YY has been retrieved.

RAG-Token

In theory, we can think of each target token in the output sequence yiy_i being generated by the most relevant document for that token ziz_i. That is, we could use the second document to generate y1y_1 and the fourth for y2y_2 and so on. Every document is considered while generating token ii. The sequence with the highest probability is the final output sequence.

In practice, the retriever retrieves the top kk documents and the generator calculates the probability for each output token over each document before marginalising; repeating for every following token.

pRAG-Token(y∣x)≈∏iNp(yi∣x,y1:i−1)=∏iN∑z∈top-k(p(⋅∣x))pη(z∣x)pθ(yi∣x,z,y1:i−1)p_{\text{RAG-Token}}(y|x) \approx \prod_{i}^{N} p(y_i|x, y_{1:i-1}) = \prod_{i}^{N} \sum_{z \in \text{top-}k(p(\cdot|x))} p_\eta(z|x) p_\theta(y_i|x, z, y_{1:i-1})

Because we can calculate the probability for a generating the next token (over all documents), the above can be translated to the following transition probability for a autoregressive seq2seq generator which can be then be plugged into a standard beam decoder to retrieve the final output sequence.

pθ′(yi∣x,y1:i−1)=∑z∈top-k(p(⋅∣x))pη(zi∣x)pθ(yi∣x,zi,y1:i−1)p'_\theta(y_i|x, y_{1:i-1}) = \sum_{z \in \text{top-}k(p(\cdot|x))} p_\eta(z_i|x) p_\theta(y_i|x, z_i, y_{1:i-1})

Note that the same could not have been done for RAG-sequence, because sequence generated with document ziz_i may not even be generated with document zjz_j.

Training

A RAG pipeline can be setup with a pre-trained retriever and generator. The authors show that such a model outperforms a parametric only model.

In addition, the authors show that the retriever and generator can be fine tuned to work together to perform even better.

Training is performed end to end using input/output pairs (xi,yi)(x_i, y_i) minimising for the negative log likelihood for each target marginalized over the documents ∑j−log(p(yi∣xi))\sum_{j} - log (p(y_i|x_i)).

This is a common mathematic technique used when we want to maximize the probability of yiy_i given xix_i.

The weights of the document encoder of the retriever are not changed due to the expensive work of re-creating the entire vector index as the weights change. The authors note that is not necessary for strong performance of the RAG model.

What are the implications of this technology?

The authors demonstrate that RAG delivers significant performance improvements over both parametric-only models (e.g., BART) and retrieval-only models (e.g., DPR) across several knowledge-intensive NLP tasks:

  • Open Domain Question Answering: Given a question, can a model respond with the exact factual answer. RAG outperformed other models and enables answering questions for which the exact answer does not exist in the retrieved documents through generation.
  • Abstractive Question Answering: Given a question, 10 "gold" passages from a search engine, can a model generate the reference answer? Even though RAG did not observe the gold passages, only the question answer pairs, its performance was comparable to parametric models that did observe the gold passages. The authors also report RAG to result in lesser hallucinations and more factual answers.
  • Jeopardy Question Generation: Given an answer, can a model generate the question? The evaluation included human input to assess if the output was relevant to the answer and if it was factual. Human evaluation results found BART to be more factual in 7.2% of the cases and RAG to be more factual in 42.7% cases. Overall RAG-Token outperformed RAG-Sequence both outperforming BART.
  • Fact Verification: Given a claim, can a model correctly classify it as supported or refuted by Wikipedia or that there is not enough information. RAG scores were within 4.3% of the state of the art models despite their more expensive and specific training.

In summary, RAG outperforms prior models in generating factual knowledge-grounded responses with fewer hallucinations. In addition, it does not need more training to update its knowledge. This has several positive implications on society including explainable, verifiable, and updatable AI systems that can ground responses on new or proprietary knowledge.

RAG has since inspired a wave of retrieval-augmented systems, including Atlas (Meta), WebGPT (OpenAI), and foundation models like Gemini and GPT-4, which apply similar retrieval-grounded reasoning at scale.

What are the limitations and drawbacks?

RAG relies on several components that each have drawbacks

  • Retriever dependency: If the retriever does not find relevant documents, then the output quality relies on the generator and its parametric memory.
  • Non-parametric memory quality: Retrieved documents could be incomplete, irrelevant, incorrect, or biased which could degrade the quality of the responses.
  • Limited reasoning: Reasoning is limited by the capability of the generator given the retrieved documents, no loops of deeper reasoning.
  • Context length constraints: Only a limited number of documents before confusing or overflowing the generator.
  • Storing and maintaining data: RAG requires high quality and up to date information which can be expensive to maintain.

Ultimately, RAG’s effectiveness depends on the quality of data, retrieval, and generation, but it remains a foundational step toward grounded, factual, and adaptive AI.

References

  • Lewis, Patrick et al. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks. (Facebook AI, 2020).
  • Karpukhin, Vladimir et al. Dense Passage Retrieval for Open-Domain Question Answering. (2020).
  • Devlin, Jacob et al. BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. (2018).
  • Lewis, Mike et al. BART: Denoising Sequence-to-Sequence Pre-training for Natural Language Generation, Translation, and Comprehension. (2019).
Comments (0)
No comments yet. Be the first to comment!