Skip to content

Language models, retrieval, prompting, and language adaptation · Long-context and retrieval-augmented language · LNG049 · Model

RETRO

Augments an autoregressive language model with retrieved text chunks from a large external database. Retrieval supplies nonparametric information during prediction, changing the role of model weights versus corpus…

Explained here Component demo, not a trained model CodeSplash's own run

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 here in one language.
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

Augments an autoregressive language model with retrieved text chunks from a large external database. Retrieval supplies nonparametric information during prediction, changing the role of model weights versus corpus storage.

Question / objective

Can retrieved text chunks improve next-token prediction without storing all knowledge in weights?

Architecture / computational structure

A causal generator uses chunk retrieval, a neighbor encoder, and retrieval cross-attention. Learned generator/retrieval-encoder weights are parameters; database, chunk size, neighbor count, and refresh cadence are system choices.

Assumptions

Retrieval can expose duplicated targets or copyrighted/private material; benchmark leakage is especially important when the retrieval corpus overlaps evaluation data.

Formula / computational definition

Nt=Retrieve⁡(x<t),L=−∑tlog⁡pθ(xt∣x<t,Nt).\mathcal N_t=\operatorname{Retrieve}(x_{<t}),\qquad \mathcal L=-\sum_t\log p_\theta(x_t\mid x_{<t},\mathcal N_t).

Chunk a prefix, retrieve nearest-neighbor chunks using an encoder/index, encode their continuations, and condition generation through retrieval cross-attention. The objective remains target-token negative log likelihood conditioned on both prefix and retrieved evidence.

Parameters and notation

Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Chunk length, neighbors per chunk, retriever/index, database freshness, continuation length, retrieval frequency, and cross-attention placement.

Fitting, fine-tuning, and adaptation

Training requires retrieval-conditioned token loss and carefully deduplicated corpus data. Adapt generator/retrieval components explicitly, freeze one component for controlled studies, and reindex when embeddings change. Validate evidence usefulness, contamination, domain retention, and the cost of retrieval at generation time.

How to use and calibrate

Measure perplexity and downstream accuracy with retrieval ablations, deduplicated databases, database-size curves, latency, and evidence provenance. 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

Improve rare technical phrase prediction by consulting a versioned external text database.

Interpretation / pitfalls

Watch out

Poor neighbors may distract the generator. 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: Full reproduction requires the published architecture plus an embedding index and large retrieval corpus; a generic nearest-neighbor call is insufficient. Python has research implementations; R can bridge them via reticulate and independently evaluate retrieved evidence. The native example scores candidate chunks only.

Example scope: RETRO candidate chunk retrieval by squared Euclidean distance on supplied vectors.

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.

Python

Component demo, not a trained model — RETRO candidate chunk retrieval by squared Euclidean distance on supplied vectors.

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)
query = [0.6,0.4]; chunks = [[1,0],[0.5,0.5],[-0.5,0.2]]
distances = [sum((a-b)**2 for a,b in zip(query,c)) for c in chunks]
print(sorted(range(len(chunks)),key=distances.__getitem__)[:2])
R

Component demo, not a trained model — RETRO candidate chunk retrieval by squared Euclidean distance on supplied vectors.

Shared setup for this chapter
softmax <- function(x) {
  shifted <- exp(x-max(x))
  shifted/sum(shifted)
}
query <- c(0.6,0.4); chunks <- rbind(c(1,0),c(0.5,0.5),c(-0.5,0.2))
distances <- rowSums(sweep(chunks,2,query,"-")^2)
print(order(distances)[1:2])

Sources

From the CodeSplash reference, entry LNG049.