Ch.19: Algorithms: How Vector Search Finds Similar Things

Outline

Transcript

0:00 Suppose your help article says “reset your password.” A customer searches “I can't get into my account.” A strict word match fails to find it, although the answer is right there. They need to know our wording before they can find the help. Ambitious requirement for a help page. Vector search can solve that mismatch by comparing numerical representations. But what is the computer actually comparing? First, a vector is an ordered list of numbers. Imagine the list two, one describing a point on a floor: two steps right, one forward.

0:31 The list locates that point. So two numbers describe one point, not two separate results. An embedding model produces a number list for each item, such as our question or help article. Now choose a distance rule. On a line, put our query at zero and an item at plus two. They're two units apart. An item at minus five is five away. Smaller distance means nearer. Longer vectors need a rule that compares all their numbers. Okay, so those numbers give us something we can measure. But do the number slots mean things like “password-related”?

1:04 No, learned coordinates generally don't have those human labels. Google's embedding tutorial makes that distinction. Training aims to put useful relationships near each other, so differently worded questions can land near the same useful article. With those vectors and a fixed distance rule, try the simplest search. Compare the query with every stored item. Keep one best-so-far result, replacing it whenever a smaller distance appears. For example, measured distances arrive as six, two, five, one. Six starts as best; two replaces it; five is worse, so keep two; then one replaces two.

1:39 After the last item, return the one at distance one. That's exact nearest-neighbor search. We know nothing was closer because we checked everything. Suppose we wanted three results. We'd retain the nearest three instead of just one. And exact means nearest under these vectors and this distance. If the embedding represents the wrong idea, perfectly accurate search can still return an unhelpful article. But that exact scan costs a comparison with every item, on every query. Long number lists make each comparison extra work too.

2:08 So suppose we build links between selected items beforehand. The items are nodes, the links are edges, and together they're a graph. A query can follow links toward promising items rather than visit the whole collection. The vector says where an item sits in the comparison space. The graph says which other items we can reach from it. Those are two different pieces of information. Like hotel rooms a metre apart across a wall: close together, but no connecting door. A nearby item isn't automatically reachable by a graph link.

2:41 First, start that walk at an entry point. Measure its neighbors. Move to one that's closer to the query, then repeat from there. Stop when no neighbor improves the current distance. That's greedy graph search. Let's say we start six units away, find a neighbor three away, then another one unit away. Six, three, one. We moved toward the query without a full scan. That seems almost suspiciously easy. What if reaching the closest item requires a step farther away first? Then greedy search can stop too early.

3:13 Every immediate neighbor can look worse while a better answer waits beyond one of them. Local improvement isn't proof that we've found the global nearest item. Because local improvement can leave us stranded, HNSW adds layers of links and a broader search near the bottom. Hierarchy meaning several layers of the same items? Yes. Every item in this graph is on the bottom layer. Only some also appear above, and fewer reach the highest layers. Search starts at the top, follows improving links, then carries the best point down a layer.

3:46 Repeat until the bottom. Like using major roads to get near an address, then smaller streets to approach it. Except these roads are links through number space, not streets on a map. Exactly. The name is Hierarchical Navigable Small World. The layers help get us into a promising region; they haven't certified the nearest answer. So at the bottom, how do we keep alternatives alive instead of committing to that greedy route? Keep a pending list of points whose neighbors we might explore, nearest pending first.

4:17 Separately keep best, the closest answers we've discovered so far. Pending is possible work; best is possible answers. I'd been picturing one list doing both jobs. They often hold the same points, which makes that tempting. Also mark each point visited when we first measure it, even if it doesn't qualify for a list. That prevents checking the same point again around a loop. Okay, let's run a small example. I want to see when those two lists actually differ. For this concrete case, give best just one slot.

4:48 That capacity is called ef. We want one final nearest result too, but capacity and requested result count are different settings. We only keep one answer, then. Start at a point named Entry, distance six from the query. Both pending and best initially hold Entry, and we mark Entry visited. Entry has two links. One leads to Bridge at distance five; another to Guide at distance two. We'll inspect Bridge first, then Guide. These are invented points and fixed links for tracing the search. Okay, Bridge first.

5:21 I want to track what happens to it when we find something better. First take Entry out of pending and examine its neighbors. Measure Bridge: five. Mark it visited. Five beats our current best, Entry at six, so Bridge replaces Entry in best and joins pending. Then measure Guide: two, and record Guide as visited. Two beats Bridge's five. Guide takes the single best slot and also joins pending. Now best holds only Guide. Pending still holds Guide and Bridge, with Guide first because it's closer. Bridge was displaced as an answer, but its possible route is still waiting.

5:56 Oh, that's why we needed both lists. If we erased Bridge everywhere, we'd lose a possible expansion, not just a worse answer. Next expand Guide. Its only link goes back to visited Entry, so there's nothing new to measure. Bridge is now nearest pending, distance five. Our one retained answer is Guide at two. The candidate we'd expand is farther than the answer we're keeping. Is that when this search stops? Yes. More generally, compare nearest pending with the worst retained answer. If pending is farther, stop.

6:28 The search also finishes when pending is empty. Oh, we stopped one link short. Bridge connects to Answer, distance one. Guide wins our list at two, but loses to the point we never visited. We did. Return Guide at two, the nearest point we found. The original HNSW paper uses that stopping comparison; it's linked in the description. Like following hotel doors instead of checking every room, we can leave a room just a metre away unchecked. So an unseen point can still beat this result. With that graph, suppose we increase ef from one to two.

7:02 What changes when Entry discovers Bridge five and Guide two? Restart at Entry. After checking its neighbors, best keeps Guide two and Bridge five; Entry drops out. Pending holds those same two points, Guide first. We expand Guide and find nothing new. That leaves Bridge waiting at five, with Guide two and Bridge five still in best. Should Bridge get a turn? Yes. Five equals the worst retained distance, five, so the farther-than test doesn't stop us. Take Bridge out of pending and explore its link.

7:34 Answer at one appears. Mark it visited, add it to pending, and replace Bridge in best. So best is Answer one, Guide two. Pending is only Answer one. Guide and Bridge already had their turns; we don't put them back. What finishes this run? Expand Answer. Its only link returns to visited Bridge, so pending becomes empty. Finish and return Answer, the exact nearest point in this graph. The extra slot let us take the route we skipped before. With two slots, Bridge could still be expanded. For each unseen neighbor, we measure and mark visited.

8:07 Add it to pending and best if best has room, or if it improves the worst retained result. Trim best to ef, leaving existing pending candidates in place. I think the capacity is clearer now. We scored several points even with 1 best slot. Ef doesn't count distance evaluations; it limits the best list that shapes the stopping test. Our extra slot rescued this route. On another graph, we could spend more work and still miss the winner. Wait, we relied on Bridge already having that useful link. Who builds these routes in the first place?

8:41 Now those routes come from insertion. Add points one at a time. Give each a randomized highest layer, so most stay low and only a small fraction reach high layers. Search existing layers for candidate neighbors, then connect the new point. My instinct is to keep only the closest neighbors. Is that enough? Try a separate line example. We're inserting a point at zero, with room for two links. Candidates sit at plus one, plus two and minus three. Consider the nearest first, so keep plus one. Plus two is next. Do we compare it with zero, or with the neighbor we just kept?

9:17 Both. Measure from plus two to 0: two units. To plus 1: one. The paper's heuristic skips a candidate that's closer to a kept neighbor than to our new point. So plus two gets skipped. Then for minus three, the distances are three to zero and four to plus one. Three is smaller than four, so it passes. The different directions come from the distance test itself. Yes. Keep minus three, and we've filled both link slots. That's one small neighbor-selection pass, not the whole insertion procedure. Its choices change what a later query can discover.

9:53 Now construction and queries have different costs. More graph links need more storage. Searching harder during insertion costs build time. Our two-slot retry increased query work without changing those links. My first thought is to try that wider query search before rebuilding the graph. How do we check whether the extra work was worth it? Measure query time and recall: how much of the exact nearest result set the approximate search recovered. Pgvector calls that query setting ef search; its docs are linked below.

10:24 For one requested result, that means checking whether it found the exact winner. Then try representative queries from the collection. Finding Answer here tells us this example worked; we still have to measure what happens on those real queries. Finally, hold representation and distance fixed. Exact scanning checks every item. HNSW navigates sparse upper layers, then expands promising pending points at the bottom while retaining its closest results. And that retained list does two jobs: it holds possible answers and helps decide which routes are still worth expanding.

10:55 That's the bit I couldn't see in the word “approximate.” A query can save work by leaving points unvisited, and miss something nearer for the same reason. Whether those vectors express the user's meaning is another question to evaluate. We can now separate bad meaning, a missed neighbor and the extra exploration that might find it. Thanks for listening to Learning Podcasts.