Why do Nearest Neighbor Language Models Work?

Frank F. Xu, Uri Alon, Graham Neubig

Large Language Models (LLMs) traditionally operate as "parametric" systems, compressing vast amounts of knowledge into a fixed set of weights. In contrast, $k$-nearest neighbor language models ($k$NN-LMs) adopt a "semi-parametric" approach. They predict the next word by interpolating a standard LM's output with a retrieval component that searches a massive datastore for similar contexts.

Surprisingly, $k$NN-LMs yield massive accuracy boosts even when the datastore contains the exact same data the model was trained on. If the model has already "seen" the data, why does looking it up again help so much? This paper deconstructs $k$NN-LMs to identify the specific design choices driving these gains, revealing that the "magic" stems primarily from ensembling different internal representations and the regularizing effect of approximate search.

Deconstructing the $k$NN-LM

To understand the source of these improvements, the authors formalize the $k$NN-LM as a generalized version of a standard softmax layer. This framing enables a comprehensive ablation study across several components:

  • Input Representations: Comparing the final feedforward layer output ($h_{ffn}$) against the multi-headed attention output ($h_{att}$).
  • Similarity Functions: Evaluating Inner Product (standard in LMs) versus L2 distance (standard in $k$NN).
  • Search Precision: Contrasting exact $k$NN search with approximate search (using the FAISS library).
  • Softmax Capacity: Testing whether adding more trainable parameters (e.g., multiple embeddings per word) can mimic the $k$NN effect.

Experiments were primarily conducted on Wikitext-103, a standard benchmark for long-range language modeling, and validated across the GPT-2 family (Distilled, Small, Medium, and Large) to ensure generalizability.

Key Mechanisms Driving Performance

The researchers identified several core phenomena that explain the success of $k$NN-LMs:

  • The Power of Two Views: Standard LMs typically use the output of the final feedforward layer to predict words, whereas $k$NN-LMs often use the output of the attention layer. The authors discovered that simply ensembling these two different "views" of the same context accounts for 55% of the total performance gain. Remarkably, more than half the benefit can be achieved without any retrieval at all.
  • The Regularization Paradox: Counter-intuitively, approximate search outperforms exact search. Using "fuzzy" results from FAISS helps the model generalize better. The authors hypothesize that exact search leads to overfitting on the training data, while the noise introduced by approximate search acts as a beneficial regularization mechanism.
  • Bypassing the Softmax Bottleneck: Standard LMs are limited by the "softmax bottleneck"—a mathematical constraint where a single vector cannot represent all possible next-word distributions. $k$NN-LMs bypass this by providing a massive, high-rank distribution that a standard parametric layer cannot match.
  • The Importance of Temperature: Tuning the softmax temperature ($\tau$) for the $k$NN component is critical. Previous work often relied on a default of 1.0, which the authors demonstrate was a lucky coincidence; in other settings, an unoptimized temperature can negate the advantages of the $k$NN-LM.

Results and Parametric Alternatives

On the Wikitext-103 benchmark, implementing a $k$NN-LM reduced the base model's perplexity from 21.75 to 19.10.

Leveraging their insights, the authors introduced a "parametric ensemble" alternative—using a separate embedding matrix for the attention output. This approach recovered a 6.5% relative improvement in perplexity, capturing a significant portion of the $k$NN-LM's benefit without the massive memory overhead or latency associated with retrieval. Furthermore, the "beneficial search bias" of approximate search provided a 2.6% relative improvement over exact search.

Limitations and Future Directions

While the authors successfully replicated over half of the $k$NN-LM's gains using a more efficient parametric model, a performance gap remains. The full $k$NN-LM retains its accuracy advantage, likely due to its effectively infinite "rank" compared to fixed-parameter models.

Future research directions include:

  1. Closing the Gap: Developing methods to achieve full $k$NN-LM performance using only trainable parameters, thereby eliminating retrieval latency entirely.
  2. Optimization Challenges: The authors attempted to train models directly on the "interpolated loss," but it underperformed expectations. Solving this optimization hurdle is a critical next step.
  3. Scaling: Investigating whether these insights hold at the "trillion-token" scale, where maintaining a retrieval datastore becomes prohibitively expensive.

Summary updated

BibTeX
@inproceedings{xu2023why,
  author = {Frank F. Xu and Uri Alon and Graham Neubig},
  title = {{Why do Nearest Neighbor Language Models Work?}},
  booktitle = {International Conference on Machine Learning},
  year = {2023},
  url = {https://openreview.net/forum?id=ARDbU7beLp},
}
Figure