Search

Search papers and lessons

Improving language models by retrieving from trillions of tokens

Sebastian Borgeaud, Arthur Mensch, Jordan Hoffmann et al. · 2021

Borgeaud et al. (2021) add a trillion-token retrieval database to a Transformer, so a 7.5B-parameter model matches much larger models without storing its facts in its weights.

On this page

  • Colour = topic mix
  • Discrete math
  • Neural network basics
  • Calculus
  • Linear algebra
  • Probability
  • Language & LLMs
  • ReadReady to readNot yet

TL;DR

Borgeaud and colleagues show that a language model can be made much stronger by letting it look up text from a huge database while it writes, rather than by making the network bigger. Their model, RETRO, splits its input into chunks, fetches earlier passages similar to the previous chunk from a database of about 2 trillion tokens, and attends to them. A RETRO model with 7.5 billion parameters is comparable to GPT-3 and Jurassic-1 on the Pile benchmark, despite using 25 times fewer parameters.

Builds on: Retrieval-Augmented Generation, Approximate Nearest Neighbor Search, Transformer · Leads to: the retrieval-augmented language models that followed it (no lesson linked yet)

Why it mattered

Through 2021, the standard way to make a language model better was to make it larger and train it on more text. Those models store what they know in their weights, so updating a fact means retraining. RETRO showed that a large part of the gain can come from a separate memory that the model reads at prediction time. The memory can be updated by changing the database, and the model does not need to be retrained to use it.

The paper's own comparison table places it against continuous cache, kNN-LM, Spalm, DPR, REALM, RAG, FiD and EMDR squared. Its distinguishing choices are a frozen encoder for the search keys, retrieval at the level of chunks rather than single tokens or whole prompts, and a database of trillions of tokens that is consulted throughout training and generation. The authors also argue that retrieval makes outputs easier to inspect, because one can see which neighbouring passages the model used.

The problem

A language model assigns a probability to text one token at a time, so that the probability of a sequence is the product of the probabilities of each token given the tokens before it. A large model can only reproduce what it has memorised or inferred, and that is costly: making it bigger increases both the computation for every token and the memory needed to store facts.

Earlier retrieval approaches had two limits. Token-level methods such as kNN-LM stored one vector per token, which is far too large for a database of trillions of tokens. Question-answering retrievers such as DPR retrieved once, for a whole question, and were trained on tasks of that kind. The paper needed a method that retrieves during generation, at the level of chunks, at a scale of trillions of tokens, while staying fast enough to run for every chunk of the output.

How it works

RETRO has three moving parts: a database of text chunks indexed by a frozen encoder, a retrieval step that finds neighbours for each chunk of input, and a decoder that reads those neighbours through chunked cross-attention. The paper's toy figure makes the bookkeeping easy to follow: a sequence of 12 tokens is split into 3 chunks of 4 tokens, and each chunk retrieves 2 neighbours. The real model uses 2048-token sequences cut into 64-token chunks.

  1. Build the database once. Each entry is a pair of consecutive 64-token chunks, called [N,F][N, F]. NN is the neighbour text used to find the entry, and FF is the text that follows it in the original document. The key for NN is the average of a frozen BERT model's token embeddings, and the value is the pair itself.
  2. Split the input. A training sequence of 2048 tokens is cut into 32 chunks of 64 tokens. Chunk CuC_u is the uu-th of these.
  3. Retrieve neighbours for each chunk. BERT embeds chunk CuC_u, and the system finds its nearest keys using squared Euclidean distance on those embeddings. It keeps the kk closest entries, with k=2k = 2 in training, and returns their [N,F][N, F] values. Because the keys come from a frozen model, the neighbours for every chunk can be computed in advance and stored with the data. In the toy figure, the first chunk retrieves nothing, so it has no retrieval input.
  4. Encode the neighbours. Each retrieved neighbour, of length 128 when NN and FF are joined, goes through a small bidirectional Transformer encoder. The encoder is conditioned on the activations of the chunk that retrieved it, so the representation of a neighbour depends on the query.
  5. Attend to the neighbours without breaking the order of tokens. Inside the decoder, some layers hold a chunked cross-attention step. The tokens of chunk CuC_u attend to the encoded neighbours of that chunk. The last token of chunk CuC_u is the first one allowed to see them, and the rest of Cu+1C_{u+1} sees them after that. The first m−1m-1 tokens of a chunk get no retrieval input at all. This keeps the model autoregressive, meaning each prediction depends only on earlier tokens.
  6. Predict the next token. The decoder's output gives a probability for every token in the vocabulary. The model is trained to make the true next token as likely as possible, and when it generates text, it retrieves new neighbours at the end of each chunk and continues.
flowchart LR
  A["Input chunk C_u"] --> B["Frozen BERT embedding"]
  B --> C["Nearest-neighbour search over trillions of tokens"]
  C --> D["k neighbours [N, F]"]
  D --> E["Bidirectional encoder"]
  A --> F["Decoder layers"]
  E --> G["Chunked cross-attention"]
  F --> G
  G --> H["Next-token probabilities"]

The retrieval keys do not change during training, which is why the search can run once for the whole dataset. The paper reports that querying a database of 2 trillion tokens takes about 10 milliseconds, and the cost is amortised over the chunk.

The math

The model is a standard autoregressive language model with one new input, the retrieved neighbours. The formulas below follow the paper's notation.

Definition: Autoregressive factorisation
For a sequence of tokens x1,…,xnx_1, \dots, x_n, the probability is the product of the probabilities of each token given all earlier tokens: p(x1,…,xn)=∏ip(xi∣x<i)p(x_1, \dots, x_n) = \prod_i p(x_i \mid x_{\lt i}). The model is trained to maximise the sum of the logs of these probabilities.

Step 1: the retrieval-enhanced likelihood

Split a sequence XX of nn tokens into ll chunks C1,…,ClC_1, \dots, C_l, each of size m=n/lm = n / l. Let \textscRetD(Cu)\textsc{Ret}_{\mathcal{D}}(C_u) be the set of kk neighbours of chunk CuC_u in the database D\mathcal{D}. The paper's log-likelihood is

L(X∣θ,D)=∑u=1l∑i=1mℓθ(x(u−1)m+i∣(xj)j<(u−1)m+i, (\textscRetD(Cu′))u′<u)L(X \mid \theta, \mathcal{D}) = \sum_{u=1}^{l} \sum_{i=1}^{m} \ell_{\theta}\left(x_{(u-1)m+i} \mid (x_j)_{j < (u-1)m+i},\ (\textsc{Ret}_{\mathcal{D}}(C_{u'}))_{u' < u}\right)

Read this in words: the probability of each token depends on the earlier tokens in the sequence and on the neighbours of the chunks before its own chunk. The neighbours of the first chunk are empty, so its likelihood does not use retrieval. The neighbours of CuC_u are not used to predict tokens inside CuC_u, which keeps the likelihood a valid autoregressive one.

Step 2: the search key

Each entry has a key \textscBert(N)\textsc{Bert}(N), the mean of BERT's token embeddings for NN. A chunk CC is compared with entries using the squared Euclidean distance

d(C,N)=∥\textscBert(C)−\textscBert(N)∥22d(C, N) = \lVert \textsc{Bert}(C) - \textsc{Bert}(N) \rVert_2^2

The kk entries with the smallest distance are the neighbours. Because BERT is frozen, the distance does not need a retriever that is trained with the language model.

Step 3: the cross-attention

Cross-attention lets a query vector hh read a set of encoded neighbours YY. The paper's simplest form is

\textscCa(h,Y)=softmax⁡(YKQTh) YV\textsc{Ca}(h, Y) = \operatorname{softmax}(Y K Q^{T} h)\, Y V

where KK and QQ are learned matrices that map the neighbour and query vectors into a shared comparison space, and VV maps the neighbour vectors to the values that are mixed together. The softmax turns the scores into weights that add up to one, so the output is a weighted average of the neighbour values. The paper uses several heads of this operation, with positional encodings added inside the softmax.

Step 4: the reading

The paper evaluates bits per byte instead of loss, because bits per byte does not depend on the tokenizer. For a set of evaluation chunks, let r(C)=s/mr(C) = s / m be the fraction of a chunk that is copied from training data, where ss is the length of the longest shared token substring. The filtered score

bpb(α)=∑C: r(C)≤αℓ(C)∑C: r(C)≤αN(C)\mathrm{bpb}(\alpha) = \frac{\sum_{C:\, r(C) \le \alpha} \ell(C)}{\sum_{C:\, r(C) \le \alpha} N(C)}

averages the log-loss ℓ(C)\ell(C) over the chunks whose overlap is at most α\alpha, divided by the bytes N(C)N(C) they encode. A small α\alpha measures performance on chunks that are almost new, which is the key check for leakage.

Results

Language modelling. On Wikitext103 with the full MassiveText database, the paper reports a validation perplexity of 3.21 and a test perplexity of 3.92 for RETRO with 1,792 billion database tokens. The baseline transformer without retrieval reached 21.53 and 22.96, and kNN-LM with a Wikipedia database reached 18.52 and 19.54. The authors caution that the very low perplexities are partly due to overlap with Wikitext103 that their deduplication did not catch, so these numbers mix retrieval with leakage. With only Wikipedia (4 billion tokens) as the database, RETRO scored 18.46 and 18.97, close to kNN-LM.

The Pile. The 7.5-billion-parameter RETRO outperforms Jurassic-1 (178 billion parameters) and Gopher (280 billion parameters) on a majority of the Pile test sets, and it outperforms its own 7-billion baseline on most of them. It does not beat the baseline on the dm_mathematics and ubuntu_irc subsets, which the authors attribute to unhelpful neighbours.

Scaling. The gain from retrieval stays roughly constant for models from 150 million to 7 billion parameters. The conclusion says the gains correspond to non-retrieval models with about 10 times more parameters on certain datasets. Larger models make better use of more neighbours: the 172-million model improves with up to 10 neighbours, and the 7-billion model with up to 40.

Question answering. After fine-tuning, RETRO 7.5B reaches an exact-match accuracy of 45.5 percent on Natural Questions, against 30.4 for the same-size closed-book baseline. RAG reported 44.5, DPR 41.5, FiD 51.4 and FiD with distillation 54.7. RETRO is competitive with the retrieval methods listed but does not reach FiD. The authors hypothesise that FiD's T5 base model relies more on its encoder output than RETRO does, which matters for question answering.

Retrofitting. An existing transformer can be given retrieval by freezing its weights and training only the new cross-attention and neighbour-encoder parameters, which are under 10 percent of the weights for the 7-billion model. This needed about 6 million sequences, around 3 percent of the pre-training sequences, and the original model's no-retrieval performance is preserved exactly.

Storage. A token-level index for kNN-LM over the 4 billion Wikipedia tokens needs about 15 terabytes. RETRO's index needs 215 gigabytes for Wikipedia and 93 terabytes for MassiveText.

Limits. The database and the test sets overlap, so the authors measure performance on chunks with little overlap. RETRO still beats the baseline down to an overlap threshold of 12.5 percent, which the authors take as evidence of real generalisation. The paper also reports that some of its gains come from copying training text, which the leakage analysis makes visible. Its privacy and bias concerns are discussed in the paper's related-work section, and the authors note that the retrieval database can be filtered to remove harmful text.

Reading guide

Check yourself

QuestionRETRO splits a 2048-token training sequence into chunks of 64 tokens. How many chunks is that, and how many tokens does the first chunk retrieve?Show answer
2048 divided by 64 is 32 chunks. The first chunk retrieves no neighbours, because its likelihood does not depend on retrieval data.
QuestionIn the paper's Wikitext103 table, the baseline transformer has a test perplexity of 22.96 and the RETRO model with the full MassiveText database has 3.92. By what factor is the perplexity reduced?Show answer
22.96 divided by 3.92 is about 5.86, so the perplexity is reduced by a factor of nearly 6. The authors warn that this comparison mixes retrieval gains with leakage from the test data.
QuestionWhy does the paper retrieve by chunk instead of by token, and why does it use a frozen BERT for the keys?Show answer
Storing one vector per token for trillions of tokens is far too large, as the kNN-LM comparison shows. Retrieving by chunk reduces storage and computation by a large factor. A frozen BERT means the keys can be computed once and stored, so the database does not need to be re-embedded during training.
QuestionA team wants to add retrieval to an existing 7-billion-parameter model without retraining it from scratch, and without any change to its no-retrieval output. Using the paper, what should they do?Show answer
Freeze the pre-trained weights and train only the chunked cross-attention and neighbour-encoder parameters, which are under 10 percent of the weights. That takes around 6 million sequences in the paper's experiment, and the model's no-retrieval performance is unchanged because the original weights are not touched.

Sources

  • Borgeaud, Mensch, Hoffmann, Cai, Rutherford, Millican, van den Driessche, Lespiau, Damoc, Clark, de Las Casas, Guy, Menick, Ring, Hennigan, Huang, Maggiore, Jones, Cassirer, Brock, Paganini, Irving, Vinyals, Osindero, Simonyan, Rae, Elsen and Sifre, "Improving language models by retrieving from trillions of tokens", arXiv:2112.04426 (2021): https://arxiv.org/abs/2112.04426
  • DOI record for arXiv:2112.04426: https://doi.org/10.48550/arXiv.2112.04426

Read the full paper

Sebastian Borgeaud, Arthur Mensch, Jordan Hoffmann et al., 2021. arXiv:2112.04426