Generalization through Memorization: Nearest Neighbor Language Models

Urvashi Khandelwal, Omer Levy, Dan Jurafsky, Luke Zettlemoyer, Mike Lewis

Introduction

Neural language models (LMs) typically solve two subproblems: (1) mapping sentence prefixes to fixed-sized representations, and (2) using these representations to predict the next word in the text (Bengio et al., 2003; Mikolov et al., 2010). We present a new language modeling approach that is based on the hypothesis that the representation learning problem may be easier than the prediction problem. For example, any English speaker knows that Dickens is the author of and Dickens wrote will have essentially the same distribution over the next word, even if they do not know what that distribution is. We provide strong evidence that existing language models, similarly, are much better at the first problem, by using their prefix embeddings in a simple nearest neighbor scheme that significantly improves overall performance.

We introduce kkNN-LM, an approach that extends a pre-trained LM by linearly interpolating its next word distribution with a kk-nearest neighbors (kkNN) model. The nearest neighbors are computed according to distance in the pre-trained embedding space and can be drawn from any text collection, including the original LM training data. This approach allows rare patterns to be memorized explicitly, rather than implicitly in model parameters. It also improves performance when the same training data is used for learning the prefix representations and the kkNN model, strongly suggesting that the prediction problem is more challenging than previously appreciated.

To better measure these effects, we conduct an extensive empirical evaluation. Applying our kkNN augmentation to a strong Wikitext-103 LM using only the original dataset achieves a new state-of-the-art perplexity of 15.79 – a 2.86 point improvement over the base model (Baevski & Auli, 2019) – with no additional training. We also show that the approach has implications for efficiently scaling up to larger training sets and allows for effective domain adaptation, by simply varying the nearest neighbor datastore. Training a model on 100-million tokens and using kkNN search over a 3-billion token dataset can outperform training the same model on all 3-billion tokens, opening a new path for efficiently using large datasets in language models. Similarly, adding out-of-domain data to the datastore makes a single LM useful across multiple domains, again without further training. Qualitatively, we find the model is particularly helpful for long-tail patterns, such as factual knowledge, which might be easier to access via explicit memory.

Nearest Neighbor Language Modeling

Language models (LMs) assign probabilities to sequences. Given a context sequence of tokens ct=(w1,…wt−1)c_{t}=(w_{1},\ldots w_{t-1}), autoregressive LMs estimate p(wt∣ct)p(w_{t}|c_{t}), the distribution over the target token wtw_{t}.

The kkNN-LM involves augmenting such a pre-trained LM with a nearest neighbors retrieval mechanism, without any additional training (the representations learned by the LM remain unchanged). This can be done with a single forward pass over a text collection (potentially including the original LM training set), where the resulting context-target pairs are stored in a key-value datastore that is queried during inference, as illustrated in Figure 1.

Let f(⋅)f(\cdot) be the function that maps a context cc to a fixed-length vector representation computed by the pre-trained LM. For instance, in a Transformer LM, f(c)f(c) could map cc to an intermediate representation that is output by an arbitrary self-attention layer. Then, given the ii-th training example (ci,wi)∈D(c_{i},w_{i})\in\mathcal{D}, we define the key-value pair (ki,vi)(k_{i},v_{i}), where the key kik_{i} is the vector representation of the context f(ci)f(c_{i}) and the value viv_{i} is the target word wiw_{i}. The datastore (K,V)\left(\mathcal{K},\mathcal{V}\right) is thus the set of all key-value pairs constructed from all the training examples in D\mathcal{D}:

At test time, given the input context xx the model generates the output distribution over next words pLM(y∣x)p_{\text{LM}}(y|x) and the context representation f(x)f(x). The model queries the datastore with f(x)f(x) to retrieve its kk-nearest neighbors N\mathcal{N} according to a distance function d(⋅,⋅)d(\cdot,\cdot) (squared L2L^{2} distance in our experiments, making the similarity function an RBF kernel).Then, it computes a distribution over neighbors based on a softmax of their negative distances, while aggregating probability mass for each vocabulary item across all its occurrences in the retrieved targets (items that do not appear in the retrieved targets have zero probability):

Finally, we follow Grave et al. (2017a) and interpolate the nearest neighbor distribution pkNNp_{\text{kNN}} with the model distribution pLMp_{\text{LM}} using a tuned parameter λ\lambda to produce the final kkNN-LM distribution:

The datastore contains an entry for each target in the training set, which for LMs can be up to billions of examples. To search over this large datastore, we use FAISS (Johnson et al., 2017), an open source library for fast nearest neighbor retrieval in high dimensional spaces. FAISS speeds up search by clustering the keys and looking up neighbors based on the cluster centroids, while reducing memory usage by storing compressed versions of the vectors. We found in preliminary experiments that using L2L^{2} distance for FAISS retrieval results in better performance for kkNN-LM, compared to inner product distance.

Prior work (Grave et al., 2017c; Merity et al., 2017) used a similar approach to compute similarity to the previous hidden states of test documents, making it easier to copy rare vocabulary items from the recent past. Such techniques have been less popular since the development of Transformers (Vaswani et al., 2017), which can learn to copy recent words using self-attention; in Section 4.1, we observe relatively small gains from caching recent items in the same test document à la Grave et al. (2017c). Most relatedly, Grave et al. (2017a) describe an online language model using nearest neighbor search over all previous hidden states, to improve domain adaptation. In our work, we only save training data, with the goal of explicitly memorizing training examples to better generalize to similar cases at test time.

Experimental Setup

Experiments in this paper use the following English corpora:

Wikitext-103 is a standard benchmark by Merity et al. (2017) for autoregressive language modeling with a 250K word-level vocabulary. It consists of 103M tokens of Wikipedia in the training set and 250K tokens in each of the development and test sets.

Books is the Toronto Books Corpus (Zhu et al., 2015), containing 0.7B. Complete books are held out for validation/test.

Wiki-3B is English Wikipedia, containing about 2.87B tokens. Whole articles are held out for validation/test.

Wiki-100M is a random 100M token subset of Wiki-3B, consisting of complete articles.

Except for Wikitext-103, text is tokenized using the byte-pair encoding (Sennrich et al., 2015) with the 29K subword vocabulary from BERT (Devlin et al., 2019).

kkNN-LM is compatible with any model that produces fixed size context representations. We use decoder-only Transformers (Vaswani et al., 2017) for language modeling, which are the current state of the art. Since the kkNN-LM makes no changes to the underlying LM, we take the exact architecture and optimization described by Baevski & Auli (2019) and use it to create a kkNN-LM for inference. This model consists of 16 layers, each with 16 self-attention heads, 1024 dimensional hidden states, and 4096 dimensional feedforward layers, amounting to 247M trainable parameters. It processes 3072 tokens of context per example for Wikitext-103 and 1024 tokens for the rest of the corpora. Following Baevski & Auli (2019), we use adaptive inputs and an adaptive softmax (Grave et al., 2017b) with tied weights (Press & Wolf, 2017) for the Wikitext-103 experiments. On other datasets we do not use adaptive inputs or an adaptive softmax.

LMs are trained to minimize the negative log-likelihood of the training corpus, and evaluated by perplexity (exponentiated negative log-likelihood) on held out data. Following Baevski & Auli (2019), 512 tokens are scored per test example, but up to 2560 tokens of extra prior context is provided for Wikitext-103 and up to 512 tokens of extra prior context is provided for the rest of the corpora.

The keys used for kkNN-LM are the 1024-dimensional representations fed to the feedforward network in the final layer of the Transformer LM (after self-attention and layernorm; see Section 5 for further explanation). We perform a single forward pass over the training set with the trained model, in order to save the keys and values. During this forward pass, each target token is provided a minimum of 1536 tokens of prior context for Wikitext-103 and a minimum of 512 tokens for the rest of the corpora. A FAISS index is then created using 1M randomly sampled keys to learn 4096 cluster centroids. For efficiency, keys are quantized to 64-bytes. During inference, we retrieve k=1024k=1024 neighbors, and the index looks up 32 cluster centroids while searching for the nearest neighbors. For Wikitext-103 experiments, we compute squared L2L^{2} distances with full precision keys, but for the other datasets we use the FAISS L2L^{2} distances (not squared) between quantized keys directly, for faster evaluation. We tune the interpolation parameter λ\lambda on the validation set.Code is available at: https://github.com/urvashik/knnlm

Although the kkNN-LM requires no training given an existing LM, it does add some other computational overheads. Storing the keys and values requires a single forward pass over the training set, which amounts to a fraction of the cost of training for one epoch on the same examples. Once the keys are saved, for Wikitext-103 building the cache with 103M entries takes roughly two hours on a single CPU. Finally, running on the validation set took approximately 25 minutes when retrieving 1024 keys. While the cost of building a large cache grows linearly in the number of entries, it is trivial to parallelize and requires no GPU-based training.

Experiments

We first experiment with creating a datastore from the same data used to train the LM. Table 1 shows that kkNN-LM improves perplexity on Wikitext-103 from 18.65 (Baevski & Auli, 2019) to a new state-of-the-art of 16.12. We also provide reported perplexities from two other recent models that also build upon Baevski and Auli’s, suggesting that further improvements may be possible by augmenting the kkNN-LM with these techniques. We compare with models trained only on the standard training set, but recent work has shown performance can be improved by training on additional data, from either the test set (Krause et al., 2019) or large amounts of web text (Shoeybi et al., 2019).

We also experiment with a continuous cache model, a related but orthogonal technique from Grave et al. (2017c), in which the model saves and retrieves neighbors from earlier in the test document, rather than the training set. Gains from interpolating with the continuous cache are smaller than reported in the original setting that used LSTMs, perhaps because self-attentive language models can learn to perform such queries. Improvements from the continous cache are additive with the kkNN-LM, pushing our state-of-the-art result to 15.79, a gain of 2.86 over the base model.

Finally, we repeat the experiment using text from a different domain, Books, to control for the possibility that encyclopedic Wikipedia text is somehow uniquely good for caching. Table 2 shows an improvement in test set perplexity from 11.89 to 10.89, suggesting that this is not the case.

2 More Data without Training

Section 4.1 has shown that retrieving neighbors from the training data can significantly improve language modeling performance. This raises the question: can retrieving nearest neighbors from data be a substitute for training on it? To test this, we train a LM on Wiki-100M and use it to build a datastore from Wiki-3B, a corpus 30 times larger than the training set. We then compare this kkNN-LM to a vanilla LM trained on the entire Wiki-3B corpus.The original LM (Baevski & Auli, 2019) was trained for 286K steps on a corpus of similar size to Wiki-100M. When scaling up to Wiki-3B, we tuned only the number of updates on the validation set and found that training for 572K steps (double) produces a slightly stronger baseline.

Table 3 shows that, as expected, the model trained on 3B tokens dramatically outperforms the model trained on 100M tokens, improving perplexity from 19.59 to 15.17. However, adding nearest neighbors retrieval over those 3B examples to the model trained on 100M tokens improves perplexity from 19.59 to 13.73; i.e. retrieving nearest neighbors from the corpus outperforms training on it. This result suggests that rather than training language models on ever larger datasets, we can use smaller datasets to learn representations and augment them with kkNN-LM over a large corpus.

To understand how the amount of data used for kkNN retrieval affects performance, we use the Wiki-100M model to create datastores using different amounts of randomly sampled data from Wiki-3B. Figure 2(a) shows that using only 1.6B examples for the datastore already surpasses the performance of the model trained on all of Wiki-3B. In addition, performance does not saturate at 3B examples in the datastore, suggesting that growing the datastore more could lead to further gains. Figure 2(b) shows the model relies more on the kkNN component as the size of the datastore increases.

3 Domain Adaptation

We also experiment with domain adaptation by creating a datastore on the target domain training set. Table 4 shows that an in-domain LM on Books has a relatively low perplexity (11.89), while a model trained on Wiki-3B performs poorly on the Books domain (34.84 perplexity). Adding kkNN search over Books to the Wiki-3B model reduces perplexity by 14 points (to 20.47), demonstrating that kkNN-LM allows a single model to be useful in multiple domains, by simply adding a datastore per domain.

Tuning Nearest Neighbor Search

While the kkNN-LM is conceptually straightforward, and requires no additional training, a number of hyperparameters are introduced for nearest neighbor search. We experiment with different choices here.

For similarity search, we extract a representation of context cc using an intermediate state of the LM f(c)f(c). Transformers compute a number of different intermediate states, and we compare several choices depicted in Figure 3, with results shown in Table 5. While all the instantiations of ff we tried are helpful, we achieved the largest improvement by using the input to the final layer’s feedforward network. We also observe that normalized representations (i.e. taken immediately after the layer norm) perform better. Repeating the experiment on the second-last transformer layer showed similar trends with slightly worse results (not shown), suggesting that the feedforward layer might be focusing more on the prediction problem, while the onus of representing the input falls more on the self-attention layer.

Each query returns the top-kk neighbors. Figure 5 shows that performance monotonically improves as more neighbors are returned, and suggests that even larger improvements may be possible with a higher value of kk. Nonetheless, even a small number of neighbors (k=8k=8) is enough to achieve a new state of the art.

We use a parameter λ\lambda to interpolate between the base model distribution and the distribution from kkNN search over the dataset. Figure 5 shows that λ=0.25\lambda=0.25 is optimal on Wikitext-103. However, λ=0.65\lambda=0.65 works best for domain adaptation results (Figure 5).

In FAISS, the nearest neighbor search computes L2L^{2} distances against quantized keys. We found results were improved from 16.5 perplexity on Wikitext-103 to 16.06 by computing squared L2L^{2} distances with full precision keys for Equation 2.

Analysis

To understand why kkNN-LM improves performance, we manually examine cases in which pkNNp_{\text{kNN}} was significantly better than pLMp_{\text{LM}}. Table 6 shows one such example, along with several others in Appendix A. The example shows an interesting case where the model matches the trigram impact on the in several retrieved neighbors, but puts almost all weight on the most relevant neighbor, thus adding more value than an nn-gram LM.

In general, we find that examples where kkNN-LM is most helpful typically contain rare patterns. Examples include factual knowledge, names, and near-duplicate sentences from the training set. In these cases, assigning train and test instances similar representations (via f(⋅)f(\cdot)) appears to be an easier problem than implicitly memorizing the next word in model parameters.

We observe that many long-tail phenomena manifest as rare nn-grams (e.g. names). Is it therefore possible to interpolate an nn-gram model with a Transformer LM, as an alternative to our kkNN approach? Figure 8 shows little improvement from using nn-gram LMs – 0.2 perplexity points (similarly to Bakhtin et al. (2018)). This result highlights the need to use the learned representation function f(⋅)f(\cdot) to measure similarity between more varied contexts.

If a neural representation function is crucial for kkNN-LM, could implicitly memorizing the training dataset in the neural network parameters replace the explicit memory in the datastore? To test this, we train a Transformer LM with no dropout. Figure 8 shows that this model eventually reaches zero training loss, indicating that it can make perfect predictions for all examples in the training set; the model has memorized the dataset. Naturally, the memorizing LM overfits, i.e. the training loss drops to 0 while the best validation perplexity is much higher at 28.59. For comparison, the vanilla Transformer LM (with dropout) has a much higher training loss (shown in Figure 8), but also generalizes better with a validation perplexity of 17.96. This result shows that the Transformer has sufficient capacity to memorize the training set.

We consider whether the memorizing LM can be an effective substitute for nearest neighbor search. Interpolating the memorizing LM with the original LM improves validation perplexity by just 0.1 – compared to 1.9 from kkNN-LM. This result suggests that although the Transformer is expressive enough to memorize all training examples, learning to do so does not result in context representations that generalize. In contrast, kkNN-LM memorizes training data while improving generalization.

From these experiments, we conjecture that kkNN-LM improves performance because (1) the Transformer LM is very good at learning a representation function for contexts with an implicit notion of similarity, and (2) while the Transformer has capacity to memorize all training examples, doing so causes its representation to generalize less effectively, but (3) the kkNN-LM allows the model to memorize the training data while retaining an effective similarity function.

Related Work

We discuss related uses of caches for language modeling in Section 2.

Similar kkNN models to ours have been proposed for computer vision tasks (Papernot & McDaniel, 2018; Orhan, 2018; Zhao & Cho, 2018), primarily motivated by improving interpretability and robustness to adversarial attacks. We hypothesize that our method may be particularly effective for language modeling, because plentiful unlabeled data allows datastores of billions of tokens, and language modeling often requires world knowledge to be learnt from few examples.

Nearest neighbor models have been applied to a number of NLP problems in the past, such as part of speech tagging (Daelemans et al., 1996) and morphological analysis (Bosch et al., 2007), but the use of learned representations makes the similarity function much more effective in the case of neural models. More recently, Kaiser et al. (2017) have used a similarly differentiable memory that is learned and updated during training, and is applied to one-shot learning tasks.

Several models have also improved language generation by using training examples directly at test time. Guu et al. (2018) propose a model that samples training sentences at random and edits them with a sequence-to-sequence model, but does not use a retrieval mechanism such as kkNN. Gu et al. (2018) introduce a translation model that attends over retrieved training set examples. Weston et al. (2018) improve a dialogue response generation model by refining similar instances from the training set. kkNN-LM differs from these approaches by working at the level of individual tokens instead of whole training sentences, as well as not incorporating the retrieval mechanism into the training pipeline.

A general trend in machine learning, and in language modeling in particular, is that adding more data consistently improves performance (Devlin et al., 2019; Radford et al., 2019; Yang et al., 2019; Liu et al., 2019; Zellers et al., 2019; Shoeybi et al., 2019). Our work offers an alternative method for scaling language models, in which relatively small models learn context representations, and a nearest neighbour search acts as a highly expressive classifier.

Conclusion and Future Work

We have introduced kkNN-LMs, which can significantly outperform standard language models by directly querying training examples at test time. The approach can be applied to any neural language model. The success of this method suggests that learning similarity functions between contexts may be an easier problem than predicting the next word from some given context. Future work should explore explicitly training similarity functions, and reducing the size of the datastore.

The authors thank the anonymous reviewers as well as Sida Wang, Kartikay Khandelwal, Kevin Clark and members of the FAIR Seattle team for helpful discussions and comments.

References

Appendix A Appendix

This section provides several examples where pkNNp_{\text{kNN}} places higher probability mass on the true target, compared to pLMp_{\text{LM}}.