← Back to research notes

Why nearest-neighbor language models mix probabilities

November 8, 2026 · 7 min read

Abstract

When a language model retrieves similar training contexts, why blend their next-token votes with its own prediction instead of trusting the retrieved examples? This review isolates the statistical role of that blend. A small neighborhood provides sharply localized evidence, but it can omit valid continuations or confidently represent the wrong population. Interpolation preserves a fallback distribution while letting retrieval correct particular predictions. The central question is therefore when a fixed mixing weight helps, and when its protection becomes too expensive. Two original calculations below make that tradeoff explicit; they are illustrative examples, not benchmark results.

Related Work

The central primary source is Khandelwal et al. (ICLR 2020), whose kNN-LM combines a frozen neural predictor with an external datastore of context representations and following tokens. This established research predates the one-month cutoff by years. The mechanism retrieves token evidence directly rather than inserting documents into a prompt.

Yogatama et al. (2021) extend the design space with adaptive gates over local context, short-term memory, and long-term memory. Their work makes the allocation of trust an explicit modeling decision. He et al. (2021) investigate the cost of external retrieval, including adaptive retrieval, datastore pruning, and dimensionality reduction. Together, these papers motivate separating three questions: whether memory contains useful evidence, how much weight it deserves, and whether consulting it is worth the computation.

Method/Mechanism

In the original kNN-LM, each stored key represents a preceding context; its value is the next token. At inference, nearby keys receive weights proportional to the exponential of negative distance. Weights for identical token values are added and normalized. Write this distribution as q(y), and the neural distribution as p(y), suppressing their shared conditioning context. The prediction is:

r(y) = (1 − λ)p(y) + λq(y), with 0 ≤ λ ≤ 1.

The following deductions are direct consequences of this mixture. If a token is absent from the retrieved values, q assigns it zero probability. For any λ below one, a positive neural probability survives. Specifically, r(y) ≥ (1 − λ)p(y). Taking negative logarithms yields a per-token bound:

−log r(y) ≤ −log p(y) − log(1 − λ).

This is a fallback guarantee relative to the base predictor, not a guarantee of improvement. With λ = 0.5, even completely unhelpful retrieval adds at most log 2, approximately 0.693 nats, to that token’s loss. Across a long sequence, such penalties accumulate. A modest-looking interpolation coefficient can therefore have substantial consequences if retrieval repeatedly misses the correct continuation.

Example 1: useful evidence with incomplete coverage

Consider a toy vocabulary containing a specialist name, a common noun, and a third valid continuation. Let the neural probabilities be (0.05, 0.55, 0.40). Suppose four equally weighted retrieved examples have next-token values consisting of three specialist names and one common noun. Then q = (0.75, 0.25, 0), and a half-and-half mixture gives r = (0.40, 0.40, 0.20).

If the specialist name is correct, its loss falls from −log 0.05 ≈ 2.996 to −log 0.40 ≈ 0.916 nats. If the third continuation is correct, retrieval alone gives infinite loss, whereas interpolation gives −log 0.20 ≈ 1.609. The base predictor would have incurred 0.916. The same mechanism produces a large gain on one outcome and a bounded penalty on another.

This example also distinguishes probability mixing from averaging logits. A geometric combination proportional to p(y)1−λq(y)λ would retain q’s zero for any positive λ. Arithmetic interpolation preserves support because either component can contribute mass independently. The choice of combination rule is part of the statistical model.

Example 2: agreement among neighbors can mislead

Now suppose p = (0.60, 0.30, 0.10), while a neighborhood drawn from duplicated, outdated records yields q = (0.05, 0.90, 0.05). At λ = 0.5, r = (0.325, 0.60, 0.075). If the first token is correct, the mixture changes the winning prediction and raises loss from approximately 0.511 to 1.124 nats. Strong agreement among neighbors has amplified a systematic mismatch.

The diagnostic is not merely neighborhood entropy. Repeating the same misleading source many times can make the retrieved distribution look highly concentrated without adding independent evidence. Distances measure similarity under a representation; neither small distances nor repeated token votes establish that the underlying records are current or applicable.

For a known target y, differentiating its mixture loss gives d[−log r(y)]/dλ = (p(y) − q(y))/r(y). Increasing retrieval weight helps exactly when q assigns that target more probability than p. At prediction time the target is unknown, so a usable gate must forecast this advantage from observable features. Optimizing a single λ on held-out text averages over contexts where retrieval helps and contexts where it hurts.

A useful interpretation is a latent choice between two predictors: first choose the neural or retrieval component with probabilities 1 − λ and λ, then sample from the chosen distribution. This interpretation explains why disagreement is allowed. The mixture does not require both predictors to endorse every token. It also shows why the components need not be equally calibrated for the arithmetic to define a valid distribution, although poor calibration can still make that distribution predict badly.

Key Findings

On WikiText-103, Khandelwal et al.’s Table 1 reports test perplexity of 18.65 for the base model and 16.12 with kNN augmentation. Adding a continuous cache reaches 15.79. These are separate configurations, and the lower number should not be attributed to kNN augmentation alone. Four insights follow from the mechanism and examples:

Limitations

The bound assumes normalized distributions and exact arithmetic; implementations must handle underflow and smoothing explicitly. It compares against the same base predictor at the same context. It does not guarantee a generated sequence stays close to a base-model sample, since changed early tokens alter later contexts. Perplexity also measures predictive fit rather than factual correctness, usefulness, or safe behavior.

The original benchmark result does not establish the optimal mixture for contemporary instruction-tuned LLMs. Retrieval coverage, representation geometry, and datastore composition can all change. He et al. report up to sixfold inference speedups over their retrieval baseline with comparable performance, but this is an experimental result under particular configurations, not a universal latency multiplier.

There is also an evaluation trap in reporting only average improvement. A retrieval system could substantially help a few rare names while slightly degrading many ordinary continuations. Another could achieve the same average through small, widespread gains. These systems have different failure profiles. The worked examples suggest measuring the distribution of per-token loss changes, stratified by whether the target appears among retrieved values. That analysis would reveal whether interpolation mainly repairs coverage failures, rescues rare continuations, or shifts errors between groups. It would not by itself establish which source deserves trust on a new query.

Future Directions

A controlled experiment should freeze the neural predictor and independently vary neighbor coverage, source duplication, and domain mismatch. Compare a fixed λ with a learned gate using distances, token agreement, source diversity, and neural uncertainty. Evaluate held-out log loss and the worst deterioration across these conditions. Report retrieval cost separately, and reserve shifted datastores for testing so the gate cannot simply memorize a familiar failure pattern.

Open question: Can a gate predict when retrieved token evidence will outperform the neural distribution under datastore shift, while retaining a useful bound on the loss incurred when its trust decision is wrong?

Summary

Probability interpolation lets a neighborhood make specific corrections while preserving a neural fallback. Its strength is also its tradeoff: increasing retrieval weight enlarges both potential corrections and the penalty for missing support. The research problem is learning when to trust the neighborhood, with reliability evaluated beyond confident agreement among retrieved examples.

References

  1. Khandelwal, Levy, Jurafsky, Zettlemoyer, and Lewis (2020). Generalization through Memorization: Nearest Neighbor Language Models. ICLR. Primary source; equations 2–3 and Table 1.
  2. Yogatama, de Masson d’Autume, and Kong (2021). Adaptive Semiparametric Language Models. TACL.
  3. He, Neubig, and Berg-Kirkpatrick (2021). Efficient Nearest Neighbor Language Models. EMNLP.