CComputer Science, Built

Act IX · Systems at Scale

Part 47 of 61

Search Engines

Degreestarts at this level53 min of film17 chaptersprerequisites: Part 16, Part 18, Part 20, Part 39

How do you find the ten most relevant passages among billions in a fifth of a second?

The part opens with the history of finding things, from Archie's file names in 1990 through AltaVista to Google's links as votes, and with its own engine: 11,261 passages of the thirty novels, 40,692 terms, 2,364,691 postings. Words are tokenized and stemmed by Porter's rules, and their counts follow Zipf's and Heaps' laws. The inverted index turns a query into a merge of sorted lists, where skip pointers and galloping search cut the comparisons for 'the AND whale' from 11,137 to 1,418. Stored as gaps, postings shrink from 32 bits to 4.96 under Rice codes, within 5% of the counting bound. Ranking is derived from the probability ranking principle through the binary independence model to BM25, and judged with average precision and nDCG on nine queries, which a sign test shows are too few to separate BM25 from tf-idf. WAND returns the same top ten while scoring as few as a tenth of the candidates. The part then adds what the web needs: PageRank as a Markov chain's stationary distribution, a link farm that lifts its target from 346th to 114th, crawling with SimHash, sharded serving, spelling correction, learning to rank, and dense retrieval with product quantization and HNSW. It ends at the frontier: graph search without a recall guarantee, learned sparse retrieval, and retrieval for models that write.

What you need. Logarithms, and probability at the level of Bayes' rule and a geometric distribution; the eigenvector view of a Markov chain helps for PageRank.

Mathematics, ideas and history
inverted indexes, postings compression (γ, δ, Golomb), BM25 derived, nDCG, WAND, PageRank, crawling, sharded serving, learning to rank, product quantization and HNSW
What we build or compute
a search engine for the thirty novels

What you will be able to do

Degree

  • Build an inverted index for a few documents by hand and answer an AND query by merging postings.
  • Compute precision, recall and nDCG at k for a ranked list with graded judgments.
  • Run two steps of PageRank's power iteration on a small graph, including a page without links.

Graduate

  • Derive the lengths of Elias gamma codes and the Golomb parameter for geometric gaps, and compare a list's size with the bound log2 C(N, f).
  • Derive BM25 from the binary independence model, and explain what k1 and b control.
  • Explain why WAND's pivot rule never loses a top-k document.

Research

  • Explain why graph-based nearest-neighbour search has no worst-case recall guarantee, and what locality-sensitive hashing guarantees in its place.
  • State what is open in evaluating retrieval for generated answers.

Industry

  • Choose between document- and term-partitioned indexes, and use hedged requests against the tail of a fan-out.
  • Build a judged query set and decide with a significance test whether a ranking change is an improvement.
  • Combine lexical and dense retrieval, with compressed codes for the shortlist and exact vectors for re-ranking.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 51 min · Research 53 min · Industry 34 min.

  1. 0Ten pages among billionsDegree2 min
  2. 1Words, stems and ZipfDegree4 min
  3. 2The inverted indexDegree3 min
  4. 3Merging postingsDegree3 min
  5. 4Compressing postingsGraduate3 min
  6. 5From tf-idf to BM25Graduate3 min
  7. 6Is the ranking good?Degree3 min
  8. 7Top k, fastGraduate3 min
  9. 8Links and the random surferDegree4 min
  10. 9Crawling the webIndustry3 min
  11. 10Serving at scaleIndustry3 min
  12. 11Spelling and autocompleteGraduate4 min
  13. 12Learning to rankIndustry3 min
  14. 13Dense retrievalGraduate4 min
  15. 14A search engine for the novelsIndustry2 min
  16. 15Frontier: retrieval and its limitsResearch2 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Ten pages among billionsDegree2 min

How do you find the ten most useful pages among hundreds of billions, in a fraction of a second? The first search engine, Archie, written at McGill University in 1990, indexed the names of files on FTP servers, not their contents. By 1994 there were crawlers and directories of the web, and in 1995 AltaVista searched the full text of the web, quickly. In 1998 Sergey Brin and Larry Page described Google, which treated links between pages as votes, and began with an index of twenty-four million pages. Today's indexes hold hundreds of billions of pages, and rank them with learned models and dense vectors as well as words.

A search engine rests on five ideas, and each is a piece of mathematics this series has met. An inverted index turns a query into the merging of sorted lists. Compression keeps those lists small enough to hold in memory. A probabilistic model of what relevant means produces the ranking formula called BM25. A random surfer wandering over links produces PageRank. And vectors place documents near queries that mean the same thing, found by searching a graph.

In this part we build one, for the thirty novels of this series. The novels are cut into 11,261 passages of four hundred words, and indexed: 40,692 distinct terms, 2,364,691 postings. Ask it for the white whale, and it ranks the passages, and shows each with a snippet around the words that matched. By the end of the part every step of that will be ours: the tokenizer, the index, the compression, the ranking, and an evaluation of how good the ranking is.

1Words, stems and ZipfDegree4 min

A search engine sees characters, and its first job is to decide what the words are. Our tokenizer keeps runs of letters and digits and folds them to lower case, so that Whale at the start of a sentence and whale in the middle become one term. Folding has a price: it also merges US, the country, with us. Next come stop words, forty-eight short words such as the, of and a. In Jane Austen's first sentence they are twelve of the twenty-three tokens. Our index keeps them, because phrases need them, but ranked queries drop them. Last, stemming cuts each word down to a stem, so that acknowledged, acknowledges and acknowledging all become one term.

Martin Porter published his stemmer in 1980, and it is still in wide use for English. It uses no dictionary: about sixty suffix rules in five steps, applied in order. Follow generalizations. Step one strips the plural. Step two turns ization into ize, step three turns alize into al, and step four removes the al, leaving gener. A rule may fire only if enough of the word would remain. Porter measures a stem by counting its vowel-consonant pairs: gener has two, so its al can go, but riv has only one, so rival keeps its ending. Our implementation reproduces all twenty of the published examples. It merges whaling and whales into whale, and connection, connected and connecting into connect. It also errs: general and generous both become gener, and ran never meets run. A lemmatizer, with a dictionary of word forms, would fix both, at a price.

Now count. The thirty novels hold four and a half million tokens, and sixty-one thousand seven hundred and twenty different words. The commonest, the, occurs two hundred and thirty thousand times: one token in twenty. The top twenty words make up almost a third of all the text. Plot frequency against rank, both on logarithmic scales, and the points fall close to a straight line. That is Zipf's law: George Kingsley Zipf described it in the 1930s and 1940s, with frequency roughly proportional to one over the rank. Fitted between ranks ten and ten thousand, our line has slope minus one point two one. At the other end, twenty-two thousand eight hundred and eighty-eight words, more than a third of the vocabulary, occur exactly once. So an index must handle a few enormous postings lists and a vast number of tiny ones, both cheaply.

How fast does the vocabulary grow as we read? Here is the number of different words seen, against the number of tokens read, novel after novel. It climbs steeply, then ever more slowly, but it never levels off: every book brings new names and new words. Gustav Herdan, and later Harold Heaps, described this as a power law: the vocabulary grows as a constant times the number of tokens to a power beta. Our fit gives beta of nought point four eight five, close to a half, so a hundred times the text brings about ten times the vocabulary. The jump at the end is Ulysses, last in our order, and the richest in new words. Stemming cuts the vocabulary by a third, to forty thousand six hundred and ninety-two terms. Those terms are the dictionary of the next chapter.

2The inverted indexDegree3 min

Without an index, every query must read all four and a half million tokens of the novels. Picture instead a table with a row for every term and a column for every passage, marked where the term occurs. For our novels that is forty thousand six hundred and ninety-two rows by eleven thousand two hundred and sixty-one columns: four hundred and fifty-eight million cells. Only two point three six million are marked, about half of one per cent. So keep only the marks: for each term, the sorted list of passages that contain it, called its postings. The text, turned on its side, has become an inverted index: from words to passages.

An inverted index has two parts. The dictionary holds every term with its document frequency, the number of passages that contain it, and the place where its list begins. Whale is in three hundred and ninety passages, Ahab in a hundred and eighty-one. The dictionary can be a hash table, from Part 17, or a sorted tree, which also allows prefix searches. The postings hold passage numbers in increasing order, each with the positions where the term occurs. The next chapters rely on that order: sorted lists merge, and neighbours are close. Whale begins with a run, passages six hundred and fifty-nine to six hundred and sixty-nine: the opening of Moby-Dick, with its pages of quotations about whales. Words cluster, and clusters compress.

How is the index built? The simplest way is to sort. Read the passages in order, and write down a pair for every term in each: the term and the passage number. Sort the pairs by term, and within a term by passage. Now each term's pairs sit together, and reading them off gives its postings, already in order. The novels make two point three six million pairs; at eight bytes a pair, that is nineteen megabytes, one sort in memory. A crawl of the web makes far more pairs than any memory holds. So sort as many as fit, write each sorted block to disk as a run, and merge the runs: Part 16's external sort, unchanged. This is blocked sort-based indexing.

3Merging postingsDegree3 min

A query for whale and sea wants the passages on both postings lists. Because both lists are sorted, one walk finds them. Keep a finger on each list and compare the two numbers. If they are equal, that passage is an answer, and both fingers move on; if not, the finger on the smaller number moves. Every comparison moves at least one finger, so the walk costs at most the sum of the two lengths. The same walk computes OR, keeping everything it passes, and AND NOT. With more than two terms, begin with the shortest lists, because an intersection can only shrink.

Galloping, from Part 24, goes further. Take each passage of the short list in turn and look for it in the long list: probe one place ahead, then two, four, eight and sixteen, doubling until a probe overshoots. Then binary search the last gap. Jon Bentley and Andrew Yao described this unbounded search in 1976. Finding m items in a list of n this way costs about m times the logarithm of n over m, far less than the walk when m is small. The AND whale now takes one thousand four hundred and eighteen comparisons, and love AND marriage one thousand nine hundred and fifteen, against two thousand six hundred and eighty for the merge.

Here are all three on five queries over the novels. When the two lists are of similar length, like whale and sea, or Elizabeth and Darcy, the merge or skips win, and galloping wastes its probes. When one list is five or twenty-nine times longer, galloping wins, nearly eight times over for the AND whale. So engines choose by the ratio of the lengths, or use adaptive algorithms, like those of Erik Demaine, Alejandro López-Ortiz and Ian Munro, which do well on any mix. And comparisons are not the whole cost: Part 24's branch-free loops and SIMD instructions, comparing several ids at once, matter as much.

Some queries are phrases: white whale, the two words adjacent and in order. That is why our postings keep positions. First intersect the passage lists, as before. Then, inside each passage that has both words, shift every position of whale back by one, and intersect with the positions of white. Each survivor is a place where the phrase begins. In the novels, a hundred and twenty-five passages contain both white and whale, but only sixty-four contain the phrase. Three passages contain call, me and Ishmael, and exactly one has the phrase: the first line of chapter one. Positions are not free: four and a half million of them, beside two point four million passage ids. The next chapter makes all of it small.

4Compressing postingsGraduate3 min

Chapter two's index holds two point three six million postings: as thirty-two-bit integers, nine and a half megabytes of document ids, and a web index holds vastly more. Here are the first twelve passages that contain whale. The list is sorted, so store the differences between neighbours instead: the gaps. The first is the id plus one, since our codes start at one. A term in f of N passages has gaps averaging N over f: for whale, about twenty-nine. Frequent terms have short gaps; rare terms have long ones, but few. So give small numbers short codes.

The simplest code works in whole bytes. Each byte carries seven bits of the gap and a flag that marks the last byte. One and five fit in a byte; six hundred and sixty has ten binary digits, so it takes two. Over the index: eight point six seven bits a posting, about a quarter of thirty-two. Decoding is a mask, a shift and a test, so it is fast. But a gap of one still costs eight bits.

But we know each list's length, so fit the code to it. If each passage holds a term independently, with probability p equal to f over N, gaps are geometric. Solomon Golomb's code of 1966 divides g minus one by a parameter M: the quotient in unary, the remainder in binary. The quotient is geometric too, and unary, one more bit per step, is ideal when each step halves the probability. So set one minus p, to the power M, to one half: M is about point six nine times the mean gap, near twenty for whale. Rice rounds M down to a power of two, so the remainder takes exactly k bits: here, four.

Here are Rice codes with k equal to two. Gaps of one to four take three bits, and each further four adds a single one. With its own k for every list, Rice spends four point nine six bits a posting over the whole index. And there is a floor. Choosing which f of N passages hold a term carries log of N choose f bits: four point seven four a posting here. Rice comes within five percent of it.

5From tf-idf to BM25Graduate3 min

Boolean retrieval answers yes or no, but a reader wants the best passage first. A word that recurs in a passage says more about it, so weight it by its term frequency, damped by a logarithm: the tenth whale adds less than the first. And a rare word says more than a common one: Karen Spärck Jones, in 1972, weighted each term by the log of N over its document frequency. Whale, in three hundred and ninety of our passages, gets three point three six; Darcy, in a hundred and seventy-one, four point one nine.

In 1977 Stephen Robertson stated the principle that answers it. Rank documents by their probability of being relevant. If those probabilities are right, and documents are relevant independently, no other order puts more relevant documents, in expectation, into the top k, for any k. The proof is an exchange: swap a likelier document below the cut with a less likely one above it, and the expected count falls. So ranking reduces to estimating one probability from words.

The binary independence model is the simplest estimate. Ranking by probability is ranking by odds. Bayes' rule turns the odds around, and the prior odds are the same for every passage, so they drop out. Treat a passage as present or absent terms, independent given relevance. The log odds become a sum over the query terms the passage contains, each weighted by how much likelier it is in relevant passages. Knowing nothing about relevance, set p to one half; since almost every passage is irrelevant, set u to the document frequency over N. Out comes idf, derived rather than guessed: Robertson and Spärck Jones, 1976.

But that model counts a word once, however often it appears, and a passage that says whale twenty times is likelier to be about whales. Stephen Harter's two-Poisson model of 1975 says a passage either is about the term or is not, with the count Poisson in each case; the weight it implies grows with the count and levels off. Robertson and Walker, in 1994, approximated it with one curve: term frequency times k one plus one, over term frequency plus k one. It is one at a single occurrence and rises towards k one plus one. With k one near zero, it is the binary model again; as k one grows, raw counts.

One more correction. A long passage repeats words because it is long, not because it is more about them. So BM25 scales k one by one minus b, plus b times the passage's length over the average. A passage twice the average needs more occurrences for the same weight; with b zero there is no normalization, with b one, full. Put together: idf from the binary model, saturation from two Poissons, and length. That is BM25, first run at TREC in 1994, and Lucene's default, with k one of one point two and b of three quarters.

6Is the ranking good?Degree3 min

To improve a ranking, we have to measure it. Here is a ranking of ten passages, the relevant ones in colour. Precision at k is the fraction of the top k that is relevant: how much of what the reader sees is useful. Recall at k is the fraction of all relevant passages that the top k contains. Six exist here, and one is never retrieved. Reading further down, recall can only rise, while precision tends to fall, so one cutoff tells only part of the story.

Average precision folds the list into one number. At each rank where a relevant passage appears, take the precision so far: one of one, two of three, three of four, and so on. Add them up and divide by the number of relevant passages, so the one never retrieved counts zero: here, point five nine. It rewards ranking relevant passages high and finding them all. Its mean over queries is MAP. On our nine test queries, cut at ten results, BM25 scores point eight zero and tf-idf point seven five.

But relevance comes in degrees, and readers rarely reach the bottom. Järvelin and Kekäläinen's measure of 2002 handles both. Each passage gets a grade, and a gain of two to the grade minus one, so a highly relevant passage is worth three relevant ones. Discount each gain by the log of its rank plus one: rank one counts in full, rank ten under a third. The sum is the discounted cumulative gain. Divide by the same sum for the ideal order of every judged passage, and each query scores between zero and one, however many relevant passages it has. Here, point eight zero.

Here are our nine queries. For most, both rankers fill the top ten with relevant passages, and nDCG is one: names are easy. Sherlock Holmes scores point six zero for both, and the fault is ours. Four of the top ten come from The Hound of the Baskervilles, which has Holmes in it too, but our rule counts only the Adventures. A bad score can be a bad judgment. Vampire count is a real failure: The Count of Monte Cristo is full of the word count. On average, BM25 scores point eight five and tf-idf point eight three.

Is that difference real, or luck? Pair the rankers query by query. Six queries tie, three favour BM25, and none favour tf-idf. If neither were better, each untied query would be a fair coin. Three heads in three tosses has probability one in eight, or one in four counting tails as well: p is point two five. Nine queries cannot tell. That is why TREC tracks use about fifty topics, with the paired tests and power calculations of Part 44; and in production, judged sets are joined by clicks and online experiments, which chapter twelve takes up.

7Top k, fastGraduate3 min

A reader wants ten results, not a ranking of every passage. The simplest evaluation walks the postings of all the query's terms together, in document order, scores every passage containing any of them, and keeps the best ten in a min-heap. The smallest score in that heap is the threshold, theta: the score to beat. For the query the sea, eleven thousand two hundred and fifty-seven of our eleven thousand two hundred and sixty-one passages are scored, and all but ten scores are thrown away.

Better to know, before scoring, the most a passage could score. When the index is built, store with each term the largest contribution it makes to any passage. Chapter five's saturation caps it anyway; the stored maximum is tighter. Suppose theta is two point six. A passage with only captain and ship scores at most two, so it cannot enter the top ten and need not be scored. Only passages with ahab can. Turtle and Flood's max-score, in 1995, used exactly this: terms whose bounds together cannot reach theta never propose a candidate.

Broder and his colleagues, in 2003, made the bound into a walk called WAND, for weak, or weighted, and. Each term has a cursor. Sort the cursors by the document they point at, and add up their bounds in that order: the first cursor where the sum passes theta is the pivot. No earlier document can reach theta, so every earlier cursor jumps straight to the pivot document, with chapter three's skip pointers or galloping. When they all land on it, that document is scored in full. Here four of thirteen documents are scored: exactly those with ahab.

On the novels, with BM25 and a real, rising threshold, the savings are large. For white whale, WAND scores two hundred and thirty-five of the sixteen hundred and ten passages that contain a term. For the sea, about a tenth: the word the is everywhere, but its bound is tiny. Pride prejudice saves least: both words are rare, their bounds high, and nearly half the candidates must be checked. In every query the top ten is identical to exhaustive scoring, score for score. WAND is safe: it never trades accuracy for speed.

8Links and the random surferDegree4 min

Words say what a page is about, not whether it is any good. Sergey Brin and Larry Page, in 1998, read the links between pages as votes: a page is important if important pages link to it, and each page splits its vote among its links. The definition is circular, and a story resolves it. A surfer clicks a random link on every page, and now and then, bored, jumps to a random page. The fraction of time the surfer spends on each page, in the long run, is its PageRank. Brin and Page also indexed the text of each link as words describing its target.

Write it down. With probability d the surfer follows a link; otherwise it teleports anywhere. So a page's rank is the teleport share, one minus d over the number of pages, plus d times the rank flowing in, each page giving an equal part of its rank to each of its links. Brin and Page suggested a d of zero point eight five. A page with no links passes its rank to everyone. In matrix form, the rank vector is the eigenvector of the Google matrix with eigenvalue one: the stationary distribution of a Markov chain, as in Part 18. Teleporting connects every page to every other, so by the Perron–Frobenius theorem that vector exists and is unique.

To compute it, start from the uniform vector and multiply by the matrix, again and again. Our synthetic web has four hundred pages, each linking to up to four earlier ones, chosen in proportion to the links they already have, plus a farm of twenty. At each step the change shrinks by at least a factor d, and here faster: to one part in a million after forty steps. The bound does not depend on the number of pages, so a web of billions also needs only a few dozen passes. The top pages are the oldest, which preferential attachment made into hubs.

Jon Kleinberg, at the same time, read links differently. Authorities are pages linked to by good hubs; hubs are pages that link to good authorities. Each score is the sum of the other kind over the links. Iterate and normalise, and the two vectors converge to the leading eigenvectors of A transpose A and A A transpose, the singular vectors of the link matrix. Kleinberg ran it on the neighbourhood of a query's results. On our web it is easily led. The top authority is the farm's target, the top hub is a farm page, and all twenty farm pages are among the twenty best hubs.

That farm is link spam: twenty pages linking to one target and to one another. Without it, the target, the newest page of our web, ranks three hundred and forty-sixth of four hundred. With it, a hundred and fourteenth of four hundred and twenty: each farm page collects its teleport share and passes most of it on. Defences followed. In 2005 the major search engines agreed on a nofollow attribute, for links a site does not vouch for, such as those in comments. TrustRank, from Gyöngyi, Garcia-Molina and Pedersen in 2004, teleports only to pages people have checked. Today links are one signal among many, combined by learned rankers, as chapter twelve will show.

9Crawling the webIndustry3 min

Before anything can be indexed, it must be fetched. A crawler starts from seed addresses in a frontier. It takes one, looks up the host, checks the site's robots dot t x t, downloads the page and parses it. Each link found is normalised, so that one page has one address, and tested against the addresses already seen, a hash set of fingerprints as in Part 17. New ones join the frontier. The text is fingerprinted too, so copies are not indexed twice. Heydon and Najork's Mercator set this design out in 1999. Crawlers must also escape traps, like a calendar linking to the next day, forever.

The frontier decides what to fetch next, and it serves two masters. Priority: important and fast-changing pages first, held in Mercator's front queues. And politeness: never hammer one server. Back queues hold one host each, and a heap records when each host may next be contacted. A common rule, in Manning, Raghavan and Schütze's textbook, waits about ten times as long as the last fetch from that host took. Sites also state their wishes. Martijn Koster's robots exclusion convention of 1994 lists paths a crawler should leave alone; in 2022 it became an internet standard, RFC nine three oh nine. A polite crawler fetches from thousands of hosts at once, and from each one slowly.

Much of the web is copied: mirrors, syndicated articles, pages that differ only in an advertisement. Moses Charikar's SimHash, of 2002, makes a fingerprint that changes a little when the text does. Cut the text into overlapping three-word shingles, and hash each one to sixty-four bits. For each bit position, add one for every shingle with a one there, and subtract one for every zero. The fingerprint keeps the signs. A small edit changes a few shingles, which rarely flips a sign. It is Part 20's random-hyperplane sketch: each bit says on which side of a random hyperplane the document's vector of shingles lies.

How well does it work on the novels? We fingerprinted two hundred passages and replaced words at random. One replaced word moves two point four bits on average; eighty words, a fifth of the passage, about twenty. Unrelated passages differ in about thirty-two bits, half of sixty-four, and the closest unrelated pair in twenty-two. Manku, Jain and Das Sarma, at Google in 2007, found three bits a good threshold for eight billion pages. To search quickly, cut the fingerprints into four blocks of sixteen bits. Three differing bits spoil at most three blocks, so one block agrees exactly, and an exact lookup per block, in four sorted tables, finds every candidate.

10Serving at scaleIndustry3 min

One machine cannot hold the web's index, or answer the world's queries, so the index must be cut into pieces. Picture it as a matrix: a row for each term, a column for each passage, a dot for each posting. Ours has 40,692 rows and 11,261 columns, and it is almost empty. Cut it by columns and each shard is a complete little index for a slice of the passages: document partitioning. Cut it by rows and each server holds the whole postings list of some terms: term partitioning. The matrix is the same; what differs is the work a query causes.

Follow the query whale sea through each layout. With documents partitioned, the broker sends the whole query to every shard. Each computes its own top ten over its quarter of the passages, and the broker merges four short lists. The scores need collection-wide statistics, such as idf, shared among the shards. With terms partitioned, only the two servers holding those terms work, but one must ship its entire list, 390 postings, to the other, which intersects them and finds 231 passages. Web engines chose documents: Google's cluster, described by Barroso, Dean and Hoelzle in 2003, cut its index into shards of documents.

Document partitioning has a price, which Part 39 called the tail at scale. A query waits for its slowest shard. Suppose, as Dean and Barroso did in 2013, that each server is slow on one request in a hundred. A query that touches one server is slow one time in a hundred; a query that must wait for a hundred servers is slow sixty-three times in a hundred. One remedy is the hedged request: after a short delay, send a second copy to another replica and keep whichever answers first. In their test it cut the ninety-nine point nine percentile from one thousand eight hundred milliseconds to seventy-four, for two percent more requests. Another is to answer without the stragglers.

The cheapest query is one you have already answered. Queries are skewed the way words are: as Chapter 1 found for the novels, a few are enormously common and most are rare, so a small head of popular queries recurs all day. A result cache in front of the broker stores whole answer pages for that head. A hit goes straight back without touching a shard. Entries must expire, because the index keeps changing underneath them. A miss takes the full path, and that is where the tail lives. Inside each shard a second cache keeps the postings of popular terms in memory. Baeza-Yates and colleagues showed in 2007 that the best terms to keep are those queries use often relative to the length of their lists.

11Spelling and autocompleteGraduate4 min

A user types c a p t i a n. What did they mean? Model the error as a message sent through a noisy channel: the intended word goes in, the fingers garble it, and a typo comes out. Here two letters were swapped. To decode, pick the word maximizing its prior probability times the probability that the channel turned it into this typo. The prior is a language model; ours is simply each word's count in the novels. The channel model says which slips are likely; ours charges a fixed penalty per edit. Kernighan, Church and Gale learned it instead, from real typing errors, in 1990. It is Bayes' rule.

The channel needs a distance between a typo and a word. It is the edit distance of Part 21: the fewest insertions, deletions and substitutions turning one string into the other. Lay one word across the top and the other down the side. Each cell is the cheapest of its three neighbours plus one, or its diagonal neighbour for free when the letters agree. That is the dynamic programming of Part 19, filled row by row. The corner says 2: a single swap of neighbouring letters costs two substitutions. Damerau observed in 1964 that transposing two neighbours is among the commonest slips, and counted it as one edit.

Comparing a typo with every word in the vocabulary is wasteful. Burkhard and Keller's tree of 1973 does better. Each word hangs below its parent on an edge labelled with the edit distance between them. To find words within one edit of a typo, compute its distance d to the root. Because edit distance is a metric, the triangle inequality says that a match can only lie under the edges labelled d minus one to d plus one, and every other subtree is skipped unvisited. On the novels' vocabulary, at a tolerance of two, our tree still computes about a third of all the distances: pruning is weak when the tolerance is large compared with the words themselves.

Here is the whole corrector on seven inputs, with a vocabulary of 31,190 words from the novels. Misspelt captain, Elizabeth, separate, monster and London are all repaired. Whale is already a word: it has 76 neighbours within two edits, but none is common enough to pay for the change, so it stays. And one is wrong. Recieve becomes relieve, because relieve is one substitution away while receive, under plain edit distance, is two. Damerau's transposition, or a channel learned from real slips, would put it right. Real correctors also read the surrounding words, and learn from query logs what people retyped next.

Better still is to catch the query before it is finished. Autocompletion is a walk down a trie, the tree of prefixes from Part 17. Type c, a, and every word below that node is a candidate. The best five, ranked by their counts in the novels, are can, came, called, cannot and can't. To find them without visiting the whole subtree, store at every node the best count anywhere beneath it. A priority queue then always expands the most promising node, and the top k come out after about k times the depth steps, however big the vocabulary. Or store the top few at each node outright, buying speed with memory. Real engines rank completions by what people search for.

12Learning to rankIndustry3 min

BM25 is one signal. A web engine has hundreds. For each query and passage it computes a vector of features: BM25 and tf-idf, whether the phrase occurs, how close the terms sit, the length, and on the web PageRank and the clicks of past users. Hand-tuning a formula that weighs a hundred of these is hopeless, so a model learns it from graded queries, like our 9 from Chapter 6, but thousands of them, graded by people. Microsoft's public MSLR data set describes each query and page by a hundred and thirty-six features. The model outputs a score to sort by. The real question is what loss to train it on.

There are three families of loss. Pointwise methods predict each passage's grade by regression, one at a time. But the user only ever sees an order, and grades are not comparable across queries. Pairwise methods look at pairs: whenever one passage is better than another, it should score higher. Burges and colleagues' RankNet, in 2005, used a logistic loss on the difference of the two scores. But it counts every misordered pair the same, whether at the top of the page or far below it. Listwise methods judge the whole list by the measure we care about, such as nDCG. But nDCG only changes when two scores cross, so it has no useful gradient.

Burges and colleagues found a way round that in 2006. Take six graded passages, in the model's current order. RankNet's gradient pushes each passage up for every worse passage above it, and down for every better one below, by an amount that depends only on the two scores. LambdaRank multiplies each pair's push by how much nDCG would change if the two swapped places. Pairs near the top now dominate, and pairs low on the page barely count. The trick is to never write a loss down at all: define the gradient you want, the lambdas, and follow it. Passage C, the best, gets the strongest push.

Judged queries are expensive; clicks are free, but biased. People mostly look at the top of the page, so a click depends on where a result was shown as well as on whether it was relevant. Joachims and colleagues showed this in 2005 with eye tracking: when the top two results were secretly swapped, users still clicked the first more often. In the cascade model of Craswell and colleagues, the user reads down the page and clicks the first result that looks right. To learn from clicks without learning the old ranking back, weight each click by one over the chance its position was looked at, measured by randomly swapping results: unbiased learning to rank.

13Dense retrievalGraduate4 min

Everything so far matches words. A query about a voyage on the ocean scores zero against a passage about a ship at sea, because they share no terms. Dense retrieval moves the problem into geometry. An encoder, the embeddings of AI, Built Part 24, maps every passage to a vector, once, offline, and the query at query time; relevance is a dot product. Related passages land near each other, and retrieval becomes nearest-neighbour search. Our own vectors are a stand-in: tf-idf projected down to 64 dimensions by a random matrix, the trick of Part 20. They keep the geometry of words, not of meaning; a trained encoder, like the dense passage retriever of Karpukhin and colleagues in 2020, learns meaning from examples.

A float vector per passage costs 256 bytes; a billion passages would need hundreds of gigabytes. Jegou, Douze and Schmid's product quantization, of 2011, shrinks it. Cut each vector into 8 pieces of 8 dimensions. In each piece's space, cluster all passages into two hundred and fifty-six groups, and store only the number of the nearest centre: one byte. The vector becomes 8 bytes. Two hundred and fifty-six choices in each of eight places give an astronomical number of codes, from very few centres. Searching needs no decompression: compute the query's distance to every centre once, and each passage's distance is a sum of eight table lookups.

How much does compression cost? We measured it on 64-dimensional passage vectors with a hundred queries. With two bytes per passage, PQ finds 7 percent of the true ten nearest; with eight bytes 31 percent; with sixteen, 54, at a sixteenth of the 256 bytes of the exact vector. The squared error falls from 0.66 to 0.08 of a unit vector. So real systems use the codes only for a shortlist: an inverted file picks a few clusters to scan, the codes rank their contents, and the best are re-scored exactly, as in the Faiss library.

Even compressed, a full scan is too slow at web scale. Malkov and Yashunin's hierarchical navigable small world graph avoids it. Each point is given a random level, and the levels thin out geometrically: in our graph of 3,000 passage vectors, 2,621 live only on the bottom, and just 4 reach level 3. Each level links near neighbours, like a skip list's express lanes. A search enters at the top, walks greedily towards the query with long hops, drops a level, and repeats with shorter hops, until a beam search on the bottom level collects the nearest. A wider beam buys recall: with a beam of 40, 81 percent of the true top ten for 467 distance computations, about a sixth of brute force.

In practice both kinds run side by side. BM25 gives one ranking, the dense retriever another, and their scores are on unrelated scales. Reciprocal rank fusion, from Cormack, Clarke and Buettcher in 2009, ignores the scores: each list gives a passage one over sixty plus its rank, and the sums decide. Passages both lists like rise to the top. Words catch names and rare terms; vectors catch paraphrase. And on collections the encoder never saw, the BEIR benchmark of 2021 found BM25 often still hard to beat. Increasingly the reader of the top passages is a language model, as in the retrieval-augmented generation of AI, Built Part 15.

14A search engine for the novelsIndustry2 min

Here is our engine, end to end. A query arrives: the hound on the moor. It is tokenized exactly as the passages were, stop words are dropped, and the rest are stemmed, so that it matches the index's terms. The engine fetches the postings of each term. It scores the candidates with BM25, letting WAND skip those that cannot reach the top ten. And it returns the ten best passages, each with a snippet cut around the first word that matched.

Four queries and their best answers. The white whale, and call me Ishmael, both go to Moby-Dick, to passages where those words cluster. Pride and prejudice goes to Jane Austen's novel, and the hound on the moor to The Hound of the Baskervilles. Nothing here knows what the books are about. The ranking comes entirely from which words are rare, where they occur, and how long the passages are.

How big is it? Our index holds 2.4 million postings. Stored as plain thirty-two-bit integers, the document ids alone take about 9.5 megabytes. As gaps in Golomb–Rice code, about 1.5, five bits a posting. And no code can do much better: choosing which f of N documents contain a term carries log of N choose f bits of information, which comes to 4.74 bits a posting here. Golomb–Rice is within a few percent of that limit, unless a code can exploit how postings cluster.

And what a web search engine adds. Hundreds of billions of pages instead of eleven thousand passages, crawled again and again; hundreds of languages, with synonyms and entities; hundreds of ranking signals combined by learned models; link authority and defences against spam; thousands of machines; and news that must be searchable minutes after it is published. But the core is the same. Lucene, the open-source library under Elasticsearch, OpenSearch and Solr, ranks with BM25 by default, over compressed inverted lists like ours.

15Frontier: retrieval and its limitsResearch2 min

What should a search engine return, now that machines can write the answer? Vector search is where theory lags furthest behind practice. Our own layered graph finds 68 percent of the true ten nearest passages with about 191 distance computations, and 95 percent with about 1232, against 3,000 for brute force. Graph indexes like this win the benchmarks, but they carry no worst-case guarantee: on adversarial data the greedy walk can stall far from the answer. Locality-sensitive hashing has guarantees but loses in practice, and recent theory is only beginning to explain when navigable graphs work. Closing that gap is open.

Finally, search is changing what it is for. In retrieval-augmented generation, from AI, Built, an engine like ours finds passages and a language model writes an answer from them, with citations. The engine becomes a model's memory, and the user may never see a ranked list at all. Generative retrieval goes further: the model memorizes the collection and emits the identifiers of relevant documents itself, which makes updating the index the hard part. How to evaluate a written answer rather than a ranked list, how to check that it is faithful to its sources, and how to keep a model's memory as fresh as an index, are open.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. Zipf's and Heaps' laws, fitted on the novels. An inverted index, and three ways to intersect its lists, from a linear merge to galloping search. Gap codes whose lengths we derived, which shrink a posting from thirty-two bits to about five. BM25, from the probability ranking principle, measured with nDCG; WAND, which finds the same top ten while fully scoring a fraction of the candidates; PageRank as the stationary distribution of a random surfer; SimHash for near-duplicates; and vectors compressed by product quantization and searched through a layered graph. One idea runs through it: a good index does almost all of the work before the query arrives.

Where this comes back. Parts 48 and 49 design a search service: how to shard it, cache it and keep it fresh. Part 50 keeps a serving system like it healthy. Part 56 returns to the eigenvectors behind PageRank with spectral graph theory. Part 57 asks when a learned ranker will generalize. And Part 60 looks at the hardware built for vector search and inference.

In practice. Normalize text the way your users type it, stem with care, and keep the original words for phrase queries. Store postings sorted and compressed in blocks, with skip data and score bounds. Treat BM25 as the baseline to beat, and tune it on judged queries. Keep a set of judged queries, measure nDCG, and test significance before shipping a ranking change. And combine lexical and dense retrieval, measuring how much the approximate vector search misses.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give our engine block-max WAND, with a score bound for every block of postings, and measure how much more it skips. The last, marked with a star, is a research problem: a graph index for nearest neighbours with guarantees on recall and speed for the kind of data people actually search.

Next time, Part 48: system design, and its building blocks. The numbers every designer should carry, load balancers and caches and the arithmetic of their hit rates, sharding and replication, rate limiters and queues, and how to put them together into the shape of a design.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Parts 48 and 49 design a search service: how to shard it, cache it and keep it fresh. Part 50 keeps a serving system like it healthy. Part 56 returns to the eigenvectors behind PageRank with spectral graph theory, Part 57 asks when a learned ranker will generalize, and Part 60 looks at the hardware built for vector search and inference.

Key results

The part's results in one place, for revision.

Zipf and Heaps\(\displaystyle f(r)\propto r^{-s},\qquad\allowbreak V(n)=K\,n^{\beta}\quad\allowbreak (s\approx 1.21,\ \beta\approx 0.485\text{ on }\allowbreak \text{the }\allowbreak \text{novels})\)
Gap codes\(\displaystyle |\gamma(g)|=2\lfloor\log_2 g\rfloor+1,\qquad\allowbreak M_{\text{Golomb}}\approx 0.69\,\tfrac{N}{f}\)
BM25\(\displaystyle \sum_{t\in q}\operatorname{idf}_t\,\frac{tf_t\,(k_1+1)}{tf_t+k_1\bigl(1-b+b\,\ell_d/\bar\ell\bigr)}\)
nDCG\(\displaystyle \mathrm{DCG}_k=\sum_{i=1}^{k}\frac{2^{g_i}-1}{\log_2(i+1)},\qquad\allowbreak \mathrm{nDCG}_k=\frac{\mathrm{DCG}_k}{\mathrm{IDCG}_k}\)
PageRank\(\displaystyle r=\frac{1-d}{N}\mathbf{1}+d\,P\,r,\qquad\allowbreak d=0.85\)
Freshness\(\displaystyle \text{fresh }\allowbreak \text{fraction}=\frac{1-e^{-\lambda I}}{\lambda I}\)

Try it

Lab 47 · Postings merged, compressed and pruned; PageRank as an eigenvector

Build the series' inverted index over 2,000 synthetic documents with Zipfian words, then check three claims: galloping beats the merge when list lengths differ, Rice codes come within a few percent of the bound log2 C(N, f), and WAND returns exactly the exhaustive BM25 top ten while scoring fewer documents; last, compare power-iteration PageRank with a direct linear solve.

Figure produced by Lab 47: Postings merged, compressed and pruned; PageRank as an eigenvector
Produced by the lab below, seed 0, in 0.7 s.
python -m videos.cs.labs 47 needs numpy, scipy, matplotlib · download lab47.py · source on GitHub
index                               2,000 documents, 3,000 terms, 193,651 postings
pairs with a length ratio above 30  27; merge / galloping comparisons, median 4.4x
bits per posting                    32-bit 32, variable byte 8.47, gamma 6.20, delta 6.16, Rice 4.79; bound 4.58
WAND on 25 queries                  top ten identical to exhaustive BM25; 35% of candidates scored on average
PageRank                            power iteration equals the linear solve to 1e-13 after 99 steps; the farm lifts its target from rank 261 to 101

Sorted lists make a query a merge, gaps between sorted ids are small numbers that a Rice code stores near the counting bound, and score upper bounds let WAND skip most documents without changing the top ten.
The code (141 lines; it asserts its own result)
"""Lab 47: index a synthetic Zipfian corpus, intersect and compress its postings, and check WAND and PageRank against exhaustive answers."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import math

import numpy as np

from explainer.cs.search import index as ix
from explainer.cs.search import links as lk
from explainer.cs.search import rank as rk

TITLE = "Postings merged, compressed and pruned; PageRank as an eigenvector"
GOAL = ("Build the series' inverted index over 2,000 synthetic documents with Zipfian words, then check three "
        "claims: galloping beats the merge when list lengths differ, Rice codes come within a few percent of the "
        "bound log2 C(N, f), and WAND returns exactly the exhaustive BM25 top ten while scoring fewer documents; "
        "last, compare power-iteration PageRank with a direct linear solve.")
TASKS = [
    "Fix every Rice parameter at k = 0 (a unary code) or k = 8 in rice_total and compare the bits per posting with the per-list rule k = floor(log2(0.69 N / f)).",
    "Ask WAND for the top 1 and the top 100 instead of the top 10. How does the share of candidates it scores move, and why?",
    "Change the damping d from 0.85 to 0.5 and to 0.99 in lk.pagerank and count the iterations until the change is below 1e-10. Compare the count with log(1e-10) / log(d).",
]

N_DOCS, VOCAB, DOC_LEN = 2000, 3000, 150


def word(i):
    """A made-up word for rank i, letters only: 0 -> 'baa', 1 -> 'bab', ..."""
    s = ""
    for _ in range(3):
        s = "abcdefghijklmnopqrstuvwxyz"[i % 26] + s
        i //= 26
    return "b" + s


def corpus(rng):
    p = 1 / np.arange(1, VOCAB + 1)
    ranks = rng.choice(VOCAB, size=(N_DOCS, DOC_LEN), p=p / p.sum())
    return [(d, "synthetic", " ".join(word(int(r)) for r in row)) for d, row in enumerate(ranks)]


def rice_total(post):
    """(bits used by Rice codes with the per-list rule, the bound sum of log2 C(N, f)), over every postings list."""
    bits = bound = 0.0
    for ps in post.values():
        ids = [d for d, _ in ps]
        gaps = [ids[0] + 1] + [b - a for a, b in zip(ids, ids[1:])]
        k = max(0, int(math.log2(max(1.0, 0.69 * N_DOCS / len(gaps)))))
        bits += sum(ix.rice_bits(g, k) for g in gaps)
        bound += math.log2(math.comb(N_DOCS, len(gaps)))
    return bits, bound


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    post, lengths = ix.build(corpus(rng), stem=False)
    by_df = sorted(post, key=lambda t: -len(post[t]))
    lab.row("index", f"{N_DOCS:,} documents, {len(post):,} terms, {sum(len(v) for v in post.values()):,} postings")

    # 1. intersection: the three algorithms agree; galloping wins when the lists differ in length
    ratios, c_merge, c_gallop = [], [], []
    for _ in range(60):
        a = ix.docs_of(post, by_df[int(rng.integers(0, 40))])
        b = ix.docs_of(post, by_df[int(rng.integers(0, 1500))])
        (m, cm), (s, _), (g, cg) = ix.merge(a, b), ix.skips(a, b), ix.gallop(a, b)
        assert m == s == g == sorted(set(a) & set(b)), "three ways to intersect, one answer"
        assert cm <= len(a) + len(b), "the merge makes at most m + n comparisons"
        ratios.append(max(len(a), len(b)) / min(len(a), len(b)))
        c_merge.append(cm)
        c_gallop.append(cg)
    ratios, c_merge, c_gallop = map(np.array, (ratios, c_merge, c_gallop))
    lopsided = ratios > 30
    assert lopsided.sum() >= 5 and np.all(c_gallop[lopsided] < c_merge[lopsided]), "galloping wins on lopsided lists"
    lab.row("pairs with a length ratio above 30", f"{int(lopsided.sum())}; merge / galloping comparisons, median "
                                                  f"{np.median(c_merge[lopsided] / c_gallop[lopsided]):.1f}x")

    # 2. compression: gaps under four codes, against the bound log2 C(N, f)
    comp = ix.compress(post, N_DOCS)
    bpp = comp["bits_per_posting"]
    bits, bound = rice_total(post)
    assert abs(bits - comp["bits"]["rice"]) < 1e-6, "the same total as the library's"
    assert bound <= bits <= 1.1 * bound, "Rice with k from the mean gap is within 10% of the bound"
    assert bpp["rice"] < bpp["delta"] < bpp["vbyte"] < 32 and bpp["rice"] < bpp["gamma"]
    for g in (1, 2, 9, 1000):
        assert len(ix.gamma_code(g)) == ix.gamma_bits(g) == 2 * int(math.log2(g)) + 1
    lab.row("bits per posting", f"32-bit 32, variable byte {bpp['vbyte']:.2f}, gamma {bpp['gamma']:.2f}, delta "
                                f"{bpp['delta']:.2f}, Rice {bpp['rice']:.2f}; bound {bound / comp['postings']:.2f}")

    # 3. WAND: the exhaustive top ten, for fewer documents scored
    shares = []
    for _ in range(25):
        query = [by_df[int(i)] for i in rng.integers(5, 400, int(rng.integers(2, 4)))]
        scores = rk.bm25_scores(post, lengths, query)
        best = sorted(scores.values(), reverse=True)[:10]
        w = rk.wand(post, lengths, query, k=10)
        assert np.allclose(sorted((scores[d] for d in w["top"]), reverse=True), best, atol=1e-9), "WAND is safe"
        assert w["scored"] <= w["candidates"] == len(scores)
        shares.append(w["scored"] / w["candidates"])
    assert np.mean(shares) < 0.9, "and it skips documents"
    lab.row("WAND on 25 queries", f"top ten identical to exhaustive BM25; {np.mean(shares):.0%} of candidates scored on average")

    # 4. PageRank: power iteration against the linear system (I - d P) r = (1 - d) / N
    out, n, target, farm = lk.synthetic_web(n=300, farm=15, seed=seed)
    r, hist = lk.pagerank(out, n)
    P = np.zeros((n, n))
    for v in range(n):
        if out.get(v):
            P[out[v], v] = 1 / len(out[v])
        else:
            P[:, v] = 1 / n
    direct = np.linalg.solve(np.eye(n) - 0.85 * P, np.full(n, 0.15 / n))
    assert abs(r.sum() - 1) < 1e-9 and np.abs(r - direct).max() < 1e-9, "the stationary distribution"
    assert all(b <= 0.85 * a + 1e-15 for a, b in zip(hist, hist[1:])), "each step shrinks the change by at least d"
    no_farm = lk.pagerank({v: us for v, us in out.items() if v not in farm}, n - len(farm))[0]
    rank_with, rank_without = int((r > r[target]).sum()) + 1, int((no_farm > no_farm[target]).sum()) + 1
    assert rank_with < rank_without, "a link farm lifts its target"
    lab.row("PageRank", f"power iteration equals the linear solve to {np.abs(r - direct).max():.0e} after {len(hist)} "
                        f"steps; the farm lifts its target from rank {rank_without} to {rank_with}")
    lab.note = ("Sorted lists make a query a merge, gaps between sorted ids are small numbers that a Rice code "
                "stores near the counting bound, and score upper bounds let WAND skip most documents without "
                "changing the top ten.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    order = np.argsort(ratios)
    ax[0].loglog(ratios[order], c_merge[order], "o", ms=4, color=labs.RED, label="linear merge")
    ax[0].loglog(ratios[order], c_gallop[order], "o", ms=4, color=labs.GREEN, label="galloping search")
    ax[0].set(title="Comparisons to intersect two postings lists", xlabel="longer list / shorter list",
              ylabel="comparisons")
    ax[0].legend()
    names = ["variable byte", "gamma", "delta", "Rice"]
    vals = [bpp["vbyte"], bpp["gamma"], bpp["delta"], bpp["rice"]]
    ax[1].set_axisbelow(True)
    ax[1].bar(names, vals, color=[labs.GREY, labs.BLUE, labs.PURPLE, labs.GOLD])
    ax[1].axhline(bound / comp["postings"], color=labs.GREEN, ls="--", label="bound: log2 C(N, f) per posting")
    for i, v in enumerate(vals):
        ax[1].text(i, v + 0.15, f"{v:.2f}", ha="center")
    ax[1].set(title="Bits per posting (gaps between document ids)", ylabel="bits")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Fix every Rice parameter at k = 0 (a unary code) or k = 8 in rice_total and compare the bits per posting with the per-list rule k = floor(log2(0.69 N / f)).
  2. Ask WAND for the top 1 and the top 100 instead of the top 10. How does the share of candidates it scores move, and why?
  3. Change the damping d from 0.85 to 0.5 and to 0.99 in lk.pagerank and count the iterations until the change is below 1e-10. Compare the count with log(1e-10) / log(d).

Problems, with solutions

Try each problem before opening its solution.

  1. Galloping. Show that galloping intersection of lists of sizes m ≤ n takes O(m log(n/m)) comparisons, and that this is optimal up to a constant.

    Solution

    Let the short list be a₁ < … < a_m and the long one b₁ < … < b_n. Galloping keeps a position in the long list that only moves forward. For aᵢ it probes 1, 2, 4, 8, … places ahead until a probe reaches a value ≥ aᵢ or runs off the end, binary searches the last bracket, and makes one equality test. If the position advances by gᵢ places, the doubling makes at most log₂(gᵢ + 1) + 1 probes and leaves a bracket of fewer than gᵢ + 1 places, so the search for aᵢ costs at most 2 log₂(gᵢ + 1) + 3 comparisons. The gᵢ sum to at most n, and log is concave, so by Jensen Σ log₂(gᵢ + 1) ≤ m log₂(n/m + 1). The total is at most 2m log₂(n/m + 1) + 3m = O(m(1 + log(n/m))), which is O(m log(n/m)) once n ≥ 2m (for n < 2m it is O(m), the cost of reading the short list). For the lower bound, consider comparison algorithms on inputs where no aᵢ equals any b_j. When the algorithm stops, it must know for every aᵢ the gap (b_j, b_{j+1}) that holds it: if aᵢ and some b_j are incomparable in the order its outcomes imply, there is a linear extension in which they are adjacent, and making them equal changes no outcome but makes the intersection non-empty, so the algorithm is wrong on one of the two inputs. Because the aᵢ are sorted, the gaps form a non-decreasing sequence of m of the n + 1 slots, which can be chosen in C(n + m, m) ways, and each comparison (never "equal" here) has two outcomes. So some input needs at least log₂ C(n + m, m) ≥ m log₂((n + m)/m) ≥ m log₂(n/m) comparisons. On the novels, love AND marriag (500 and 2,363 postings) took 1,915 comparisons, against m log₂(n/m) ≈ 1,120, within the factor of 2 of the analysis. The AND whale took 1,418, below the worst case's log₂ C(11,647, 390) ≈ 2,459, because every whale passage contains the: the bound is for the worst input, and adaptive analyses (Demaine, López-Ortiz and Munro) measure how hard an instance is.

  2. Code lengths. Derive the lengths of Elias γ and δ codes, and the Golomb parameter that is optimal for geometric gaps.

    Solution

    A gap g ≥ 1 has L = ⌊log₂ g⌋ + 1 binary digits, the first always 1. γ writes L − 1 zeros and then the L digits; the decoder counts zeros to learn how many digits follow, so the code is prefix-free and |γ(g)| = 2⌊log₂ g⌋ + 1. For each L there are 2^(L−1) gaps of length 2L − 1, so Σ 2^(−|γ(g)|) = Σ_L 2^(−L) = 1: the code is complete, and by Kraft it is ideal for P(g) = 2^(−|γ(g)|) ≈ 1/(2g²). δ writes L in γ and then the L − 1 digits after the leading 1: |δ(g)| = ⌊log₂ g⌋ + 2⌊log₂(⌊log₂ g⌋ + 1)⌋ + 1 = log₂ g + O(log log g), so it wins for large gaps. For g = 9, γ = 0001001 (7 bits) and δ = 00100001 (8); for g = 100, 13 bits against 11. For Golomb's code, let each passage hold the term independently with p = f/N, so P(g) = (1 − p)^(g−1) p. Write g − 1 = qM + r with 0 ≤ r < M. Then P(q) = Σ_r (1 − p)^(qM+r) p = θ^q (1 − θ), with θ = (1 − p)^M: the quotient is geometric again. Unary spends q + 1 bits, which is ideal when P(q) = 2^(−(q+1)), that is when θ = ½: (1 − p)^M = ½, M = ln 2 / (−ln(1 − p)) ≈ 0.69/p = 0.69 N/f. Within a block the probability of r falls only by the factor θ = ½ from one end to the other, so a (truncated) binary remainder is nearly ideal. The exact integer optimum is M = ⌈log(2 − p) / (−log(1 − p))⌉ (Gallager and van Voorhis, 1975). For whale, p = 390/11,261: M ≈ 19.7, the integer optimum 20, and under the geometric model 6.30 bits per gap with M = 20 and 6.32 with Rice's M = 16 (k = 4), against the model's entropy of 6.27 bits. Real postings cluster, which is why the whole index's Rice codes (4.96 bits) sit a little above log₂ C(N, f) (4.74).

  3. BM25. Derive BM25's term weight from the binary independence model with a two-Poisson approximation, and explain k₁ and b.

    Solution

    Rank by the odds of relevance; by Bayes' rule and independence of terms given relevance, the log odds are, up to terms that do not depend on the passage, Σ over query terms present of w_t = log [p_t (1 − u_t)] / [u_t (1 − p_t)], where p_t and u_t are the chances that t occurs in a relevant and in an irrelevant passage. With no relevance information take p_t = ½, and since almost every passage is irrelevant u_t ≈ df/N: w_t = log((N − df)/df), with 0.5 added to each count to give the Robertson–Spärck Jones weight log((N − df + 0.5)/(df + 0.5)). It is negative for df > N/2 (for the, in 11,257 of 11,261 passages, −7.82), so Lucene and our rank.py use log(1 + (N − df + 0.5)/(df + 0.5)): 0.0004 for the, 3.36 for whale. The binary model ignores how often t occurs. Harter's two-Poisson model says a passage is either elite for t (about it) or not, with tf Poisson of mean λ in the first case and μ < λ in the second, the mixing weights depending on relevance. The weight of a count is then w(tf) = log [P(tf | R) P(0 | R̄)] / [P(tf | R̄) P(0 | R)]: it is 0 at tf = 0, rises with tf, and as tf grows the elite component dominates both mixtures, so w tends to a limit, the weight of eliteness itself, which plays the part of the binary model's weight. The model's four parameters cannot be estimated without relevance data, so Robertson and Walker kept only that shape: w(tf) ≈ w_t · tf/(tf + k₁), scaled by k₁ + 1 so that a single occurrence scores exactly w_t (a common factor, so the ranking is unchanged): tf(k₁ + 1)/(tf + k₁). k₁ sets how fast the count saturates: k₁ → 0 gives the binary model, k₁ → ∞ raw counts; with k₁ = 1.2 the factor is 1, 1.375, 1.774 and 1.964 at tf = 1, 2, 5 and 10, tending to 2.2. For length, a long passage has more occurrences because it is long (the verbosity hypothesis), so measure tf against the passage's relative length B = 1 − b + b|d|/avgdl: (tf/B)(k₁ + 1)/(tf/B + k₁) = tf(k₁ + 1)/(tf + k₁B). b = 0 ignores length (long passages cover more topics, the scope hypothesis); b = 1 normalises fully. With b = 0.75, a passage twice the average length has K = k₁B = 2.1 and scores 0.71 for one occurrence and 1.07 for two; one half the average, K = 0.75 and 1.26 for one. Our passages are all about 400 words, so b changes little here.

  4. PageRank. Show that PageRank is the stationary distribution of a Markov chain, and that power iteration converges at rate d.

    Solution

    Let M be the N × N matrix with M_pq = 1/L(q) when q links to p (L(q) its number of links) and M_pq = 1/N for every p when q has no links; each column sums to 1. Let G = dM + (1 − d)/N · 𝟏𝟏ᵀ. G_pq is the chance that a surfer on q moves to p next (with probability d follow a random link, otherwise jump to a page chosen uniformly), its columns sum to d + (1 − d) = 1, and (Gr)p = (1 − d)/N + d Σ{q→p} r_q/L(q) (with dangling pages' rank spread evenly), which is the PageRank equation. So a vector r ≥ 0 with Σr = 1 and r = Gr is exactly a stationary distribution of that chain. Every entry of G is at least (1 − d)/N > 0, so the chain is irreducible and aperiodic, and by Perron–Frobenius the eigenvalue 1 is simple with a positive eigenvector: r exists and is unique. For convergence take any z with Σz = 0 (the difference of two probability vectors): 𝟏ᵀz = 0, so Gz = dMz, and since M has non-negative entries and columns summing to 1, ‖Mz‖₁ ≤ Σ_q |z_q| Σ_p M_pq = ‖z‖₁. Hence ‖Gz‖₁ ≤ d‖z‖₁, and the iterates r_k = G^k r₀ satisfy ‖r_k − r‖₁ ≤ d^k ‖r₀ − r‖₁ ≤ 2d^k, and successive changes shrink by at least d: ‖r_{k+1} − r_k‖₁ ≤ d^k ‖r₁ − r₀‖₁. (Equivalently, every other eigenvalue of G has modulus at most d; Haveliwala and Kamvar, 2003.) The bound does not depend on N: getting below 10⁻⁶ from at most 2 takes log(2 × 10⁶)/log(1/0.85) ≈ 89 steps for any web. On our synthetic web the change was 1.04 after the first step; the bound allows 1.04 × 0.85³⁹ ≈ 1.8 × 10⁻³ after forty, and we measured 1.1 × 10⁻⁶, shrinking by about 0.81 a step near the end.

  5. Build. Add block-max WAND to our engine (score bounds per block of postings) and measure how many more documents it skips.

    Solution

    Solution notes. In rank.wand each term's list is already a list of (passage, contribution) pairs with one bound ub[i], its largest contribution. In the same pass, cut each list into blocks of B postings (say 64) and store, for each block, its last passage and its largest contribution; give each cursor a block pointer as well. Pick the pivot exactly as now, with the global bounds. Then make the shallow check: for every cursor whose current passage is no later than the pivot's, move only its block pointer to the block that would contain the pivot's passage (no postings are read), and add those blocks' maxima. If the sum exceeds θ, continue as WAND does: score the pivot if every such cursor is on it, else advance them to it. If not, no passage up to the end of the shortest of those blocks can reach θ: move those cursors to the smaller of (the earliest block end + 1) and the current passage of the first other cursor, without scoring anything. Count fully scored passages as scored does, and count block checks separately. Check safety exactly as test_wand_matches_exhaustive does, against top(bm25_scores(...)), on the toy documents and on the five queries of compute_wand, score for score. Then report, for block sizes 32, 64 and 128, the passages fully scored by WAND (235, 117, 1,144, 359 and 213 for the five queries) and by block-max WAND. Our passages all have about 400 words, so a term's contributions vary mainly with tf; expect the largest gains for long lists whose maximum is set by a few passages with a high count, and little for pride prejudice, whose terms are rare. Our cursors advance one posting at a time, so to turn skipped passages into saved time the cursor moves should also use the skip pointers or galloping of Chapter 3.

  6. ★ Research. Find a graph-based nearest-neighbour index with provable recall and query time on realistic data.

    Discussion. Open. Graph indexes such as HNSW win the benchmarks (ours finds 81% of the true top ten for 467 of 3,000 distances), but their guarantees are heuristic: on adversarial inputs the greedy walk can stall far from the answer, and Indyk and Xu (NeurIPS 2023) built instances on which HNSW and other popular graphs need time linear in n, while proving bounds for one slowly built variant of DiskANN's graph on data of bounded doubling dimension. Structures with guarantees in doubling dimension, such as navigating nets (Krauthgamer and Lee, 2004) and cover trees (Beygelzimer, Kakade and Langford, 2006), and locality-sensitive hashing in high dimension (Part 20), lose in practice, and doubling dimension is a worst-case measure that may be large for real embeddings. A good answer would fix a model of realistic data (low intrinsic dimension in some measured sense, or a generative model of embeddings), give a graph built in near-linear time with degree and query time polylogarithmic in n (exponential only in the intrinsic dimension), prove recall at least 1 − δ for beam search on it, and show on real vectors that the model's assumptions hold. Partial results for a single beam width, for random data on a sphere, or a lower bound showing what no sparse graph can achieve, would already be new.

Notes and sources

Glossary

  • token, case folding, stop word, stem, lemmatizer — the units a search engine indexes, and how words are normalised into terms.
  • Zipf's law, Heaps' law, hapax legomenon — frequency against rank; vocabulary against text read; a word seen once.
  • inverted index, dictionary, postings, document frequency (df) — from each term to the sorted passages that contain it.
  • blocked sort-based indexing, single-pass in-memory indexing, segment — building an index larger than memory; an immutable piece of an index that changes.
  • skip pointer, galloping (exponential) search, positional index, phrase query — faster intersection; positions for adjacent words.
  • gap, variable-byte code, Elias γ and δ codes, Golomb and Rice codes, PForDelta — postings stored as small numbers in short codes.
  • tf-idf, vector space model, cosine similarity — weighting terms and ranking by angle.
  • probability ranking principle, binary independence model, two-Poisson model, BM25, k₁, b — ranking by the probability of relevance; its estimate from words; saturation and length normalisation.
  • precision, recall, average precision, MAP, DCG, nDCG, test collection, pooling, sign test — measuring a ranking against judgments.
  • dynamic pruning, max-score, WAND, pivot, block-max WAND, safe and unsafe, tiered index, champion list — finding the top k without scoring every candidate.
  • PageRank, damping factor, teleportation, Google matrix, power iteration, HITS, hub, authority, link farm, TrustRank — ranking pages by links, and gaming it.
  • crawler, frontier, politeness, robots.txt, freshness, URL normalisation, shingle, SimHash, near-duplicate — fetching the web, keeping it fresh, and recognising copies.
  • document- and term-partitioned index, broker, shard, replica, fan-out, hedged request, result cache, postings cache — serving one query from many machines.
  • noisy channel, edit distance (Levenshtein, Damerau), BK-tree, trie, autocompletion — guessing what the user meant to type.
  • learning to rank, pointwise, pairwise, listwise, RankNet, LambdaRank, LambdaMART, position bias, cascade model, inverse propensity weighting — learning a ranking function from judgments and clicks.
  • dense retrieval, embedding, product quantization, codebook, asymmetric distance, inverted file, HNSW, beam width, recall@10 — searching by nearness of vectors, compressed and approximate.
  • hybrid retrieval, reciprocal rank fusion, learned sparse retrieval, late interaction, retrieval-augmented generation, generative retrieval — combining words and vectors, and retrieval for language models.

Sources

  • C. D. Manning, P. Raghavan and H. Schütze, Introduction to Information Retrieval (2008); S. Büttcher, C. L. A. Clarke and G. V. Cormack, Information Retrieval: Implementing and Evaluating Search Engines (2010); I. H. Witten, A. Moffat and T. C. Bell, Managing Gigabytes (2nd ed., 1999).
  • M. F. Porter, "An algorithm for suffix stripping", Program 1980; G. K. Zipf, Human Behavior and the Principle of Least Effort (1949); H. S. Heaps, Information Retrieval: Computational and Theoretical Aspects (1978).
  • J. Zobel and A. Moffat, "Inverted files for text search engines", ACM Computing Surveys 2006; S. Heinz and J. Zobel, "Efficient single-pass index construction for text databases", JASIST 2003; A. Moffat and J. Zobel, "Self-indexing inverted files for fast text retrieval", ACM TOIS 1996; J. Bentley and A. Yao, "An almost optimal algorithm for unbounded searching", Information Processing Letters 1976; E. Demaine, A. López-Ortiz and J. I. Munro, "Adaptive set intersections, unions, and differences", SODA 2000.
  • P. Elias, "Universal codeword sets and representations of the integers", IEEE Trans. Inf. Theory 1975; S. Golomb, "Run-length encodings", IEEE Trans. Inf. Theory 1966; R. Gallager and D. van Voorhis, "Optimal source codes for geometrically distributed integer alphabets", IEEE Trans. Inf. Theory 1975; M. Zukowski, S. Héman, N. Nes and P. Boncz, "Super-scalar RAM-CPU cache compression", ICDE 2006; D. Lemire and L. Boytsov, "Decoding billions of integers per second through vectorization", Software: Practice and Experience 2015.
  • K. Spärck Jones, "A statistical interpretation of term specificity and its application in retrieval", Journal of Documentation 1972; S. Robertson and K. Spärck Jones, "Relevance weighting of search terms", JASIS 1976; S. Robertson, "The probability ranking principle in IR", Journal of Documentation 1977; S. Harter, "A probabilistic approach to automatic keyword indexing", JASIS 1975; S. Robertson and S. Walker, "Some simple effective approximations to the 2-Poisson model for probabilistic weighted retrieval", SIGIR 1994; S. Robertson and H. Zaragoza, "The probabilistic relevance framework: BM25 and beyond", Foundations and Trends in Information Retrieval 2009.
  • K. Järvelin and J. Kekäläinen, "Cumulated gain-based evaluation of IR techniques", ACM TOIS 2002; J. Zobel, "How reliable are the results of large-scale information retrieval experiments?", SIGIR 1998.
  • H. Turtle and J. Flood, "Query evaluation: strategies and optimizations", Information Processing & Management 1995; A. Broder, D. Carmel, M. Herscovici, A. Soffer and J. Zien, "Efficient query evaluation using a two-level retrieval process", CIKM 2003; S. Ding and T. Suel, "Faster top-k document retrieval using block-max indexes", SIGIR 2011.
  • S. Brin and L. Page, "The anatomy of a large-scale hypertextual Web search engine", WWW 1998; J. Kleinberg, "Authoritative sources in a hyperlinked environment", J. ACM 1999; Z. Gyöngyi, H. Garcia-Molina and J. Pedersen, "Combating Web spam with TrustRank", VLDB 2004.
  • A. Heydon and M. Najork, "Mercator: a scalable, extensible Web crawler", World Wide Web 1999; J. Cho and H. Garcia-Molina, "Synchronizing a database to improve freshness", SIGMOD 2000; M. Charikar, "Similarity estimation techniques from rounding algorithms", STOC 2002; G. S. Manku, A. Jain and A. Das Sarma, "Detecting near-duplicates for web crawling", WWW 2007; RFC 9309, Robots Exclusion Protocol (2022).
  • L. A. Barroso, J. Dean and U. Hölzle, "Web search for a planet: the Google cluster architecture", IEEE Micro 2003; J. Dean and L. A. Barroso, "The tail at scale", Communications of the ACM 2013; R. Baeza-Yates et al., "The impact of caching on search engines", SIGIR 2007.
  • F. Damerau, "A technique for computer detection and correction of spelling errors", Communications of the ACM 1964; W. Burkhard and R. Keller, "Some approaches to best-match file searching", Communications of the ACM 1973; M. Kernighan, K. Church and W. Gale, "A spelling correction program based on a noisy channel model", COLING 1990.
  • C. Burges et al., "Learning to rank using gradient descent", ICML 2005; C. Burges, "From RankNet to LambdaRank to LambdaMART: an overview", Microsoft Research Technical Report MSR-TR-2010-82 (2010); T. Joachims et al., "Accurately interpreting clickthrough data as implicit feedback", SIGIR 2005; N. Craswell, O. Zoeter, M. Taylor and B. Ramsey, "An experimental comparison of click position-bias models", WSDM 2008; T. Joachims, A. Swaminathan and T. Schnabel, "Unbiased learning-to-rank with biased feedback", WSDM 2017.
  • H. Jégou, M. Douze and C. Schmid, "Product quantization for nearest neighbor search", IEEE TPAMI 2011; Y. Malkov and D. Yashunin, "Efficient and robust approximate nearest neighbor search using hierarchical navigable small world graphs", IEEE TPAMI 2018; V. Karpukhin et al., "Dense passage retrieval for open-domain question answering", EMNLP 2020; G. Cormack, C. Clarke and S. Büttcher, "Reciprocal rank fusion outperforms Condorcet and individual rank learning methods", SIGIR 2009; N. Thakur et al., "BEIR: a heterogeneous benchmark for zero-shot evaluation of information retrieval models", NeurIPS 2021 Datasets and Benchmarks.
  • O. Khattab and M. Zaharia, "ColBERT: efficient and effective passage search via contextualized late interaction over BERT", SIGIR 2020; T. Formal, B. Piwowarski and S. Clinchant, "SPLADE: sparse lexical and expansion model for first stage ranking", SIGIR 2021; Y. Tay et al., "Transformer memory as a differentiable search index", NeurIPS 2022; P. Indyk and H. Xu, "Worst-case performance of popular approximate nearest neighbor search implementations: guarantees and limitations", NeurIPS 2023.
About this partfrom its README

Part 47 of a sixty-one-part course in computer science (see the series plan and the syllabus), the third part of Act IX, Systems at Scale. Finding the ten most useful pages among hundreds of billions in a fraction of a second rests on five pieces of mathematics: an inverted index turns a query into the merging of sorted lists, compression keeps those lists in memory, a probabilistic model of relevance yields BM25, a random surfer yields PageRank, and vectors searched through a layered graph find passages by meaning. We build each piece small enough to read, and put them together as a search engine for the thirty novels.

The instruments are in explainer/cs/search/ (tested in tests/test_cs47_search.py):

  • text.py: the thirty novels cut into passages of 400 words (11,261 of them); a tokenizer with case folding; 48 stop words; Porter's stemmer written out rule by rule and checked against his published examples; Zipf's and Heaps' laws fitted by least squares on log scales.
  • index.py: the inverted index, postings with positions, built in one pass; Boolean intersection by linear merge, with skip pointers every √n, and by galloping search, each counting comparisons; phrase queries over positions; postings stored as gaps in variable-byte, Elias γ and δ, and Golomb–Rice codes, with the bits counted.
  • rank.py: tf-idf with length normalisation and BM25 (Lucene's idf, k₁ = 1.2, b = 0.75); precision, average precision and nDCG on nine queries with rule-based judgments; WAND, document at a time with per-term score bounds, counting the passages it fully scores.
  • links.py: PageRank by power iteration and HITS on a synthetic web grown by preferential attachment, with a link farm; SimHash fingerprints over three-word shingles; stand-in passage vectors (tf-idf projected to 64 dimensions by a random matrix); product quantization by k-means in each sub-space, searched by asymmetric distance; a compact HNSW graph; edit distance, a BK-tree and noisy-channel spelling correction; top-k autocompletion.
Chapter notes
  • Hook. Finding things: Archie (McGill, 1990) indexing FTP file names; crawlers and directories by 1994; AltaVista's full text of the web (1995); Google (1998), links as votes, an index of 24 million pages; today's indexes of hundreds of billions of pages (Google, How Search Works). Five ideas. Our engine: 11,261 passages, 40,692 terms, 2,364,691 postings; white whale answered with four passages of Moby-Dick (BM25 10.53, 10.31, 10.07, 9.59), each with a snippet.
  • 1. Words, stems and Zipf. Tokens, case folding (US and us merge), stop words (12 of the 23 tokens of Austen's first sentence); Porter's stemmer step by step on generalizations → gener, with the measure m; all 20 of Porter's published examples reproduced; whaling, whales → whale, but general and generous both → gener, and ran never meets run. Zipf's law: 4,556,139 tokens and 61,720 different words; the occurs 230,876 times (5.1%), the top 20 words are 32% of the text; slope −1.21 on ranks 10 to 10,000; 22,888 words (37%) occur once. Heaps' law: K = 32.9, β = 0.485, with Ulysses, last in our order, the jump at the end; stemming turns 61,720 words into 40,692 terms, 34% fewer.
  • 2. The inverted index. The incidence matrix: 40,692 terms by 11,261 passages, 458 million cells, of which 2,364,691 (0.52%) are marked. Dictionary (whale in 390 passages, ahab in 181) and postings (a passage averages 405 tokens and 210 distinct terms); whale opens with a run, passages 659 to 669, Moby-Dick's pages of quotations about whales. Building by sorting (2.36 million pairs, 19 MB at 8 bytes a pair; blocked sort-based indexing as Part 16's external sort); single-pass in-memory indexing (Heinz and Zobel, 2003); segments merged like the carries of a binary counter, deletions in a bitmap, as in Lucene and Part 34's LSM trees.
  • 3. Merging postings. AND as a merge of two sorted lists, at most m + n comparisons; skip pointers every √n (the AND whale, 11,257 and 390 postings: 11,137 comparisons, 1,790 with skips); galloping search (Bentley and Yao, 1976): 1,418 for the AND whale, and 1,915 for love AND marriag against 2,680 for the merge. The five queries compared (merge, skips, galloping): whale–sea 924, 720, 994; captain–ahab 278, 292, 386; love–marriag 2,680, 2,598, 1,915; the–whale 11,137, 1,790, 1,418; elizabeth–darci 349, 310, 534. Lists of similar length favour the merge or skips; at length ratios of 4.7 and 28.9 galloping wins, 7.9 times fewer comparisons than the merge for the AND whale. Phrases over positions: white whale in 64 of the 125 passages that have both words; mr darcy 137 of 159; sherlock holmes 99 of 101; call me ishmael in exactly one of 3, the first line of chapter one; 4,556,139 positions beside 2,364,691 passage ids.
  • 4. Compressing postings. As 32-bit integers the ids take 9.5 MB; gaps average N/f (whale: 11,261/390 ≈ 28.9). Variable byte: 8.67 bits a posting. Elias γ (2⌊log₂ g⌋ + 1 bits, ideal for P(g) ≈ 1/(2g²) by Kraft) and δ: 5.64 and 5.54 bits a posting. Golomb's code derived for geometric gaps, M ≈ 0.69 N/f (19.7 for whale), and Rice's power of two, k = 4; Rice codes with k = 2 drawn; Rice over the index, one k per list: 4.96 bits a posting, against the bound log₂ C(N, f), 4.74 bits, within 5%. Block codecs: fixed widths packed side by side and unpacked by SIMD, PForDelta (2006), Lemire and Boytsov's SIMD-BP128 (2015).
  • 5. From tf-idf to BM25. Term frequency damped by a logarithm and Spärck Jones's idf (ln(N/df): whale 3.36, darci 4.19); passages as vectors in Salton's SMART geometry, ranked by cosine; the probability ranking principle (Robertson, 1977) with its exchange proof; the binary independence model derived step by step to the Robertson–Spärck Jones idf (1976), and Lucene's form log(1 + (N − df + 0.5)/(df + 0.5)), never negative; Harter's two-Poisson model and Robertson and Walker's saturation tf(k₁ + 1)/(tf + k₁), drawn for k₁ = 0.5, 1.2, 2 and 5; length normalisation by b; BM25 at TREC-3 (1994), Lucene's defaults k₁ = 1.2, b = 0.75.
  • 6. Is the ranking good? Precision and recall at k on an illustrative ranking of ten (six relevant passages, one never retrieved); average precision 0.59; MAP on our nine queries, cut at ten: BM25 0.80, tf-idf 0.75. nDCG derived (gain 2^g − 1, discount 1/log₂(i + 1), divided by the ideal order): 0.80 for the illustrative ranking. Test collections (Cranfield), TREC's pooling, Zobel's finding that comparisons survive incomplete pools. Our nine queries, graded by rule: nDCG@10 of 1.00 for both rankers on six of them; sherlock holmes 0.60 for both, because 4 of BM25's top ten come from The Hound of the Baskervilles, which the rule cannot count; vampire count 0.25 and 0.23, swamped by The Count of Monte Cristo; means 0.847 and 0.834. The sign test: 6 ties, 3 for BM25, none for tf-idf, p = 2 × 2⁻³ = 0.25: nine queries cannot tell.
  • 7. Top k, fast. Scoring everything: the sea has a term in 11,257 of the 11,261 passages, and all are scored into a min-heap whose smallest score is θ. Per-term upper bounds and max-score (Turtle and Flood, 1995); WAND's pivot (Broder et al., 2003) on a toy query with bounds 0.8, 1.2, 3.0 and θ = 2.6: 4 of 13 documents scored, exactly those with ahab. On the novels, BM25's top ten with a rising θ: white whale 235 of 1,610 candidates scored (15%), captain ahab ship 117 of 952 (12%), the sea 1,144 of 11,257 (10%), love marriage money 359 of 3,633 (10%), pride prejudice 213 of 454 (47%); every top ten identical to exhaustive scoring, score for score. Block-max WAND (Ding and Suel, 2011; in Lucene since 2019); tiered indexes and champion lists, which are unsafe.
  • 8. Links and the random surfer. Links as votes and anchor text (Brin and Page, 1998); the PageRank equation, d = 0.85, pages without links, the Google matrix's eigenvector as a Markov chain's stationary distribution (Part 18), Perron–Frobenius. Power iteration on a synthetic web of 400 pages grown by preferential attachment plus a farm of 20: the change falls to 1.1 × 10⁻⁶ after 40 steps, faster than the guaranteed factor 0.85 a step; the top pages are the oldest (pages 0, 2, 1, 3, 8). HITS (Kleinberg, 1999) as the leading singular vectors of the link matrix: the top authority is the farm's target (page 399), the top hub a farm page (400), and all 20 farm pages are among the 20 best hubs. Link spam: the target ranks 346th of 400 without the farm, 114th of 420 with it; nofollow (2005) and TrustRank (Gyöngyi, Garcia-Molina and Pedersen, 2004).
  • 9. Crawling the web. The crawl loop: frontier, DNS and robots.txt, fetch, parse, content fingerprint, URL normalisation and the seen-URL set (Part 17); Mercator (Heydon and Najork, 1999) and crawler traps. The frontier's front queues for priority and back queues with a heap of hosts for politeness (a pause of about ten times the last fetch); robots.txt (Koster, 1994; RFC 9309, 2022). Freshness: a page changing at rate λ and revisited every I is fresh for (1 − e^(−λI))/(λI) of the time; Cho and Garcia-Molina's (2000) uniform revisiting beats proportional. SimHash (Charikar, 2002) over three-word shingles as Part 20's random hyperplanes: on 200 passages with words replaced at random, 1 word moves 2.4 bits on average (at most 7), 5 words 5.5 (13), 20 words 10.4 (22), 80 words 19.8 (29); unrelated passages differ in 31.9 bits on average, at least 22; Manku, Jain and Das Sarma's (2007) 3-bit threshold for 8 billion pages, found by exact lookups on four 16-bit blocks.
  • 10. Serving at scale. The index as a sparse matrix cut by columns (document-partitioned shards) or by rows (term-partitioned servers); whale AND sea in each layout: four shards each return a top ten for the broker to merge, against one server shipping all 390 postings of whale to the other, which finds the 231 passages with both; web engines partition by document (Barroso, Dean and Hölzle, 2003). The tail at scale: 1 − 0.99ⁿ of queries are slow, 63% for 100 servers; hedged requests cut the 99.9th percentile from 1,800 ms to 74 ms for 2% more requests (Dean and Barroso, 2013). Shards and replicas as a grid; result caches for the head of a Zipf-skewed query stream, postings caches (Baeza-Yates et al., 2007).
  • 11. Spelling and autocomplete. The noisy channel, argmax P(w) P(t | w), with counts in the novels as the language model and a fixed penalty per edit (Kernighan, Church and Gale, 1990, learned theirs); the Levenshtein table (captian to captain: 2 edits) and Damerau's transposition (1964); BK-trees (Burkhard and Keller, 1973) pruning by the triangle inequality, drawn for whsle within one edit; on the 31,190 words that occur at least three times, tolerance 2 still costs 8,098 to 11,752 distances per typo, about a third. Seven inputs: captian, elizabth, seperate, monstr and londn repaired; whale kept (76 neighbours, none common enough); recieve → relieve, one substitution away, where receive is two. Completion as the best k below a trie node: ca gives can, came, called, cannot, can't.
  • 12. Learning to rank. Features of a query and a passage (BM25, tf-idf, phrase, proximity, length; on the web PageRank and clicks; MSLR-WEB30K has 136); pointwise, pairwise (RankNet, 2005) and listwise (ListNet, 2007) losses; LambdaRank's lambdas, RankNet's pair gradients times |ΔnDCG|, on six illustrative passages (nDCG 0.60; passage C, grade 3 at rank 3, pushed hardest); LambdaMART as boosted trees on the lambdas (AI, Built Part 6): nDCG 0.60, then 0.94, then 1, the ideal order; the Yahoo! Learning to Rank Challenge (2010). Clicks and position bias: the swapped-results eye-tracking study (Joachims et al., 2005), the cascade model (Craswell et al., 2008), inverse propensity weighting (Joachims, Swaminathan and Schnabel, 2017).
  • 13. Dense retrieval. Vocabulary mismatch; an encoder (AI, Built Part 24) and the dot product; our stand-in vectors, tf-idf projected to 64 dimensions by a random matrix (Part 20), 256 bytes each; DPR (Karpukhin et al., 2020). Product quantization (Jégou, Douze and Schmid, 2011): 8 sub-vectors of 8 dimensions, one byte each; recall of the true top ten over 100 queries is 7%, 13%, 31% and 54% with 2, 4, 8 and 16 bytes, squared error 0.66, 0.49, 0.27 and 0.08; codes shortlist and exact vectors re-rank (Faiss). HNSW (Malkov and Yashunin) on 3,000 passage vectors: levels of 2,621, 334, 41 and 4 points; building took 1,061,951 distances; beam 40 finds 81% of the top ten for 467 distances, about a sixth of brute force's 3,000 (beams 10 to 160: 68% for 191 to 95% for 1,232). Reciprocal rank fusion (Cormack, Clarke and Büttcher, 2009); BEIR (2021); retrieval-augmented generation (AI, Built Part 15).
  • 14. A search engine for the novels. The pipeline on the hound on the moor (stems hound, moor): postings, BM25, top ten, snippets. Four top answers: white whale → Moby-Dick, passage 817 (BM25 10.5); call me ishmael → Moby-Dick, passage 676 (10.4); pride and prejudice → Pride and Prejudice, passage 2 (11.3); the hound on the moor → The Hound of the Baskervilles, passage 4,653 (15.4). The index's ids under each code: 32-bit 9.5 MB, variable byte 2.6, γ 1.7, δ 1.6, Golomb–Rice 1.5, the bound 1.4. What a web engine adds; Lucene beneath Elasticsearch, OpenSearch and Solr.
  • 15. Frontier: retrieval and its limits. Graph search without a guarantee (our HNSW: 68% recall for 191 distances, 95% for 1,232, against 3,000), locality-sensitive hashing (Part 20); learned sparse retrieval (SPLADE, 2021), late interaction (ColBERT, 2020), hybrids, and why BM25 stays hard to beat on new collections; retrieval for machines that write: retrieval-augmented generation and generative retrieval (Tay et al., 2022), and what is open in evaluating written answers. Four open problems and the ★ research problem.
  • Outro. Recap, payoffs, practice, problems, next part.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record

We build a search engine for the thirty novels.

  1. Hook: from Archie (1990) and AltaVista (1995) to Google (1998); the scale of a web index (cited).
  2. Tokenizing and normalizing: Porter's stemmer; case folding; stop words. Zipf's and Heaps' laws fitted on the novels.
  3. The inverted index: dictionary and postings; sort-based and single-pass in-memory construction (callback to Part 16's external sort).
  4. Boolean retrieval: merging postings; skip pointers (√n); galloping intersection (callback to Part 24); positional indexes for phrases.
  5. Postings compression: gaps; variable-byte; Elias γ and δ (code lengths derived, callback to AI, Built 1); Golomb–Rice with its optimal parameter derived; SIMD block codecs (callback to Part 24).
  6. Ranking: tf–idf and cosine similarity; the probability ranking principle (Robertson 1977); the binary independence model up to BM25, with its k₁ saturation and b length normalization derived.
  7. Evaluation: precision, recall, MAP, nDCG (derived); test collections and pooled judgments; significance (callback to Part 44).
  8. Top-k retrieval: WAND and block-max WAND (dynamic pruning with score upper bounds); tiered indexes.
  9. Link analysis: PageRank as an eigenvector (callback to Part 18); HITS; link spam.
  10. Crawling: the URL frontier, politeness, freshness policies, near-duplicates by SimHash (callback to Part 20).
  11. Serving at scale: document- against term-partitioned indexes (callback to Part 39); replicas; fan-out and the tail (callback to Part 39); result and postings caches.
  12. Spelling and autocomplete: noisy-channel correction with edit distance (callbacks to Parts 19 and 21); BK-trees; top-k completion over tries (callback to Part 17).
  13. Learning to rank: pointwise, pairwise, listwise; LambdaMART (callback to AI, Built 6); click models and position bias.
  14. Dense retrieval: embeddings (callback to AI, Built 24); product quantization (Jégou et al. 2011) and HNSW (Malkov & Yashunin); hybrid lexical-plus-dense retrieval; retrieval for language models (AI, Built 15).
  15. Our engine for the novels: the index, BM25, phrases, snippets, and an evaluation on a small query set we judge ourselves (labelled illustrative). Outro.

Computed: Zipf and Heaps fits; index sizes under each code; comparison counts for intersection algorithms; BM25 against tf–idf on our judged set; WAND pruning rates; PageRank on a synthetic web; SimHash near-duplicates; PQ distortion; HNSW recall against speed. Visuals: postings lists sliding together during intersection; gap codes as bit strings; BM25's saturation curves; WAND's pivot moving across lists; a random surfer on a graph; HNSW's descent through its layers. In practice: Lucene, Elasticsearch, OpenSearch; web and e-commerce search; vector databases; retrieval-augmented generation. Reading: Manning, Raghavan & Schütze, Introduction to Information Retrieval; Büttcher, Clarke & Cormack, Information Retrieval: Implementing and Evaluating Search Engines; Witten, Moffat & Bell, Managing Gigabytes; Zobel & Moffat 2006; Robertson & Zaragoza 2009; Porter 1980; Brin & Page 1998; Kleinberg 1999; Broder et al. 2003; Ding & Suel 2011; Charikar 2002; Jégou, Douze & Schmid 2011; Malkov & Yashunin 2018; Burges 2010.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 倍增查找求交。 证明对长度为 m ≤ n 的两个表,倍增(跳跃式)查找求交需要 O(m log(n/m)) 次比较,并证明这在常数因子内是最优的。

    解答

    设短表为 a₁ < … < a_m,长表为 b₁ < … < b_n。倍增查找在长表中维护一个只会向前移动的位置。对 aᵢ,它向前探查 1、2、4、 8……个位置,直到某次探查到达 ≥ aᵢ 的值或越过表尾,再在最后一个区间里二分查找,最后做一次相等比较。若位置前进了 gᵢ 个位置, 倍增至多探查 log₂(gᵢ + 1) + 1 次,留下的区间不到 gᵢ + 1 个位置,所以查找 aᵢ 至多花 2 log₂(gᵢ + 1) + 3 次比较。各 gᵢ 之和至多为 n, 而 log 是凹函数,由 Jensen 不等式 Σ log₂(gᵢ + 1) ≤ m log₂(n/m + 1)。总数至多 2m log₂(n/m + 1) + 3m = O(m(1 + log(n/m))), 当 n ≥ 2m 时就是 O(m log(n/m))(n < 2m 时是 O(m),即读一遍短表的代价)。 下界:考虑基于比较的算法,输入中没有 aᵢ 等于任何 b_j。算法停下时,它必须知道每个 aᵢ 落在哪个间隙 (b_j, b_{j+1}) 中:如果在它的 比较结果所蕴含的顺序里 aᵢ 与某个 b_j 不可比,就存在一个线性扩张使二者相邻,把它们设为相等不改变任何比较结果,却使交集非空, 所以算法在这两个输入之一上出错。由于 aᵢ 有序,这些间隙构成 n + 1 个位置中 m 个位置的非降序列,共有 C(n + m, m) 种选法,而每次比较 (这里从不出现“相等”)只有两种结果。所以某个输入至少需要 log₂ C(n + m, m) ≥ m log₂((n + m)/m) ≥ m log₂(n/m) 次比较。在小说上, love AND marriag(500 和 2,363 个倒排项)用了 1,915 次比较,而 m log₂(n/m) ≈ 1,120,在分析给出的 2 倍之内。the AND whale 用了 1,418 次,低于最坏情形的 log₂ C(11,647, 390) ≈ 2,459,因为每个含 whale 的段落都含 the:下界针对最坏的输入,而自适应分析 (Demaine、López-Ortiz 与 Munro)衡量的是一个实例有多难。

  2. 编码长度。 推导 Elias γ 码和 δ 码的长度,以及对服从几何分布的间隔最优的 Golomb 码参数。

    解答

    间隔 g ≥ 1 有 L = ⌊log₂ g⌋ + 1 位二进制数字,第一位总是 1。γ 码先写 L − 1 个 0,再写这 L 位数字;解码器数 0 的个数就知道 后面跟着几位,所以它是前缀码,|γ(g)| = 2⌊log₂ g⌋ + 1。对每个 L 有 2^(L−1) 个长度为 2L − 1 的间隔,所以 Σ 2^(−|γ(g)|) = Σ_L 2^(−L) = 1:这个码是完备的,由 Kraft 不等式,它对 P(g) = 2^(−|γ(g)|) ≈ 1/(2g²) 是理想的。δ 码先用 γ 码写 L, 再写首位 1 之后的 L − 1 位:|δ(g)| = ⌊log₂ g⌋ + 2⌊log₂(⌊log₂ g⌋ + 1)⌋ + 1 = log₂ g + O(log log g),所以间隔大时它更短。g = 9 时, γ = 0001001(7 位),δ = 00100001(8 位);g = 100 时为 13 位对 11 位。 对 Golomb 码,设每个段落独立地以概率 p = f/N 含有该词项,于是 P(g) = (1 − p)^(g−1) p。写 g − 1 = qM + r,0 ≤ r < M。则 P(q) = Σ_r (1 − p)^(qM+r) p = θ^q (1 − θ),其中 θ = (1 − p)^M:商仍服从几何分布。一元码花 q + 1 位,当 P(q) = 2^(−(q+1))、即 θ = ½ 时最理想:(1 − p)^M = ½,M = ln 2 / (−ln(1 − p)) ≈ 0.69/p = 0.69 N/f。在一个块内,r 的概率从一端到另一端只下降 θ = ½ 倍, 所以(截断的)二进制余数几乎是理想的。精确的整数最优值是 M = ⌈log(2 − p) / (−log(1 − p))⌉(Gallager 与 van Voorhis,1975)。 对 whale,p = 390/11,261:M ≈ 19.7,整数最优值为 20;在几何模型下,M = 20 时每个间隔 6.30 位,Rice 码的 M = 16(k = 4)为 6.32 位,而模型的熵是 6.27 位。真实的倒排表是成簇的,所以整个索引的 Rice 码(4.96 位)比 log₂ C(N, f)(4.74 位)略高。

  3. BM25。 从二元独立模型出发,借助双泊松近似推导 BM25 的词项权重,并解释 k₁ 和 b。

    解答

    按相关的几率排序;由贝叶斯法则以及给定相关性时各词项独立,对数几率除去与段落无关的项外,等于对段落中出现的查询词项求和 w_t = log [p_t (1 − u_t)] / [u_t (1 − p_t)],其中 p_t、u_t 分别是 t 出现在相关段落和不相关段落中的概率。没有相关性信息时取 p_t = ½;几乎所有段落都不相关,所以 u_t ≈ df/N:w_t = log((N − df)/df),各计数加 0.5 就得到 Robertson–Spärck Jones 权重 log((N − df + 0.5)/(df + 0.5))。当 df > N/2 时它是负的(the 出现在 11,261 个段落中的 11,257 个里,权重为 −7.82),所以 Lucene 和我们的 rank.py 用 log(1 + (N − df + 0.5)/(df + 0.5)):the 为 0.0004,whale 为 3.36。二元模型不管 t 出现了几次。Harter 的 双泊松模型说,一个段落对 t 要么是“精英”的(讲的就是它),要么不是;前一种情形 tf 服从均值 λ 的泊松分布,后一种服从均值 μ < λ 的 泊松分布,混合权重取决于相关性。于是一个计数的权重为 w(tf) = log [P(tf | R) P(0 | R̄)] / [P(tf | R̄) P(0 | R)]:tf = 0 时为 0, 随 tf 上升;tf 增大时精英分量在两个混合分布中都占主导,所以 w 趋于一个极限,即“精英”本身的权重,它扮演二元模型中权重的角色。 这个模型的四个参数没有相关性数据就无法估计,所以 Robertson 与 Walker 只保留了它的形状:w(tf) ≈ w_t · tf/(tf + k₁),再乘以 k₁ + 1,使出现一次时恰好得 w_t(这是公共因子,不改变排序):tf(k₁ + 1)/(tf + k₁)。k₁ 决定计数饱和得多快:k₁ → 0 退回二元模型, k₁ → ∞ 就是原始计数;k₁ = 1.2 时,tf = 1、2、5、10 对应的因子为 1、1.375、1.774、1.964,趋于 2.2。关于长度:长段落出现次数多是 因为它长(冗长假设),所以用段落的相对长度 B = 1 − b + b|d|/avgdl 来衡量 tf:(tf/B)(k₁ + 1)/(tf/B + k₁) = tf(k₁ + 1)/(tf + k₁B)。 b = 0 不考虑长度(长段落涵盖更多话题,即范围假设);b = 1 完全归一化。取 b = 0.75,长度为平均两倍的段落 K = k₁B = 2.1,出现一次 得 0.71,两次得 1.07;长度为平均一半时 K = 0.75,出现一次得 1.26。我们的段落都约 400 词,所以这里 b 影响不大。

  4. PageRank。 证明 PageRank 是一个马尔可夫链的平稳分布,并证明幂迭代以速率 d 收敛。

    解答

    设 M 为 N × N 矩阵:q 链接到 p 时 M_pq = 1/L(q)(L(q) 为 q 的链接数);q 没有链接时对所有 p 取 M_pq = 1/N;每一列之和 为 1。令 G = dM + (1 − d)/N · 𝟏𝟏ᵀ。G_pq 是停在 q 上的冲浪者下一步到 p 的概率(以概率 d 随机点一个链接,否则均匀地跳到任一页面), 它的列和为 d + (1 − d) = 1,而 (Gr)p = (1 − d)/N + d Σ{q→p} r_q/L(q)(没有链接的页面把排名平均分给所有页面),这正是 PageRank 方程。所以满足 r ≥ 0、Σr = 1、r = Gr 的向量恰好是这个链的平稳分布。G 的每个元素至少为 (1 − d)/N > 0,所以这个链不可约且非周期, 由 Perron–Frobenius 定理,特征值 1 是单重的,并有正的特征向量:r 存在且唯一。关于收敛:取任意满足 Σz = 0 的 z(两个概率向量之差), 则 𝟏ᵀz = 0,所以 Gz = dMz;又因 M 的元素非负、列和为 1,‖Mz‖₁ ≤ Σ_q |z_q| Σ_p M_pq = ‖z‖₁。因此 ‖Gz‖₁ ≤ d‖z‖₁,迭代 r_k = G^k r₀ 满足 ‖r_k − r‖₁ ≤ d^k ‖r₀ − r‖₁ ≤ 2d^k,相邻两步的变化也至少按 d 缩小:‖r_{k+1} − r_k‖₁ ≤ d^k ‖r₁ − r₀‖₁。(等价地, G 的其他特征值的模都不超过 d;Haveliwala 与 Kamvar,2003。)这个界与 N 无关:从至多 2 降到 10⁻⁶ 以下,对任何规模的网页都只需 log(2 × 10⁶)/log(1/0.85) ≈ 89 步。在我们的合成网页上,第一步的变化是 1.04;这个界在第四十步时允许 1.04 × 0.85³⁹ ≈ 1.8 × 10⁻³, 而实测为 1.1 × 10⁻⁶,临近结束时每步缩小约 0.81 倍。

  5. 动手。 给我们的引擎加上 block-max WAND(每个倒排块一个得分上界),并测量它多跳过了多少文档。

    解答

    解答要点。 在 rank.wand 中,每个词项的表已经是(段落,得分贡献)对的列表,并有一个上界 ub[i],即它最大的贡献。在同一遍里把 每个表切成 B 个倒排项一块(比如 64),为每块存下它的最后一个段落号和块内最大的贡献;再给每个游标一个块指针。仍像现在这样用全局 上界选出枢轴。然后做浅层检查:对当前段落不晚于枢轴段落的每个游标,只把它的块指针移到可能包含枢轴段落的那一块(不读任何倒排项), 把这些块的最大值相加。若和超过 θ,就照 WAND 的做法继续:这些游标都在枢轴上时给枢轴打分,否则把它们推进到枢轴。若不超过,则直到 这些块中最早结束的那块的末尾,没有段落能达到 θ:把这些游标移到(最早的块末尾 + 1)与第一个其他游标的当前段落两者中较小的那个, 一个也不打分。完整打分的段落照 scored 那样计数,块检查另行计数。安全性的检验与 test_wand_matches_exhaustive 一样,与 top(bm25_scores(...)) 比较,在玩具文档和 compute_wand 的五个查询上逐个分数核对。然后对块大小 32、64、128 报告 WAND(五个查询 分别为 235、117、1,144、359、213)和 block-max WAND 完整打分的段落数。我们的段落都约 400 词,所以一个词项的贡献主要随 tf 变化; 可以预期,最大值由少数高频段落决定的长表收益最大,而词项都很罕见的 pride prejudice 收益很小。我们的游标一次只前进一个倒排项, 要把跳过的段落变成省下的时间,游标的移动还应当用上第 3 章的跳表指针或倍增查找。

  6. ★ 研究。 求一个基于图的最近邻索引,在现实的数据上有可证明的召回率和查询时间。

    讨论。 尚未解决。HNSW 这样的图索引在基准测试中领先(我们的图用 3,000 次中的 467 次距离计算找到真正前十中的 81%),但它们的 保证是启发式的:在对抗性的输入上,贪心游走可能停在离答案很远的地方。Indyk 与 Xu(NeurIPS 2023)构造了使 HNSW 等常用图需要关于 n 线性时间的实例,同时对 DiskANN 的图的一种慢速构建的变体,在倍增维度有界的数据上证明了界。在倍增维度下有保证的结构,如导航网 (Krauthgamer 与 Lee,2004)和覆盖树(Beygelzimer、Kakade 与 Langford,2006),以及高维中的局部敏感哈希(第20部分),在实践中 都不如图索引;而倍增维度是最坏情形的度量,对真实的嵌入向量可能很大。好的答案应当确定一个现实数据的模型(某种可测意义下的低内在 维度,或嵌入向量的生成模型),给出一个近线性时间构建、度数和查询时间关于 n 为多对数(只对内在维度是指数的)的图,证明在它上面的 束搜索召回率至少为 1 − δ,并在真实向量上表明模型的假设成立。仅对单一束宽、对球面上的随机数据的部分结果,或者说明任何稀疏图都做不到 什么的下界,就已经是新的。

Build the film

python -m videos.cs.cs47.compute        # the part's numbers, into .cache/cs47
python tools/build.py cs47                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs47 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs47. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs47.compute
python -m unittest tests.test_cs47_search
python tools/build.py cs47