Language models, retrieval, prompting, and language adaptation · Long-context and retrieval-augmented language · LNG058 · Model
k-nearest-neighbor language model (kNN-LM)
Enhances a pretrained language model using a datastore of hidden representations paired with observed next tokens.
In CodeSplash
Documented in the Academy only. There's no Set up button.
- Availability
- Explained here
- Code example
- Component demo, not a trained model
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Enhances a pretrained language model using a datastore of hidden representations paired with observed next tokens. Nearest-neighbor memories can improve rare-event prediction and adaptation without changing every model weight.
Question / objective
Can a nonparametric memory improve a fixed language model's rare-token predictions?
Architecture / computational structure
A frozen or specified base LM supplies hidden keys; a datastore maps keys to observed next tokens and a distance kernel produces a distribution. Base weights may remain fixed; interpolation and neighbor settings are tuned hyperparameters.
Assumptions
A datastore can leak evaluation text or retain private examples.
Formula / computational definition
p_kNN(w|h) is proportional to sum_i:y_i=w exp(-d(h,k_i)/T); combine p(w|h)=lambda p_kNN(w|h)+(1-lambda)p_LM(w|h). Keys k_i represent past contexts and values y_i their observed next tokens.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Neighbor count, distance metric, temperature T, interpolation lambda, datastore domain/size, key layer, and approximate-index accuracy.
Fitting, fine-tuning, and adaptation
Build the datastore only from allowed training text, keeping the base model frozen for the original adaptation route. Tune neighbor count, temperature, and interpolation on development loss. Fine-tuning the encoder requires recomputing keys; validate privacy, contamination, domain retention, storage, and latency.
How to use and calibrate
Compare perplexity, rare-token performance, domain adaptation, datastore contamination, and quality-latency-storage tradeoffs. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Adapt next-word prediction to specialist jargon without updating the base model weights.
Interpretation / pitfalls
Watch out
Distances may be poorly calibrated under domain shift, and retrieval adds substantial memory and latency. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: Use a pretrained model plus a documented vector index in Python; R bridges the encoder and can compute interpolation natively. The example aggregates two-token neighbor probabilities and mixes them with a base distribution, not an end-to-end datastore builder.
Example scope: kNN-LM neighbor aggregation and interpolation with a base token distribution.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Component demo, not a trained model — kNN-LM neighbor aggregation and interpolation with a base token distribution.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
distances, values = [0.1,0.2,0.5], [0,0,1]
w = softmax([-d/0.2 for d in distances])
p_knn = [sum(weight for weight,value in zip(w,values) if value==token) for token in [0,1]]
p = [0.6*k+0.4*b for k,b in zip(p_knn,[0.4,0.6])]
print(p_knn,p)
Component demo, not a trained model — kNN-LM neighbor aggregation and interpolation with a base token distribution.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
distances <- c(0.1,0.2,0.5); values <- c(0L,0L,1L)
w <- softmax(-distances/0.2)
p_knn <- sapply(0:1,function(token) sum(w[values==token]))
p <- 0.6*p_knn + 0.4*c(0.4,0.6)
print(list(knn=p_knn,mixed=p))
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG058.