19 Encoders, Embeddings and Retrieval
The previous chapter left us able to do a good deal with a released language model. We can load one, check that it computes on our machine what its authors computed on theirs, prompt it, and put an error bar on its score. Two ordinary requests still defeat it. Ask it how this book’s old load_array helper decides whether to shuffle its data, and it answers from whatever it absorbed in training. The answer we will meet is fluent and wrong, although the paragraph that says so is somewhere in the book. Ask it to sort the messages of a support desk by topic, ten thousand of them an hour, and it reads its solved examples again for every message. The first request needs a way to find a passage. The second needs a model that learns from labels once and then labels cheaply.
Both requests are met by models that turn text into vectors, so that texts with similar meanings lie close together. The idea is older than neural networks. Linguists of the 1950s proposed that a word is known by the company it keeps, and word2vec made vectors built on that idea cheap to learn from billions of words. BERT computed a vector for every token from the words on both sides of it, and a small layer on top turned those vectors into labels. Contrastive training then taught such encoders to place a question next to the passage that answers it. Encoders still do much of the routine work of search, filtering and tagging, and once they have found the passage, a decoder can answer from documents it never saw in training. One old tool holds its ground through all of this. The word index of a search engine, which does little more than count the words a question shares with a passage, turns out to be the hardest baseline to beat on this book.
The chapter moves in three steps. First we compute vectors: for words, from co-occurrence counts (Section 19.1); for tokens in context, from a pretrained encoder that we fine-tune and set against a prompted decoder (Section 19.2); and for whole texts, by contrastive training (Section 19.3). Then we find passages with a word index and a vector index together, and ask what an approximate index gives up for speed (Section 19.4). Last we hand what was found to a generator, and when an answer comes back wrong, we ask which stage lost it (Section 19.5, Section 19.6).
From the third section on, every experiment runs on one collection: this book without the Language Models part, cut into passages and paired with questions whose answers and source passages we know. Language models, not people, drafted and checked those questions, and Section 19.5 says what that can miss. The load_array question is one of them. We follow it from a search that misses its passage, through a retriever that ranks the passage first, to a generator that answers it from the page. The corpus, the retriever and the questions return later in this part; the agents of Chapter 27, for instance, search the book with this retriever and decide for themselves when to do so.
We start from released encoders and do not pretrain one; Section 11.4 showed on a small scale how that works. Images, which the same contrastive methods can place in one space with text, are left out.
We assume the transformer of Chapter 11 and the prompting, scoring and paired error bars of Chapter 18. We ran the notebooks on one GPU with 24 GB of memory and the judge that grades answers on two, but no notebook requires a GPU. The long computations were done once and their results published with the book. Each notebook fetches them and recomputes a small part of each as a check; without a GPU it takes a cheaper path, with fewer examples or a smaller search, and its output says which. The questions were drafted and checked through a paid API, and the generator’s answers and the judge’s verdicts took hours of GPU time. All of these were recorded once, so the notebooks replay them and call no API.
Resources and Further Reading
The resources below accompany the sections of this chapter, and each names the section it goes with. All are freely accessible online. If you read only three, read the training overview of Sentence Transformers, the Faiss wiki and Jason Liu’s essay on improving a RAG system: between them they cover how an embedder is trained, how an index is chosen, and how to decide what to fix next. Methods that build on the chapter without being taught in it, such as learned sparse retrieval, late interaction and the many ways of improving a retrieval-augmented pipeline, are collected in Section 19.7.
Courses
- Stanford CS224N: Natural Language Processing with Deep Learning opens with word vectors and a first assignment on them, the material of Section 19.1. Its pretraining lecture covers the masked-token encoders of Section 19.2, and its lecture on agents, tool use and retrieval-augmented generation the system of Section 19.5.
- Berkeley CS288 has lectures on text classification, the task of Section 19.2, on retrieval and RAG, and on experimental design, which frames the one-change-at-a-time measurements of Section 19.6.
- CMU 11-711: Advanced Natural Language Processing gives a lecture to retrieval and RAG, with readings on retrieval-based language models that extend Section 19.4 and Section 19.5.
Illustrated introductions
- Jay Alammar’s The Illustrated Word2vec draws the sliding window and the negative samples of skip-gram, a picture to read beside Section 19.1.
- His The Illustrated BERT draws the input layout and the task heads of a masked-token encoder, as Section 19.2 uses them.
- The ModernBERT announcement by the model’s authors explains the design of the encoder that Section 19.2 uses, including two choices the section leaves out: unpadding and its attention kernels.
Libraries and their documentation
- The Sentence Transformers documentation and its training overview describe the library that Section 19.3 checks its derivations against, with the contrastive losses, Matryoshka training and quantized vectors of that section.
- The Faiss wiki explains the inverted files, product quantizers and graphs of Section 19.4, how to name a combination of them, and how to choose one for a collection of a given size.
- Pyserini provides BM25 and other word-index baselines with reproducible settings, and BEIR evaluates retrievers on collections of many kinds, the test behind the warning in Section 19.4 that a dense retriever trained on one collection can fall below BM25 on another.
Building retrieval-augmented systems
- Jason Liu’s Systematically Improving Your RAG and Eugene Yan’s Patterns for Building LLM-based Systems and Products separate the retrieval and the generation of a pipeline and measure each, the decomposition that Section 19.5 and Section 19.6 carry out on the book.
- The Hugging Face cookbook’s Advanced RAG builds a complete pipeline in one notebook, to set beside the pipeline of Section 19.5 and compare stage by stage.