Generalization through Memorization: Nearest Neighbor Language Models
Paper · 2019 · Urvashi Khandelwal, Omer Levy, Dan Jurafsky et al.
Summary
A language model can recognize that two passages call for the same kind of continuation and still assign little probability to the word that actually comes next. This paper asks whether the ability to recognize similar contexts can help recover continuations the usual prediction mechanism overlooks. The authors’ proposal, kNN-LM, starts with a trained Transformer and gives it access to a searchable collection of examples. Each example pairs a vector representing the text up to a particular position with the token that followed it. At prediction time, the system uses the current context to find nearby vectors, gives closer examples greater influence, and combines their suggested continuations with the Transformer’s ordinary predictions. The authors build the collection by running the trained network over text with its parameters fixed.
The central experiment uses the same Wikitext-103 training text for both the original training and the searchable collection. On the test set, the base Transformer achieves a perplexity of 18.65. Perplexity measures how much probability a system gives to the actual continuations across a corpus, with lower values indicating better predictions. Adding retrieval from the training set brings test perplexity to 16.12. A separate continuous cache, which retrieves from earlier in the test document, brings the combined system to 15.79. On the Books test set, retrieval from the Books training collection brings perplexity from 11.89 to 10.89. The Wikipedia and Books results show that the searchable copies can help even when every example in them was already available during training.
Changing the collection also changes which text the system can draw on at prediction time. On held-out Wiki-3B text, a Transformer trained on Wiki-100M reaches 13.73 perplexity when it can retrieve from the larger corpus. The comparison Transformer trained on the larger corpus reaches 15.17 through its ordinary prediction mechanism. In a domain adaptation experiment, a Wikipedia-trained Transformer scores 34.84 perplexity on held-out Books text, and a searchable collection built from Books lowers that value to 20.47. Building these collections requires encoding and indexing the text, and using them adds a search at prediction time. The Transformer itself needs no further training for either change.
The authors’ examples include rare names, facts, and passages for which the collection holds an unusually close match. Some retrieved passages share the same short phrase but differ in how well they fit the rest of the context. In such cases the learned vectors can put the more relevant passage much closer to the query. This helps explain how explicit memory can improve predictions on unseen text. The system can reuse the continuation of a past example whenever the trained representation puts a new context near it. The perplexity results measure the overall benefit of that arrangement. The examples show particular ways in which it can help.
Deep dive: Generalization through Memorization: Nearest Neighbor Language Models
Nearest neighbor language modeling improves next-word prediction by retrieving similar contexts from a searchable collection of past examples. · about 34 minutes to read
The problem and its context
Recognizing similar situations and predicting their continuations
In autoregressive language modeling, the text before a position is the information available for predicting the token at that position. A token is a unit of text in the system’s vocabulary. It can be a word or a piece of one, depending on the corpus and the way it is segmented. The system assigns probabilities to the possible next tokens and can then use another observed or generated token to extend the context. In the paper’s evaluations, the observed text supplies these contexts, and the probabilities assigned to the actual continuations determine the score.
The paper distinguishes two jobs inside next-token prediction. The first is to represent the preceding text as a fixed-length vector. The second is to turn that vector into a probability distribution over the vocabulary. This distinction goes back to earlier neural approaches described in the paper, including A Neural Probabilistic Language Model. The authors ask how much useful information the learned representation makes available to a different prediction procedure. A standard predictor uses parameters learned over the corpus to score the possible next words. A nearest neighbor predictor can instead use the representation to locate specific occasions on which similar text occurred, then read out the next words directly.
The authors illustrate the distinction with two ways of introducing a work by Dickens, one framed as a statement about authorship and one using the verb wrote. A reader can see that the alternatives invite much the same kind of answer even when the relevant title is unknown to that reader. In the authors’ analogy, a neural network might likewise put the two contexts close together while giving too little probability to the particular title in the text. Finding a past occurrence that leads to that title requires an effective measure of context similarity. Producing the title through the regular output layer requires that the training process preserve its association with that kind of context in the parameters used for prediction.
This distinction matters when useful continuations are unevenly represented in the corpus. Common patterns supply many examples from which to learn. A specific name, date, or association may occur in only a few informative contexts. The paper uses the term long tail for patterns of this kind. When a rare example does exist in the training text, a retrieval system can keep its continuation attached to its context. The learned representation then determines which new contexts can benefit from that record. Exact repetition is one opportunity for reuse. A close match in meaning or structure can also make the stored example relevant.
The paper’s question is therefore more specific than whether a system improves when it receives more text. It first asks whether a different way of accessing the original training examples improves predictions while leaving the trained parameters fixed. This makes the source of the extra evidence clear. The datastore provides a new route to the examples, since the network used to encode a query is the same one that previously learned from the corpus. The authors then ask a second question about text the network never trained on. The same representation can encode that text and make it available for lookup, so the amount of text accessible during prediction can vary independently of the amount used for parameter training.
Earlier uses of memory and examples
Earlier approaches had already used a form of nearest neighbor lookup to exploit repetition within documents. The paper discusses Pointer Sentinel Mixture Models and the continuous cache. A continuous cache keeps representations of previous positions in a test document and uses their continuations as evidence at later positions. A rare word introduced in a document may recur there, so a mechanism that looks at the recent past has a direct source of evidence about that word. The authors point out that Transformer self-attention can also draw on recent words in the supplied context. A cache over a separate collection gives the system access to occurrences beyond the current document.
The paper identifies an online language modeling approach by Grave and colleagues as its closest predecessor. That approach searches previous hidden states to adapt to the text encountered over time. Its searchable memory by design reflects earlier observations in the stream. The principal datastore in kNN-LM is instead built from a designated training collection before evaluation. During the main retrieval experiments it is available as a fixed body of examples. In the experiment that combines approaches, the continuous cache contributes evidence from the current test document, while the training-set datastore contributes evidence from the prior collection. Their different sources of evidence explain why the two mechanisms can coexist.
The paper also traces example-based approaches in part-of-speech tagging and morphological analysis. In those applications, a prediction can draw on similar examples for which the desired label or analysis is already known. The kNN-LM version applies that principle to the continuation of a text prefix and uses a neural network to determine which prefixes are similar. Related work in computer vision had used nearest neighbors in learned representations, with goals that included interpretability and robustness. The authors see a particular opportunity in text because ordinary collections supply the labels for the memory automatically. Every position with a known continuation can contribute an example.
Several predecessors in language generation also used training instances at prediction time. Generating Sentences by Editing Prototypes sampled a training sentence and edited it to produce an output. Work on machine translation attended to retrieved examples, and Retrieve and Refine used similar responses from training data as material to refine in dialogue. In kNN-LM, the stored continuation is a single token. A lookup changes the probability of that token and of other candidates at one position. It does so after the representation network has been trained. The granularity and the point of integration are important because they allow an existing predictor to be augmented at inference without redesigning its training procedure.
A parallel line of work addressed language modeling chiefly by using more data for training. The paper cites examples including RoBERTa, XLNet, and Megatron-LM. The question kNN-LM adds to that discussion is where the benefit of extra text comes from. Training on an example gives it an opportunity to shape the shared parameters. Encoding and indexing it gives future queries a chance to find its particular continuation. The paper examines how much each route contributes in a controlled language modeling setup.
The method, step by step
What goes into the datastore
The method begins with a trained autoregressive predictor and a collection of text. Imagine stopping just before a token in that collection. Everything the network is allowed to see to the left of that position is the context. The network converts it into an internal vector, and the following token supplies the observed answer. The authors save the vector and the answer as a pair. At the next position, the preceding token has become part of the context, so the new vector and its associated answer form another pair. Repeating this procedure gives the collection a record for each target position.
The authors call this collection of pairs a key–value datastore. The key is what the system searches, and the value is what it reads after finding a match. In this case, the key represents the lead-up to an occurrence. The value is the identity of the token at that occurrence. Entries for the same value can have quite different keys, because the same token can occur after many different contexts. Conversely, several nearby keys may have different values. Similar prefixes often admit multiple continuations, and the method preserves that variation as evidence for a distribution.
At prediction time, the same network produces the same kind of vector for the current context. The search index finds stored vectors in its vicinity and returns their associated tokens. A nearby entry carries more weight than a distant entry. If a token is returned several times, the contributions from all of its occurrences are added. The resulting distribution is then combined with the network’s ordinary next-token distribution. These two distributions reflect different information. One summarizes what the trained parameters predict across the vocabulary. The other summarizes what followed the particular contexts selected by the search.
How kNN-LM builds memory and predicts a token
The steps in order.
The construction and lookup stages happen on different schedules. The encoding pass and index construction are done in advance for a collection. The query and combination are performed when a next-token probability is needed. Only the preceding context is used to make the query. The observed target at a stored position is available because the entire storage corpus is already known. The target at an evaluation position is used afterward to score the prediction.
The notation and probability calculation
The paper describes the prediction context as the sequence of tokens preceding the target position.
cₜ = (w₁, …, wₜ₋₁)
Here, t is the position to be predicted, cₜ is the context at that position, and w with a positional subscript denotes the token at that position. The parentheses indicate an ordered sequence. The ellipsis stands for the intervening tokens, from the initial token w₁ through wₜ₋₁, immediately before position t. In the implementation, the amount of preceding text that can be supplied is bounded by the context used for the example.
p(wₜ ∣ cₜ)
Here, p denotes a conditional probability distribution, wₜ is the next token at position t, and cₜ is the preceding context. The vertical bar means “given.” Before seeing which continuation occurs, the predictor assigns a probability to each candidate for wₜ. The probability of the observed token is the quantity used in evaluation.
The first construction equation describes which pairs are stored.
(𝒦, 𝒱) = { (f(cᵢ), wᵢ) ∣ (cᵢ, wᵢ) ∈ 𝒟 }
Here, 𝒟 is the collection of context–target examples from which the memory is built. The subscript i identifies one such example, whose context is cᵢ and whose actual next token is wᵢ. The trained network supplies f, a function that turns a context into a fixed-length vector. The pair (f(cᵢ), wᵢ) is the entry created from that example. 𝒦 denotes the keys and 𝒱 the associated values. The braces describe the collection of entries, the vertical bar introduces the condition for inclusion, and ∈ means that the original pair belongs to 𝒟. Operationally, the index retains an entry for every target position so that multiple occurrences can contribute to the later prediction.
For a query, the system applies f to the current context and finds nearby keys. A smaller distance means that a stored context is a closer match under the chosen representation and distance function. Each retrieved entry receives a weight obtained by exponentiating the negative distance. Reversing the sign gives the closest entries the largest weights. The exponential makes the strength of evidence depend on the distances themselves as well as the order in which neighbors are returned. When a single context is substantially closer than the rest, its token can dominate the retrieved distribution. When several contexts have comparable distances, their tokens can share the available weight.
pₖₙₙ(y ∣ x) ∝ ∑₍ₖᵢ,ᵥᵢ₎ ∈ 𝒩 𝟙[y = vᵢ] exp(−d(kᵢ, f(x)))
Here, x is the current context, y is a candidate next token, and pₖₙₙ(y ∣ x) is its probability under the nearest neighbor predictor. The symbol 𝒩 denotes the entries returned for the query. In each entry, kᵢ is the stored context vector and vᵢ is the stored continuation. The sum ∑ runs over those entries. The indicator 𝟙[y = vᵢ] includes the weight of an entry when its continuation equals y and gives that entry zero contribution to y otherwise. The distance function d compares the stored vector kᵢ with f(x), the vector for the current context. The expression exp is the exponential function and − changes the distance to its negative. The symbol ∝ indicates that the displayed sum is proportional to the probability. Dividing by the sum of the weights of all retrieved entries makes the resulting probabilities sum to one.
This procedure is equivalent to distributing probability among the retrieved occurrences and then pooling all occurrences that predict the same token. A token absent from the retrieved values has zero probability under this part of the system. A frequently retrieved continuation can gain support from several entries. A token found in just one entry can still rank first if its context is close enough. The vocabulary is that of the base predictor, so the probability from retrieval and the probability from the ordinary output can be combined token by token.
p(y ∣ x) = λ pₖₙₙ(y ∣ x) + (1 − λ) pₗₘ(y ∣ x)
Here, p(y ∣ x) is the final probability assigned to candidate y given context x. The term pₖₙₙ(y ∣ x) is the probability derived from the retrieved entries, and pₗₘ(y ∣ x) is the probability assigned by the trained network’s usual output. The parameter λ is the fraction of the mixture assigned to retrieval. The complementary fraction 1 − λ goes to the base predictor, and the plus sign adds the weighted terms. The authors select λ using validation data. For an intermediate setting, a token absent from the returned neighbors retains the probability supplied by its share of the ordinary distribution.
This final calculation is a linear interpolation, meaning a weighted average of the two distributions. It gives every query in a given setting the same mixture weight. The identities of the neighbors, the distribution of their distances, and the agreement among their continuations vary with each query. Those differences change the retrieval distribution within the fixed mixture. Keeping these roles distinct helps explain why the number of neighbors, the distance calculation, and the interpolation weight can each affect the result.
Choosing and indexing the vectors
The experiments use the decoder-only architecture and training procedure associated with Adaptive Input Representations for Neural Language Modeling. A decoder-only Transformer uses the available left context to make a next-token prediction. Self-attention combines information from earlier positions, and the successive layers compute internal states that the output mechanism eventually turns into vocabulary probabilities. The network in the paper has 16 layers, with 16 attention heads per layer. Its hidden states have 1024 dimensions and its feedforward layers have 4096 dimensions. The architecture has 247M trainable parameters. Its input contains 3072 tokens per example for Wikitext-103 and 1024 tokens per example for the other corpora.
The authors tried several internal states as possible representations. In the main setup they use the 1024-dimensional vector entering the feedforward network of the final layer. This point comes after self-attention and layer normalization. Layer normalization adjusts the scale of a layer’s activations. The extracted vector is used in the same way for stored contexts and for queries, which puts both in the same coordinate space. Retrieving with a late internal state also leaves the final prediction machinery available to compute the ordinary vocabulary distribution.
For Wikitext-103, the datastore pass gives target tokens a minimum of 1536 tokens of preceding context under the authors’ construction procedure. For the other corpora the specified minimum is 512 tokens. The encoder processes the collection in a single forward pass. A forward pass calculates the states and outputs for the supplied text. Training additionally adjusts the weights in response to prediction errors. For datastore construction the network is already trained, and the pass records existing states alongside the known target tokens.
Searching all the stored vectors individually would burden every prediction. The authors use FAISS, a library for large-scale similarity search, to organize the keys. The index groups vectors into clusters represented by centroids. A search can identify promising clusters using their centroids and look for individual neighbors within them. To construct the index, the authors randomly sample 1M keys and use them to learn 4096 centroids. They also quantize the keys to 64 bytes each, meaning that the search index stores compressed descriptions of the vectors. A query looks up 32 centroids and requests 1024 neighbors in the main experiments.
There are two distinct distance operations in this setup. The first helps the index select which entries to return. The second provides the scores for the probability calculation. In Wikitext-103 experiments, the authors recompute squared Euclidean distance from full-precision keys for the second operation. Euclidean distance measures ordinary geometric separation, and squaring it changes how rapidly the exponential weight decreases with separation. For the other corpora, the authors use the Euclidean distances returned by FAISS directly, based on quantized keys and without squaring. This makes evaluation faster. Thus the same retrieval-and-mixture equations support configurations with different scoring precision. The authors make the implementation available in the knnlm code repository.
Experiments and results
Corpora, baselines, and evaluation
The experiments cover encyclopedia articles and books in English. Wikitext-103 supplies 103M training tokens and 250K tokens in each of its development and test sets. It has a word-level vocabulary of 250K items. Books is the Toronto Books Corpus, with 0.7B tokens and complete books set aside for validation and testing. Holding out whole books allows the domain experiments to evaluate predictions in books excluded from the training collection. The article-based splits likewise reserve whole articles for Wiki-3B validation and testing. Toronto Books Corpus
Wiki-3B contains about 2.87B tokens of English Wikipedia. Wiki-100M is a randomly selected 100M-token subset of that corpus, sampled in complete articles. Because it comes from Wiki-3B, this smaller collection lets the authors ask how the same kind of text helps when it is available in different amounts for training or for retrieval. The smaller corpus supplies the examples that shape the representation in the retrieval scaling experiment. Larger portions of Wiki-3B can then populate the memory without changing the trained encoder.
The corpora other than Wikitext-103 use byte-pair encoding with the 29K vocabulary from BERT. This is a form of subword tokenization, in which the vocabulary can represent words with smaller pieces. A prediction in these experiments concerns the next unit under that vocabulary. The Wikitext-103 experiments use adaptive inputs and an adaptive softmax with tied weights, following the base architecture. The softmax is the output mechanism that turns scores into probabilities, and weight tying shares parameters between the input and output representations. The other corpora use the architecture without the adaptive input and softmax components. BERT
The training objective is negative log-likelihood. Assigning high probability to the observed token makes its contribution to this loss small. Assigning it very low probability makes its contribution large. Perplexity is the exponentiated negative log-likelihood for the held-out sequence on a per-token basis. Because the score depends on the probability of the observed target, the system can improve its perplexity by placing more probability on that target even when a different token still ranks first. The reported results therefore describe probability estimates across held-out text. Comparisons are most informative within an evaluation set and tokenization, where competing configurations are asked to score the same sequence of targets.
The evaluation scores 512 tokens per test example. For Wikitext-103, the predictor can also see up to 2560 earlier tokens as prior context. For the other corpora it can see up to 512 extra tokens. This procedure gives the scored block access to earlier text and reserves the perplexity calculation for the designated targets. The mixture weight is tuned on validation data. The main comparisons isolate different interventions. The in-domain tests add retrieval to an already trained predictor, the Wiki-3B test compares different routes for incorporating a larger corpus, and the Books adaptation test changes the domain of the datastore while holding the Wikipedia-trained predictor fixed.
Retrieval from the original training set
The first Wikitext-103 comparison holds the training corpus constant. The base Transformer has already been trained on the standard training split. The kNN-LM version encodes that same split and can look up its examples while assigning probabilities to the test text. The base obtains a test perplexity of 18.65, and the version with training-set retrieval obtains 16.12. The Wikitext-103 comparison reports the median of three random seeds. Other reported comparisons in the paper include systems trained on the standard split that build on the same underlying architecture. The authors also note that earlier work had obtained improvements with additional text, including dynamic use of test data or training on web text. The main retrieval comparison shows what can be gained with the original training corpus.
Wikitext-103 test perplexity with training-set retrieval and caching
Retrieving from the training set improves the base prediction, and adding a continuous cache gives the lowest perplexity.
The numbers
| System or setting | perplexity |
|---|---|
| Base Transformer | 18.65 |
| Transformer with training-set retrieval | 16.12 |
| Transformer with training-set retrieval and continuous cache (this paper) | 15.79 |
The continuous cache in the combined result retrieves from earlier positions in the test document. This evidence is available as the text is read, so the cache can capture occurrences specific to that document. Its addition brings test perplexity to 15.79, which the paper reports as an improvement of 2.86 points over the base Transformer. The authors describe the cache’s gains as smaller than in the earlier work with recurrent networks. They suggest that the Transformer’s self-attention may already provide part of the ability to reuse recent text. The improvement from combining the two retrieval sources shows that the training-set datastore still leaves some useful evidence in the document itself.
Books provides a second test of retrieval from the original training domain. The authors first train on Books, then use the same training collection as the source of neighbors. On the Books test set, the ordinary predictor scores 11.89 perplexity and the retrieval-augmented version scores 10.89. The experiment addresses the possibility that Wikipedia’s structure or factual content is especially favorable for nearest neighbor lookup. The improvement on Books establishes that a benefit is also possible for this different corpus. Because Books uses sub-word units and different context and distance settings, the experiment supports a comparison of the direction of the effect across domains. The numerical perplexities themselves belong to their respective benchmarks.
The controlled feature of both comparisons is that the text supplying the memory already participated in training. There is no extra text to account for the difference in performance. What changes is how the prediction process can get to a specific continuation. The base output reflects the learned parameters. The datastore connects an individual stored context with what followed it. The lower held-out perplexity shows that adding this route helps on average, including in a model with a strong ordinary prediction mechanism.
Using a larger corpus through retrieval
The Wiki-3B experiment changes how much text is available, and where it is used. The authors train a predictor on Wiki-100M and use that predictor to encode a datastore from Wiki-3B. They compare it with an ordinary predictor trained on Wiki-100M and an ordinary predictor trained on Wiki-3B. The paper describes 286K training steps for the earlier setup on a corpus comparable in size to Wiki-100M. For the larger training run, the authors tune the number of updates on validation data and use 572K steps, which gives the stronger baseline in their comparison.
Held-out Wiki-3B perplexity with larger-corpus training or retrieval
The Wiki-100M Transformer with retrieval from Wiki-3B scores below the Transformer trained on Wiki-3B alone.
The numbers
| System or setting | perplexity |
|---|---|
| Transformer trained on Wiki-100M | 19.59 |
| Transformer trained on Wiki-3B | 15.17 |
| Wiki-100M Transformer with Wiki-3B retrieval (this paper) | 13.73 |
The larger training run improves held-out Wiki-3B perplexity from 19.59 to 15.17 relative to the smaller-data predictor. That comparison establishes that the larger corpus is beneficial through ordinary training in this setup. The predictor trained on Wiki-100M reaches 13.73 when it can search the large datastore. Its representation, learned on the smaller corpus, is therefore useful for finding continuations in the much larger collection. The result compares two complete systems that use the larger corpus in different places, and the lower score belongs to the one that retains it as searchable memory.
The authors also sample smaller datastores from Wiki-3B while keeping the Wiki-100M predictor fixed. Reported perplexity improves throughout the tested range as the datastore grows. A datastore with 1.6B entries already lets the smaller-trained system surpass the ordinary predictor trained on the full larger corpus. The measured curve continues to improve at about 3B entries. The validation-selected mixture also puts more weight on retrieval as the datastore grows. Together, those observations show that, for this encoder and this corpus, increasing the number of available examples improves both the final score and the measured usefulness of the retrieval distribution within the mixture.
Changing domains through the datastore
The domain adaptation experiment asks whether a memory built from Books can help a predictor trained on Wikipedia score Books text. The comparison includes the ordinary Wikipedia-trained system, that same system with retrieval from the Books training collection, and an ordinary system trained directly on Books. These comparisons separate what a change to the available examples accomplishes from what full in-domain parameter training accomplishes.
Held-out Books perplexity with Wikipedia training and Books retrieval
A Books datastore improves predictions from the Wikipedia-trained Transformer, while direct training on Books gives the lowest score in this comparison.
The numbers
| System or setting | perplexity |
|---|---|
| Transformer trained on Wiki-3B | 34.84 |
| Wiki-3B Transformer with Books retrieval (this paper) | 20.47 |
| Transformer trained on Books | 11.89 |
The Wikipedia-trained Transformer starts at 34.84 perplexity on held-out Books text. Adding the Books datastore brings it to 20.47. The comparison with a predictor trained directly on Books, at 11.89, shows the scale of the remaining difference between these options. The adaptation result establishes that an encoder trained on Wikipedia can retrieve useful examples in Books. The target-domain text is still essential to the intervention, because it supplies the contexts and continuations that the system searches. The flexibility is that the same set of trained parameters can use another domain’s examples by building a datastore for that domain.
The cost of making examples searchable
The paper measures some of the extra work separately from perplexity. Generating keys and values entails one forward pass over the storage text. The authors describe that pass as costing a fraction of what it takes to train for an epoch over the same examples. For the Wikitext-103 collection, building the index after saving the keys takes roughly two hours on one CPU for 103M entries. The Wikitext-103 validation run takes roughly 25 minutes when retrieving 1024 keys per query. These timings concern different phases. The first is an up-front construction cost for a collection, and the second includes the cost of accessing the index during evaluation.
The authors describe construction work as growing linearly with the number of entries and as parallelizable without GPU-based training. The large-corpus comparison shows that the datastore offers a different placement of compute: encode the larger collection and pay for lookup at evaluation time, while using the smaller collection for the training run. The paper’s timing measurements give an implementation-scale example of that arrangement. The perplexity comparisons measure the predictive benefit directly.
What the ablations show
Where to take the context representation
The authors compare several points in the final Transformer layer from which they can extract the vector used for both keys and queries. Each version searches the same kind of training-set datastore with 1024 neighbors on Wikitext-103 validation data. The interpolation weight is tuned separately for each representation. This lets each vector type be evaluated with a mixture that suits the quality of the evidence it provides, since a single mixture weight could favor a particular representation independently of its best attainable score.
All of the tested states yield an improvement, with the best validation result coming from the input to the final feedforward network. Vectors taken immediately after layer normalization tend to work better. Repeating the comparison in the preceding Transformer layer gives similar trends with slightly worse results. This is evidence that the location and scaling of an internal state matter when distance is used as the decision rule. States within a single predictor can support useful context comparisons to different degrees.
The authors suggest that the attention stage may do more of the work of assembling a representation of the input, while the later feedforward computation may be more closely involved in prediction. The experiment tests states taken at different locations and measures their downstream retrieval value. It supports the practical choice of a key function. Assigning a particular linguistic role to either component remains an interpretation of the pattern, since the components were learned together to serve the language modeling objective.
How much evidence to retrieve and trust
Increasing the number of returned neighbors improves Wikitext-103 validation perplexity throughout the range tested. The authors report that even k = 8 is enough to achieve what they describe as a new state-of-the-art result in that comparison. The main experiments use k = 1024. A broad set of neighbors can contribute additional occurrences of a relevant token and capture other plausible continuations. The distance weighting limits the influence of a weaker match relative to that of a closer one. The observed trend is about adding neighbors under this weighting rule and for this particular index and dataset.
The best interpolation weight varies with the task. On Wikitext-103 validation data the optimum is λ = 0.25. In the domain adaptation validation comparison the optimum is λ = 0.65. In the first case the ordinary predictor is already trained on the same domain as the evaluation text, and retrieval supplements it. In the second case the memory contains target-domain text and the ordinary predictor was trained on Wikipedia. The higher tuned weight illustrates how a collection of in-domain examples can provide a larger share of useful predictive evidence when the base predictor comes from a different domain.
The datastore size experiment offers a related comparison. As the authors give the fixed Wiki-100M encoder access to larger samples of Wiki-3B, validation tuning favors a larger contribution from the neighbor distribution. The effect concerns a change to the evidence available to the same representation function. The index can draw from more stored contexts, and the mixture can use more of the resulting probability mass. The results show the benefit of fitting the mixture for a chosen datastore and task.
How distances affect the result
The paper examines the scores used after the neighbors have been found. FAISS can return distances computed from quantized keys. In a Wikitext-103 comparison, using those distances gives a perplexity of 16.5. Recomputing squared Euclidean distances with full-precision keys gives 16.06 in the same reported comparison. The paper identifies the corpus for these tuning figures, while the precision comparison itself gives no separate split designation. The main test-set comparison is reported with its own values.
This change affects the weights assigned to returned entries. A more faithful estimate of separation can increase the influence of a particularly relevant context. Squaring the distance also changes the shape of the weighting function that converts distance to probability. Because both change together in the reported experiment, the observed benefit is evidence for the combined scoring choice. The paper also reports that Euclidean distance worked better in preliminary retrieval experiments than an inner product score. The implementations for the larger corpora retain the faster quantized distance calculation, so this precision result primarily explains the Wikitext-103 choice.
Learned context similarity and short word sequences
The paper compares the neural retrieval mechanism with a simpler way of accessing recurring patterns. An n-gram is a sequence of adjacent tokens. An n-gram predictor can use counts of short sequences to estimate which token tends to follow a short suffix of the current context. This makes it a plausible alternative for rare names or recurring phrases whose local wording is distinctive. The authors interpolate an n-gram predictor with the Transformer and measure the result on Wikitext-103 validation data. They report an improvement of 0.2 perplexity points from this kind of interpolation. The improvement from nearest neighbors in the learned context space is larger in their validation comparisons.
The qualitative analysis helps explain the distinction. In one example, several stored contexts share the same short phrase ending, a trigram. One of those contexts is especially relevant to the actual continuation. The learned search puts nearly all of its weight on that example. Local token overlap can make each of the examples a plausible candidate, while the larger context represented by the neural vector helps identify the most pertinent occurrence. The result concerns the combination of a learned comparison and example-level memory. The n-gram experiment gives a baseline for how much plain local repetition contributes in the setup.
The authors inspect several other cases in which the nearest neighbor distribution gives the observed target higher probability than the ordinary distribution. One illustrates the fact that Georges Bizet wrote Carmen. Giving that association an addressable place in memory allows a relevant query to reinforce the title. In another example, the corpus contains many occurrences of a date pattern, and the most strongly weighted context is the one relevant to the date being predicted. A further example shows a flatter distribution, with several plausible continuations and the highest probability assigned to the one that actually occurs. These cases show both concentrated and dispersed retrieval evidence. Which contexts are available and how closely they match the current context determine the outcome.
The examples were chosen because retrieval gave the observed continuation substantially better support. They describe ways the system succeeds, including a close match to a rare training example and the ability to prefer one context among several superficially similar alternatives. Their selection leaves open how frequently each kind of success accounts for the overall score. The corpus-level comparison with the n-gram predictor provides the broader evidence that matching short sequences alone captures relatively little of the measured gain.
Memorization in parameters and in the datastore
The authors also ask whether the ordinary Transformer can be induced to memorize the training set in its parameters and then provide useful extra evidence in a mixture. They train a version without dropout. Dropout is a regularization technique that makes part of the network’s activity unavailable during training, encouraging a predictor that remains effective under that variation. In the experiment without dropout, the training loss reaches 0. The authors take that as evidence that the network has sufficient capacity to reproduce the training continuations.
The resulting predictor’s best Wikitext-103 validation perplexity is 28.59. The ordinary Transformer trained with dropout reaches 17.96 on validation in spite of carrying a higher training loss. The gap shows that getting the training continuations right through parameter fitting is compatible with much weaker performance on new contexts. The important question for the proposed mechanism is whether the memorizing predictor still supplies something useful when combined with the regularized one.
Interpolating the original predictor with the memorizing version improves validation perplexity by 0.1. The authors report a gain of 1.9 for kNN-LM in the corresponding validation comparison. This supports treating the datastore as a distinct way to preserve the training examples. In kNN-LM, the encoder derives from the regularized training run, and the memory stores individual continuations directly. A new context gains access to them through proximity in that encoder’s representation space. In the dropout experiment, the additional predictor must express its memory through shared parameters and its own vocabulary distribution.
The authors conjecture from this comparison that forcing the network to memorize the training set can yield representations that generalize less well. The experiment directly measures training fit, validation perplexity, and the effect of interpolating the outputs. A direct comparison of retrieval using the two encoders would address the narrower question of how much their vector spaces differ as measures of context similarity. The result that is established here is that a parameter-memorizing predictor contributes little to the mixture, while a datastore accessed through the regularized predictor contributes substantially more in this setup.
Limitations
Limits and open questions the authors state
The authors identify the datastore’s size as a practical problem and propose reducing it as future work. Keeping an entry for every target means that larger collections bring more keys and values to construct and store. Quantization reduces the space used by indexed vectors. The Wikitext-103 configuration that recomputes distances also needs access to full-precision keys for the returned entries. Every evaluated prediction uses both the ordinary forward computation for its context and a query to the index. The contribution of retrieval consequently comes with construction, storage, and inference costs even though the underlying predictor needs no retraining.
The paper also proposes explicitly training a similarity function. In the experiments, f comes from a network trained for next-token prediction. The authors then choose a useful internal state and distance calculation empirically. This shows that a representation learned for prediction can also support effective retrieval. How far retrieval could improve with a training objective designed for the search is left open. The paper’s successful use of existing internal vectors establishes a starting point for that question.
At the upper end of the datastore-size experiment, the authors observe continued improvement and suggest that still larger memories could help. The evidence extends to the sizes and samples examined. Further increases would depend on the quality and distribution of the additional text, the suitability of the learned representation, and the search implementation. Likewise, the improvement observed when retrieving more neighbors comes from the tested range of neighbor counts. The eventual effect of even larger searches remains an empirical question.
Limits of the experimental evidence
The corpora are English-language Wikipedia and Books. That range supports the finding that retrieval helps in both encyclopedia text and books and provides a concrete example of transferring an encoder between domains. The domain adaptation experiment draws its evidence from one transfer direction and uses a collection of target-domain text. Its outcome establishes that this switch can be accomplished by changing the datastore. The generality of the effect across other languages, kinds of text, and more divergent domains remains open, as does the behavior when there is little suitable target-domain material to index.
The larger-corpus comparison is also bounded by the training setup. The smaller corpus is sampled from the larger one. Both are drawn from the same kind of text, which helps the experiment isolate how a larger body of Wikipedia data can be used. The full training run uses a specific architecture, update schedule, and validation tuning procedure. The result supports the claim that retrieval from a larger corpus can outperform training on that corpus under these conditions. It leaves open the comparison with other architectures, training budgets, or strategies that combine larger-corpus training with larger-corpus retrieval. A cost comparison across those alternatives would also need matched measurements of training, indexing, storage, and prediction.
Perplexity measures how much probability the system assigns to observed continuations across held-out text. It can support a claim about factual cases when accompanied by an inspection of particular examples, such as the one about Bizet. A systematic estimate of factual accuracy, factual coverage, or reliability over generated passages would require an evaluation designed around those outcomes. The paper’s manual examples establish that the procedure can give useful support to particular facts and dates. Their selection from cases that favor retrieval supplies little information about factual contexts in which the returned examples are misleading or in which useful evidence is absent.
The interpretation of generalization also depends on the type of match. A held-out context may be extremely close to a stored one, and the paper explicitly includes near duplicates among the cases where the method helps. Predicting a held-out continuation using that kind of match is a real capability of an example-based system. The aggregate results do not quantify how much of the gain comes from those cases and how much comes from applying the same association across significantly different wording. The short-sequence baseline and the inspected examples support the claim that learned similarity can do more than local suffix matching. They leave the relative contribution of different types of similarity undetermined.
Finally, the paper frames the distinction between recognizing similar contexts and predicting their next word as a hypothesis supported by the experiments. Both the learned vector and the ordinary vocabulary distribution come from a network trained on the same prediction objective. The datastore gives the similarity-based method access to explicit examples that the ordinary output mechanism can use only through the network’s parameters. The results establish that a learned representation can support a stronger predictor when paired with those examples. Establishing a general ranking of the intrinsic difficulty of the two tasks would require a way to compare them independently of that difference in available memory.
What came after
Retrieval inside the language modeling system
REALM takes retrieval into language model pretraining. This shifts the point at which outside examples become available. In kNN-LM, training produces the encoder and a separate indexing pass gives that encoder a memory at inference. REALM addresses the related question of using retrieval as part of the stage in which the language model learns. The connection is the coupling between a learned text representation and searchable information. The difference in placement makes pretraining itself part of the design space.
Improving Language Models by Retrieving from Trillions of Tokens pursues the scale question raised by the Wiki-3B comparison. The earlier paper showed a benefit from enlarging the collection accessible through retrieval while keeping the smaller-trained predictor fixed. The later work takes the searchable corpus as a major axis for increasing the information a system can reach. The shared research question is how much additional text can improve predictions through access to external examples.
In-Context Retrieval-Augmented Language Models explores retrieval through the text context supplied to the generator. In kNN-LM, a retrieved continuation is already a vocabulary item, so its weight can be added directly to a distribution over next tokens. In-context retrieval gives the generator text that can influence its own prediction. This changes the point of integration. One approach combines probabilities at the output, while the other asks the generator to use retrieved material in the input it reads.
REPLUG addresses retrieval for black-box language models. Its setting makes the form of access to the predictor central. The earlier kNN-LM setup depends on access to a specific hidden state for constructing keys and queries. A black-box setting calls for retrieval augmentation that can work through the available interface. Both works ask how an existing predictor can benefit from information supplied through a retrieval mechanism, with different assumptions about access to its internal computation.
Retrieval for knowledge and generation
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks applies retrieval-augmented generation to tasks that require access to knowledge. The kNN-LM paper demonstrates the value of retrieved examples at the level of an individual continuation. This later work makes generation for knowledge-intensive tasks the setting for using retrieved information. That change gives the system a broader job: retrieved material has to help produce a task response, whose usefulness can depend on more than the probability of a single observed token.
Retrieval Augmentation Reduces Hallucination in Conversation examines the relation between retrieval and unsupported content in dialogue. Its question connects to the factual examples in kNN-LM, where the collection can give a known association a direct influence on the output. The conversation work takes unsupported statements as an outcome to study in its own right. This is a distinct use of external evidence from the earlier paper’s measurement of how much probability a system reserves for the true continuation.
Active Retrieval Augmented Generation addresses retrieval as a decision made during generation. In the kNN-LM setup, a token prediction calls the index and then applies a mixture weight chosen in advance for the setting. Active retrieval makes the timing of information access part of the problem. That direction matters when a generation can encounter new information needs as its text develops. It extends the question from what can be recovered given a query to when another query should be made.
Enabling Large Language Models to Generate Text with Citations investigates generation in which the reader can see citations for the resulting text. The kNN-LM calculation uses the source contexts to determine how strongly to weight particular tokens. A citation-oriented approach gives provenance a role in the generated result itself. This shifts attention from whether a retrieval changes the prediction to how the system can expose the evidence associated with the text it produces.
When to rely on memory
When Not to Trust Language Models explicitly studies the effectiveness of parametric and non-parametric memories. Parametric memory is information accessible through learned weights. A searchable collection is a form of non-parametric memory because specific facts or examples can remain available as individual records. KNN-LM combines these sources and demonstrates that both can contribute to a single next-token distribution. The later work makes the circumstances under which each source deserves trust an explicit subject of investigation.
Memory-Based Model Editing at Scale puts external memory to work in model editing. Where kNN-LM builds a memory from observed continuations to improve held-out prediction, the editing work makes changing particular behavior the purpose of memory. The relationship lies in preserving information outside the original parameter fit so that it can be called upon when relevant. It brings the question of accurate access to a different setting, where remembering an intended change is useful only if related inputs can trigger it appropriately.
Learning To Retrieve Prompts for In-Context Learning uses retrieval to select examples for a prompt. Selection plays a role similar to finding relevant contexts in kNN-LM: an example can be present in a collection and still be useful only when the system can locate it for a new input. Here the selected items serve as demonstrations to the predictor, which uses them in context. In kNN-LM the selected items contribute their continuation probabilities through a distance-weighted vote. The move from voting over recorded tokens to supplying demonstrations makes both retrieval quality and the predictor’s use of the selected examples part of the outcome.
Cite
Cite as Urvashi Khandelwal, Omer Levy, Dan Jurafsky, Luke Zettlemoyer and Mike Lewis. 2019. Generalization through Memorization: Nearest Neighbor Language Models. arXiv:1911.00172.
@misc{khandelwal2019generalization,
title = {{Generalization through Memorization: Nearest Neighbor Language Models}},
author = {Urvashi Khandelwal, Omer Levy, Dan Jurafsky, Luke Zettlemoyer and Mike Lewis},
year = {2019},
doi = {10.48550/arxiv.1911.00172},
eprint = {1911.00172},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.1911.00172}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/khandelwal-2019-generalization-through-memorization-nearest-neighbor/
References
- Alexei Baevski and Michael Auli. Adaptive input representations for neural language modeling. In ICLR, 2019. our card
- Anton Bakhtin, Arthur Szlam, Marc'Aurelio Ranzato, and Edouard Grave. Lightweight adaptive mixture of neural and n-gram language models. arXiv preprint arXiv:1804.07705, 2018. OpenAlex ↗ · Scholar ↗
- Yoshua Bengio, Réjean Ducharme, Pascal Vincent, and Christian Jauvin. A neural probabilistic language model. Journal of machine learning research, 30 (Feb):0 1137–1155, 2003. our card
- Antal van den Bosch, Bertjan Busser, Sander Canisius, and Walter Daelemans. An efficient memory-based morphosyntactic tagger and parser for dutch. LOT Occasional Series, 7:0 191–206, 2007. OpenAlex ↗ · Scholar ↗
- Walter Daelemans, Jakub Zavrel, Peter Berck, and Steven Gillis. Mbt: A memory-based part of speech tagger-generator. In WVLC, 1996. our card
- Zihang Dai, Zhilin Yang, Yiming Yang, William W Cohen, Jaime Carbonell, Quoc V Le, and Ruslan Salakhutdinov. Transformer-xl: Attentive language models beyond a fixed-length context. In ACL, 2019. OpenAlex ↗ · Scholar ↗
- Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pre-training of deep bidirectional transformers for language understanding. In NAACL, 2019. our card
- Edouard Grave, Moustapha M Cisse, and Armand Joulin. Unbounded cache model for online language modeling with open vocabulary. In NIPS, pp. 6042–6052, 2017a. OpenAlex ↗ · Scholar ↗
- Edouard Grave, Armand Joulin, Moustapha Cissé, Hervé Jégou, et al. Efficient softmax approximation for gpus. In Proceedings of the 34th International Conference on Machine Learning-Volume 70, pp. 1302–1310. JMLR. org, 2017b. our card
- Edouard Grave, Armand Joulin, and Nicolas Usunier. Improving neural language models with a continuous cache. In ICLR, 2017c. our card
- Jiatao Gu, Yong Wang, Kyunghyun Cho, and Victor OK Li. Search engine guided neural machine translation. In Thirty-Second AAAI Conference on Artificial Intelligence, 2018. OpenAlex ↗ · Scholar ↗
- Kelvin Guu, Tatsunori B Hashimoto, Yonatan Oren, and Percy Liang. Generating sentences by editing prototypes. Transactions of the Association for Computational Linguistics, 6:0 437–450, 2018. our card
- Jeff Johnson, Matthijs Douze, and Hervé Jégou. Billion-scale similarity search with gpus. arXiv preprint arXiv:1702.08734, 2017. our card
- Łukasz Kaiser, Ofir Nachum, Aurko Roy, and Samy Bengio. Learning to remember rare events. In ICLR, 2017. OpenAlex ↗ · Scholar ↗
- Ben Krause, Emmanuel Kahembwe, Iain Murray, and Steve Renals. Dynamic evaluation of transformer language models. arXiv preprint arXiv:1904.08378, 2019. OpenAlex ↗ · Scholar ↗
- Yinhan Liu, Myle Ott, Naman Goyal, Jingfei Du, Mandar Joshi, Danqi Chen, Omer Levy, Mike Lewis, Luke Zettlemoyer, and Veselin Stoyanov. Roberta: A robustly optimized bert pretraining approach. arXiv preprint arXiv:1907.11692, 2019. our card
- Hongyin Luo, Lan Jiang, Yonatan Belinkov, and James Glass. Improving neural language models by segmenting, attending, and predicting the future. In ACL, 2019. OpenAlex ↗ · Scholar ↗
- Stephen Merity, Caiming Xiong, James Bradbury, and Richard Socher. Pointer sentinel mixture models. ICLR, 2017. our card
- Tomáš Mikolov, Martin Karafiát, Lukáš Burget, Jan Černockỳ, and Sanjeev Khudanpur. Recurrent neural network based language model. In Eleventh annual conference of the international speech communication association, 2010. OpenAlex ↗ · Scholar ↗
- A. Emin Orhan. A simple cache model for image recognition. In NeurIPS, 2018. OpenAlex ↗ · Scholar ↗
- Nicolas Papernot and Patrick McDaniel. Deep k-nearest neighbors: Towards confident, interpretable and robust deep learning. arXiv preprint arXiv:1803.04765, 2018. OpenAlex ↗ · Scholar ↗
- Ofir Press and Lior Wolf. Using the output embedding to improve language models. In ICLR, 2017. our card
- Alec Radford, Jeff Wu, Rewon Child, David Luan, Dario Amodei, and Ilya Sutskever. Language models are unsupervised multitask learners. URL https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf, 2019. OpenAlex ↗ · Scholar ↗
- Rico Sennrich, Barry Haddow, and Alexandra Birch. Neural machine translation of rare words with subword units. arXiv preprint arXiv:1508.07909, 2015. our card
- Mohammad Shoeybi, Mostofa Patwary, Raul Puri, Patrick LeGresley, Jared Casper, and Bryan Catanzaro. Megatron-lm: Training multi-billion parameter language models using gpu model parallelism. arXiv preprint arXiv:1909.08053, 2019. OpenAlex ↗ · Scholar ↗
- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is all you need. In Advances in neural information processing systems, pp. 5998–6008, 2017. our card
- Jason Weston, Emily Dinan, and Alexander H Miller. Retrieve and refine: Improved sequence generation models for dialogue. arXiv preprint arXiv:1808.04776, 2018. our card
- Zhilin Yang, Zihang Dai, Yiming Yang, Jaime Carbonell, Ruslan Salakhutdinov, and Quoc V Le. Xlnet: Generalized autoregressive pretraining for language understanding. arXiv preprint arXiv:1906.08237, 2019. our card
- Rowan Zellers, Ari Holtzman, Hannah Rashkin, Ali Farhadi, Franziska Roesner, and Yejin Choi. Defending against neural fake news. In NeurIPS, 2019. our card
- Jake Zhao and Kyunghyun Cho. Retrieval-augmented convolutional neural networks for improved robustness against adversarial examples. arXiv preprint arXiv:1802.09502, 2018. OpenAlex ↗ · Scholar ↗
- Yukun Zhu, Ryan Kiros, Rich Zemel, Ruslan Salakhutdinov, Raquel Urtasun, Antonio Torralba, and Sanja Fidler. Aligning books and movies: Towards story-like visual explanations by watching movies and reading books. In Proceedings of the IEEE international conference on computer vision, pp. 19–27, 2015. our card