kNN-LM

Also known as: k-nearest neighbor language model

On this page 7

kNN-LM, the k-nearest neighbor language model, is a method that improves a pretrained neural language model by interpolating its next-token distribution with a distribution built from the nearest neighbors of the current context in a large datastore of stored context representations. It belongs to the Retrieval & knowledge family of techniques in artificial intelligence, where external memory supplements what a model has learned in its weights.

Introduced in 2020 under the idea of generalization through memorization, kNN-LM requires no additional training of the base model. It changes only inference: the model looks up contexts it has seen before, notes which token followed them, and uses that evidence to sharpen its own prediction.

How kNN-LM builds and queries its datastore

The method has two phases. In the datastore construction phase, a frozen language model makes a single forward pass over a text collection. For every token position, it stores a key-value pair: the key is the model’s hidden representation of the preceding context, and the value is the actual next token.

In the inference phase, the model encodes the current context into the same kind of vector and runs a nearest neighbor search over the keys. The retrieved neighbors vote for their stored next tokens, weighted by a softmax over negative distances, which yields the retrieval distribution. The final prediction mixes the two distributions with an interpolation weight called lambda.

The following table summarizes the core components of kNN-LM and their typical settings in the original formulation.

ComponentWhat it isTypical setting
KeyHidden state of the contextInput to the final feed-forward layer
ValueToken that followed the contextOne vocabulary item
kNumber of neighbors retrievedHundreds to about 1,024
DistanceSimilarity measure between keysSquared Euclidean distance
LambdaWeight of the retrieval distributionAbout 0.2 to 0.3 in domain
IndexStructure for fast searchFAISS with quantization
Core components and typical settings

Why memorization improves prediction

kNN-LM works because similarity between contexts is easier to learn than the next word itself. The neural model may assign a modest probability to a rare token, yet its representation of the context can still sit very close to stored contexts that were followed by exactly that token.

The gains are largest for rare patterns and long-tail facts, such as names, numbers and fixed phrases, which a parametric model compresses poorly. On the WikiText-103 benchmark, the original work reported a perplexity drop from roughly 18.7 to roughly 16.1 without any retraining, a notable result for that benchmark at the time.

The table contrasts where parametric memory and the datastore each contribute most.

AspectParametric modelkNN datastore
Common syntaxStrongAdds little
Rare entitiesOften underestimatedStrong when present
New domain textNeeds fine-tuningAdded by indexing
Knowledge updatesRequires retrainingEdit the datastore
Inference costOne forward passPlus a vector search
Parametric prediction compared with retrieval in kNN-LM

kNN-LM compared with other retrieval-augmented models

kNN-LM differs from most retrieval-augmented systems in what it retrieves and where retrieval enters. It retrieves individual tokens at the output layer, whereas systems such as RAG, REALM and RETRO retrieve text passages and feed them into the model’s input or intermediate layers.

ApproachRetrieved unitIntegration point
kNN-LMNext-token valuesOutput distribution
RAGText passagesPrompt or encoder input
REALMDocumentsPretraining and input
RETROText chunksChunked cross-attention
kNN-MTTarget-language tokensTranslation output distribution
Retrieval granularity and integration point

Because kNN-LM never shows retrieved text to the model, it cannot reason over retrieved evidence or cite a source passage. Its strength is fine-grained, training-free adaptation of the output distribution, which makes it closer to a smoothing technique than to a question-answering pipeline.

The approach also differs in storage granularity. A passage retriever might index a few million chunks, while a kNN-LM datastore over the same corpus contains one vector for every token, which is often hundreds of times larger. Later variants reduce this burden by pruning redundant entries, merging neighbors that predict the same token, or following automaton-like pointers between consecutive datastore entries so that fewer searches are needed.

In machine translation, the same principle appears as kNN-MT, which retrieves target-language tokens from a datastore of translated sentence pairs. Both methods show that a frozen model plus a searchable memory can adapt to new text far more cheaply than retraining.

Practical use and configuration

kNN-LM is most useful for domain adaptation without fine-tuning: building a datastore from in-domain text lets a general model absorb specialized vocabulary. It is also a research tool for studying how model representations encode context similarity.

Configuration involves a few decisions that strongly affect quality and cost. The decision table below summarizes recommended choices for common situations.

SituationRecommended choiceReason
In-domain datastoreModerate lambdaNeighbors are reliable
Out-of-domain queriesLower or adaptive lambdaPoor neighbors add noise
Billions of entriesQuantized approximate indexMemory and latency limits
Latency-sensitive serviceSmaller k and cachingSearch dominates cost
Frequently changing textIncremental datastore updatesNo retraining required
Configuration decisions for kNN-LM

Limitations and known trade-offs

The main obstacle is storage and search cost. The datastore holds one entry per training token, so a corpus of 100 million tokens produces 100 million high-dimensional vectors, often requiring heavy quantization and approximate search.

  • Inference slows down noticeably because every generated token triggers a vector search.
  • Gains shrink for larger models, which already memorize much of what the datastore supplies.
  • Open-ended generation can degrade, since retrieved tokens may encourage repetition or copying.
  • Privacy and licensing risks arise because the datastore contains verbatim training text.
  • A fixed lambda is suboptimal; adaptive weighting based on retrieval confidence usually works better.

In everyday language

A language model guesses the next word in a sentence. kNN-LM gives it a giant notebook of past sentences. Before guessing, the model looks up situations that resemble the current one. It checks which word came next in those cases.

Then it combines two opinions: its own guess and the notebook’s evidence. This is like a translator who checks earlier translations before choosing a rare term. The key point is that the model improves without new training, simply by consulting stored examples.

Seen in the real world

A research group works with a general language model that performs poorly on legal contract text, where defined terms and clause numbering follow strict patterns. Fine-tuning would require new compute budgets and a separate model version for each client.

Instead, the group runs the frozen model once over about 50 million tokens of anonymized contracts and stores every context vector with its next token in a quantized FAISS index. At inference, the model retrieves 1,024 neighbors per token and mixes them in with a lambda of 0.25.

Perplexity on held-out contracts drops clearly, and the model now completes defined terms correctly far more often. The trade-off is latency: each token takes noticeably longer to generate, so the group uses kNN-LM for batch drafting and scoring, not for interactive chat.