4 Geometry and high-dimensional search
Space is a doubt: I must constantly mark it, designate it.
Georges Perec, Espèces d’espaces (1974)
4.1 Pharmacy, open now
Mia has just moved from Lisbon to Zagreb with her son, for a job she wanted, in a city she does not know yet. Everything here still has to be worked out from nothing. She cannot read the street names without stopping, she does not know which tram goes where, and every corner is a guess. At home she never had to think about where things were. Here the space itself is the problem.
On their first night in the new flat, at eleven, her son has a fever. The medicine she packed is somewhere in a box she cannot find. She picks up her phone and types pharmacy, open now, and five pharmacies appear on the map before her thumb has left the screen.
Here nearest means spatially nearest. A pharmacy that is almost the closest is a longer walk, at night, with a sick child, through streets she has never seen. And an answer that comes late is no answer. She is not going to stand in the hallway waiting for a map to think.
The service behind the phone holds every place on a continent, and at this moment millions of people are asking it something, each from a different spot. Which pharmacy is nearest depends on where you stand, so no order by distance can be prepared in advance. The phone also left out two pharmacies that were closer to Mia than some of the five, because they were closed.
The plain way to answer her is to measure the distance to every pharmacy and keep the nearest. This is a linear scan, the search chapter’s sequential scan with a distance in place of a key comparison. It is exact and needs no preparation. Every faster method in this chapter is checked against its answer, as the contracts chapter checked a clever method against the obvious algorithm as the definition.
Start with the plain way, on a small example. Mia stands at q = (5, 5) on a grid. Six pharmacies are open around her, named by letters in the order they are stored: a (2, 7), b (6, 3), c (9, 8), d (4, 1), e (7, 6) and f (1, 4). Measure each one. The distance from q to a point p is \sqrt{(p_x - q_x)^2 + (p_y - q_y)^2}, but there is no need for the square root, because comparing squared distances picks the same pharmacy, and with integer coordinates they stay integers.
\operatorname{dist}(p, q)^2 = (p_x - q_x)^2 + (p_y - q_y)^2 \tag{4.1}
For a that is 3^2 + 2^2 = 13. The other squared distances are 5 for b, 25 for c, 17 for d, 5 for e and 17 for f. The nearest is b, at squared distance 5, tied with e. Every structure in this chapter breaks ties the same way: the lower letter wins, which is the point stored first. So the answer is b, and the three nearest are b, e and a. A later section shows why the squares are always safe to compare, and what else near can mean.
Here is that scan in code.
None for no points.sq_dist adds up the squared differences, coordinate by coordinate. enumerate hands over each point with its number, counting from 0, so a is 0, b is 1, and so on. A point keeps its number however a structure rearranges the points. For the k nearest, the library keeps the k best so far in a heap, with the worst of them on top. Each new point is compared with that one only (scan.py).
The scan measures every point, for every query. With n points, each query costs n distances, and nothing is learned between queries. The next person, standing a street away, starts again from scratch, and so does Mia if she walks to the corner and asks again.
Draw twelve points anywhere on squared paper. People ask from different spots, “which point is nearest me?”, millions of times. Design something you could prepare once that answers faster than measuring every point.
Five minutes. You’re done when you can name one point your design would never measure for some query, and say why it is safe not to measure it.
In the scan, the squared distance to c, 25, says nothing about any other pharmacy, and that is a waste. Each structure in this chapter makes one measurement tell you about many points. One comparison can rule out half a street. One distance can prove a whole region of the map too far away to matter.
The chapter prepares the map once, so that most places never need measuring at all. It does that first for everything inside a strip of the map, and then for the single nearest place. A month on, Mia will ask her phone something harder, a place like one she loved in Lisbon. Every idea that worked on the map will then be tried again, in a space where it no longer works so well.
4.2 Everything between two streets
Range tree
The next morning the fever is down, and the boy is asleep. Mia opens the map again, this time without hurry. She wants to know every pharmacy between her street and the river, the stretch she will walk every day on her way to the school and to work. That is not one place but a strip of the map, and the question is everything in it.
The keys 3, 9, 12, 17, 21, 26, 30, 41 are distances along a street. Report every key in the range from 10 to 28, ends included, while looking at as few keys as you can.
Five minutes, with a pencil. You’re done when you can say where the looking starts and stops, and name the keys you reported without looking at them one by one.
Did you start with the search chapter’s binary search for 10? It finds where 10 would go, between 9 and 12, and that is one end of the range. Then you probably read 12, 17, 21 and 26 one at a time, until 30 told you to stop. Search for 28 as well, and follow both searches down a tree together. They go the same way until the two ends part. What lies between their paths after that?
The promise rests on invariant 1, and invariant 2 keeps the two walks in the cost short.
4.2.1 Keys in the leaves
The search chapter’s ordered trees could already read off every key in a range, one at a time. This tree hands the range back as a few whole subtrees instead, so that each subtree can later carry its own tree on a second coordinate. The tree keeps the keys in its leaves, sorted left to right along the bottom. Every node above the leaves is an inner node. It covers a run of the sorted keys, sends the first half to its left and the rest to its right, and holds the largest key on its left. When the count is odd, the left side takes the extra key, so a node over n keys sends \lceil n/2 \rceil of them left. The key that a node holds is therefore its lower median. That key separates the node’s two sides, as invariant 1 asks.
Like every index, the range tree works in two phases. The build runs once, before anyone asks. Then each query touches only a small part of what the build made. Build it on the eight keys from the exercise. The root covers all eight, sends 3, 9, 12 and 17 left and 21, 26, 30 and 41 right, and holds 17. Its left child splits 3 and 9 from 12 and 17, and holds 9. Its right child splits 21 and 26 from 30 and 41, and holds 26. One level further down, the nodes hold 3, 12, 21 and 30, and below each of them hang two leaves. The tree is three levels deep, since halving eight keys three times leaves one.
In code, the tree is built over positions in the sorted list rather than over the keys themselves. A leaf is one position, and an inner node covers a run of positions, from start up to just before end.
The constructor sorts the keys once, each with the number it was stored under, so the answer can name the stored points. build then never compares two keys at all, because the sorted list already says where every split falls. The omitted constructor lines reject keys that cannot be ordered and keep each key’s original number. The whole class is in range_tree.py.
4.2.2 Where the two ends part
A query asks for every key from lo to hi. It starts at the root and walks down while the whole range lies on one side of the node’s key, going left when hi is smaller than the key and right when lo is larger. The first node where neither holds is where the two ends part. That node is the split node, and from there the walk becomes two walks [1, Sec. 5.1].
Below the split node, each walk follows the rules of Table 4.1. When lo’s walk goes left, the right subtree it passes lies wholly inside the range, so it is reported whole, without reading a key. hi’s walk does the same with the left subtrees it passes when it goes right.
| walk | at a node with key s | then |
|---|---|---|
| to the split node | hi < s |
go left |
s < lo |
go right | |
| neither | stop: this is the split node | |
lo’s, from the split node’s left child |
lo \le s |
report the right subtree whole, go left |
s < lo |
go right | |
hi’s, from the split node’s right child |
s \le hi |
report the left subtree whole, go right |
hi < s |
go left |
Run it on the range from 10 to 28. The root’s key, 17, lies inside the range, so the root is already the split node. lo’s walk starts at 9, and 9 is smaller than 10, so it goes right, to 12. There 10 \le 12, so the walk reports the whole right child, the leaf 17. Then it goes left to the leaf 12, which it checks and finds inside. hi’s walk starts at 26, and 26 \le 28, so it reports the whole left child, which holds 21 and 26. Then it goes right to 30. There 28 is smaller than 30, so it goes left to the leaf 30, which it checks and finds outside. The answer is 12, 17, 21 and 26.
Count what the query read. It checked only two leaves against the range, and 12 went in while 30 did not go in. The leaves 17, 21 and 26 came out in whole pieces and were never compared with anything. The leaves 3, 9 and 41 were never reached at all. Every range works this way, with two walks down the tree and whole pieces between them.
Now take a range that sits inside one subtree, from 18 to 25. At the root, 17 is smaller than 18, so the walk goes right. At the node 26, the range’s end 25 is smaller than 26, so it goes left. At the node 21, the range lies on both sides, so 21 is the split node. Its left child is the leaf 21, which is checked and lies inside. Its right child is the leaf 26, which is checked and lies outside. The answer is 21. A binary search would also walk down to the split node. The two walks below it are what the tree adds.
In code, the query collects the pieces, the canonical subtrees. They are the whole subtrees, together with the leaf at the end of each walk when that leaf passes its check.
The test not w.split < lo writes lo \le w.split with only “smaller than”. So the same code works for any keys that can be ordered: numbers, words, dates. The omitted lines, ..., return nothing at once for an empty tree, or for a range whose lo is above its hi.
Walk it yourself below. Type a range, and before each step, say which way the walk goes.
Each walk goes down one level per step, and invariant 2 keeps the tree at most \lceil \log_2 n \rceil levels deep, since every level halves the keys. So a query costs two walks of at most \lceil \log_2 n \rceil steps, plus one step for each key it reports.1 For a million keys, that is about forty steps of walking, whatever the range, plus the answer itself.
Start above the split node. The walk went right only at a node whose key was smaller than lo. By invariant 1, nothing on that node’s left is larger than its key, so the keys that the walk passed by there are all smaller than lo and outside the range. In the same way, it went left only past keys larger than hi. So every key in the range sits below the split node.
Below it, take lo’s walk. hi’s walk is the mirror. Every key on the split node’s left is at most the split node’s key, which is at most hi, so on this side only lo can rule a key out. At a node whose key is at least lo, the right child’s keys are at least that key (invariant 1), so they are all in range, and reporting them whole is right. At a node whose key is smaller than lo, the left child’s keys are no larger, so they are all out, and skipping them is right. Either way, the child the walk leaves is decided whole, and the walk goes on into the child that is still undecided. At the bottom one leaf remains, and it is checked on its own. So no key in range is missed.
Nothing is reported twice, either. Each reported piece hangs off the walk at a different node, so no piece lies inside another. The leaves at the ends of the walks sit on the walks themselves, not inside any piece.
4.2.3 Two coordinates at once
A strip on a real map is often a rectangle, between two streets running one way and two running the other. A list sorted by the first coordinate finds everything between the first pair of streets at once, but then every one of those points has to be checked on the second coordinate, and that can be nearly all of them. The tree does better, because the answer for the first coordinate is a few whole subtrees. So on every inner node, attach a second tree that holds the points below that node, sorted by the other coordinate. A rectangle query reports the points inside both ranges. It walks the first tree as a range query on the first coordinate. In each whole subtree that this walk would report, it runs a second range query for the other coordinate on that subtree’s own tree, and reports what that finds. The first tree hands over about 2 \log_2 n whole subtrees, and each runs its own walk of \log_2 n steps. The query takes O(\log^2 n + k) time for k points reported, and the trees take O(n \log n) memory, since each point appears in one second tree on every level above it [1, Sec. 5.3]. The library’s two-coordinate tree is RangeTree2D.
4.2.4 What a strip can’t tell you
At eleven at night Mia did not want every pharmacy in a strip. She wanted the nearest one, and a strip cannot answer that. A rectangle drawn around her may be empty, or it may hold forty points. Even when the rectangle holds points, the nearest one can lie outside it. A point just outside the middle of one side is closer than a point tucked into a corner inside. Widening the strip until something appears is guesswork. Finding the nearest place needs a structure built for that question.
4.3 The nearest one, now
k-d tree
On her first night, Mia needed the closest pharmacy, and a strip cannot tell her which one it is. The scan finds it by measuring every pharmacy in the city, for every one of the millions of people asking. The k-d tree finds it by measuring about four pharmacies.
Here are twelve points: a (19, 8), b (16, 4), c (5, 17), d (13, 18), e (0, 10), f (2, 19), g (7, 16), h (10, 2), i (20, 20), j (12, 0), k (15, 11), l (18, 7). Cut them in half by turns, first by x, then by y, then by x again. At each cut, sort that region’s points along the axis and split them in the middle. When the count is odd, the left side takes the extra point. The cut goes through the left side’s last point. Stop when every point is alone. Then stand at (1, 13). Which regions must you open, that is, look inside, to be sure which point is nearest, and which can you leave closed?
Ten minutes. You’re done when you can name a region you never opened and say why leaving it closed was safe.
When you left a region closed, you compared two things. One of them was a distance to a point you had already measured. What was the other one, and where on the paper could you see it?
A data set’s real dimension is how many directions its points really spread in. On a map it is two.
4.3.1 Cutting by turns
A map has two dimensions. Two numbers say where a point is, one for how far east it lies and one for how far north it lies. The range tree sorted along one of them. The k-d tree cuts the map itself into regions⬢, using the two dimensions in turns [1, Sec. 5.2], [2]. Cutting space into regions like this is a spatial partition. Each cut is a straight line across one region, at right angles to one axis. It passes through the region’s lower median on that axis, just as each range-tree node split its keys. On one side of a cut, no point lies past the cut. On the other side, no point lies before it (invariant 1). Each side gets half the points, and the left side takes the extra point when the count is odd (invariant 2). Then each side is cut along the other axis, and so on, until every region holds one point.
Here are the twelve points from the exercise. Sorted by x, the sixth point is j, at 12, so the first cut is x \le 12. e, f, c, g, h and j go left, and the other six go right. The left six, sorted by y, are cut at y \le 10, below which sit j, h and e. The right six are cut at y \le 8, below which sit b, l and a. The third round cuts by x again, at x \le 10 and x \le 5 on the left, x \le 18 and x \le 15 on the right. After each of those cuts, one side holds a pair and the other side holds a single point. Four more cuts by y split the four pairs, at y \le 2, y \le 17, y \le 4 and y \le 11. That makes eleven cuts and twelve regions of one point each, in a tree four levels deep. The build itself finishes each left side all the way down to single points before it starts the right side. Figure 4.5 and the widget below number the cuts in that order.
In code, the build is handed one list per axis, each holding the region’s points sorted along that axis.
by_axis[a] lists the numbers of the region’s points in order along axis a, and depth % self.dim takes the axes in turns. goes_left is a set of the left side’s points, so each split asks “is this point on the left?” once per point per list. Splitting a list this way never reorders it, so no region is ever sorted again. The whole build costs O(n \log n) after the first sorts. The rest of the class is in kdtree.py.
Press Next step to build the tree one cut at a time. Before each press, say which axis the next cut uses and which point it goes through.
That was the build. The same tree answers the rectangle query from the last section. Keep track of the rectangle that each region covers. A region that lies wholly inside the query’s rectangle is reported whole, without looking at its points. A region that misses it is skipped. Any other region is opened, and its two sides are checked the same way (KDTree.range). On a plane it opens O(\sqrt{n} + k) regions for k points reported [1, Sec. 5.2].
4.3.2 The closest region first
Now ask the tree for the nearest point. Stand at q = (1, 13). The simplest search goes down to your own region, measures its point, and comes back up. On the way up it crosses a cut only if the circle around you, out to the best distance so far, reaches past that cut. That is the depth-first search, and it never misses the nearest [3]. But it opens regions in the tree’s order, not by how close they are. From q = (1, 13) it measures c, then f and g, and only then the nearest, e. That makes four points. The search below measures two.
A region is a rectangle on the map. For each axis, the search below keeps an offset: how far q lies outside the rectangle along that axis, or 0 when q lies between the rectangle’s two sides. The sum of the squared offsets is the region’s bound, the least squared distance anything inside that region could have from q. It is the squared distance from q to the nearest point of the rectangle. The search gets it from the cuts. Crossing a cut changes only one offset: on the far side, the offset along the cut’s axis becomes the distance from q to the cut.
\text{bound} = \text{offset}_x^2 + \text{offset}_y^2 \;\le\; \operatorname{dist}(p, q)^2 \quad \text{for every point } p \text{ in the region} \tag{4.2}
The library’s search keeps every region it has found but not yet opened in a queue, each with its bound. A queue that always hands out the entry with the smallest key first is a priority queue. The search takes the region with the smallest bound, opens it, and puts its two sides back into the queue with their own bounds. When the region at the front of the queue is farther away than the best point found so far, everything still waiting is farther too, and the search stops. This is best-first search⬢, which opens the closest region first [4]. In the worst case it opens all 2n - 1 regions the build made, from the whole map down to the single points. The scan kept its k best in a priority queue too, with the worst on top, and in code both queues are heaps.
How many points does the search have to measure before it can be sure of the nearest? Here is the search, step by step. The whole map has bound 0, and opening it puts both halves in the queue. The left half holds e, f, c, g, h and j, and it goes in at bound 0, since q stands in it. The right half goes in at (12 - 1)^2 = 121. The search opens the left half and then the region of c, f and g. Then it opens the region of c and f, and then c alone. Every one has bound 0. It measures c at squared distance 32, which is (5-1)^2 + (17-13)^2 = 16 + 16 by equation (4.1). That is the best so far. But the region below the cut y \le 10, which holds e, h and j, is still waiting in the queue at bound (10 - 13)^2 = 9. The bound 9 is less than the squared distance 32, so a point in that region could still be nearer than c.
So it opens the region of e, h and j, then the region of e and h, and then e alone. Each has bound 9. It measures e at squared distance 10, which is (0-1)^2 + (10-13)^2 by equation (4.1). Now the front of the queue holds g and f, each at bound 16, which is more than 10, and the search stops. Behind them still wait j at 90, h at 121, and the whole right half of six points at 121. The nearest is e.
Count it. The search opened eight regions and measured only two points, c and e, and left the other ten unmeasured. It measured c first, but the answer was e. The search found something good early, and the bounds told it exactly how far to keep looking.
A region stays closed only when its bound is already farther than the best point found⬢. Nothing in it can be closer, so skipping it keeps invariant 3. The code does it in a single line.
Two queues run side by side. One holds the regions, nearest bound first. The other holds the k best points, farthest first, so the point to beat is always on top. The stop is strict. A region whose bound equals the k-th best distance is still opened, because a point in it at that same distance would win the tie if that point was stored earlier. This function sits behind k_nearest_with_stats, in kdtree.py.
Play with it below. Drag q around the map, and before each step, say which region opens next. Then name every region that will still be waiting when the search stops.
Five minutes. You’re done when you have called three openings in a row before pressing the button, and named the waiting regions at the stop.
The appendix at the end of the chapter proves that leaving a region closed is safe. The same loop returns later in this chapter, where it walks from point to linked point.
4.3.3 A map of who is nearest
There is another way to prepare the map for nearest-point queries. Give every spot on the map to the point nearest to it. The spots that belong to one point form a region around it, a cell, and the cells tile the whole map. This is the Voronoi diagram of the points. The problem it solves has an old name, the post office problem: which post office is nearest to this house [1, Ch. 7]? With the diagram stored, a query becomes one search for the cell that holds q.
In the figure, a point has only a few neighbors, the points whose cells share a wall with its cell. Those neighbors lie in different directions around it. The graph index in the second half of the chapter comes back to that picture.
4.3.4 How fast, measured
The box’s cost comes from one run. On one thread, the library built a k-d tree over 1,000,000 points spread uniformly over a square, with one point per leaf. Asked 10,000 nearest-neighbor queries, it answered about 830,000 queries a second, measuring 3.93 points per query on average. The tree was 20 levels deep, and each search opened about 30 of its regions.
The build can also stop cutting once a region holds 8 points or fewer. Each leaf then keeps up to 8 points, and opening a leaf measures all of them. A tree built that way runs faster still. The Python printed above cuts down to one point per leaf, as traced in this section.
On the same data, 8 points to a leaf answered 23% more queries a second. The tree is smaller, with about an eighth of the nodes, so a search takes fewer queue steps, and the points of a leaf sit together in memory. Those savings more than pay for measuring about 14 points per query instead of four. On a million points in 20 tight clusters, the speedup was 34%. Each cluster spread about a hundredth of the square’s side around a random center in the same square. On the uniform points, the run’s peak memory fell to under a third, with the points themselves counted.
4.3.5 What the k-d tree relies on
The circle around you, out to the best point found so far, crosses only a few of the tree’s cuts. Most regions sit wholly outside it, and their bounds say so. That is what happens with ordinary points in two dimensions. It also happens with any points that really spread in only a few directions, which is the low real dimension for which the box’s Assumes line asks. A month from now, Mia’s question will put that assumption to the test.
4.4 The part of town she knows
Convex hull
Two weeks on, Mia knows a few places in Zagreb by heart: home, the pharmacy, the school, the café on the corner where the waiter now nods at her. She marks them on the map and stretches a line around them. Inside the line is the part of the city she knows. Her rental site can show only the flats inside it, so it must check thousands of listings against the line.
Eight points: a (1, 5), b (4, 11), c (10, 4), d (0, 7), e (8, 6), f (3, 1), g (9, 12), h (12, 8). Stretch a rubber band around all of them. State a rule that decides, for any point, whether the band bends at it.
Five minutes. You’re done when your rule decides every one of the eight, including a, and you can say how many checks it costs for n points.
The rubber band is the convex hull of the points, the smallest fence with no dents that holds them all. Every point is inside the fence or on it, and the fence turns only at points. A point on a straight stretch of the fence is left out.
Your rule probably looked at pairs of points and asked whether all the others lie on one side of the line through them. That works. There is a faster way, and it builds a fence as you walk. Go left to right and keep the fence below the points seen so far. A new point can push the fence out. Which kept point does it leave inside, no longer a corner?
The algorithm rests on one question asked of three points. Walking from p to q and on to r, do you turn left or right⬢? The answer is the sign of one number, the orientation of the three points:
\operatorname{orient}(p, q, r) = (q_x - p_x)(r_y - p_y) - (q_y - p_y)(r_x - p_x) \tag{4.3}
It is positive for a left turn, negative for a right turn, and zero when the three lie on one line. So its sign says which side of the line from p to q the point r lies on.
Andrew’s monotone chain [5] builds the fence in two halves. Sort the points left to right, so the chain only ever moves right. Walk them in that order to build the lower half of the fence. While the last two kept points and the new one do not turn strictly left, drop the middle one, which cannot be a corner. Then keep the new point. After the last point, walk right to left in the same way for the upper half, and join the two halves. At every moment, what is kept turns left at every point, which is what a fence with no dents does when you walk it counterclockwise [1, Sec. 1.1].
Run it on the eight points. Sorted left to right, they come as d, a, f, b, e, g, c, h. On the lower half, a is dropped as soon as f arrives, because d, a and f lie on one line. Their orientation is \operatorname{orient}(\mathbf{d}, \mathbf{a}, \mathbf{f}) = 0, and that is not a strict left turn. Then b is dropped when e arrives, and when c arrives, first g is dropped and then e. The lower half is d, f, c, h.
Now walk the upper half yourself, back from h, and join the two halves.
Walking back from h, the chain drops c when g arrives and drops e when b arrives. Then it drops f when a arrives, and drops a itself when d arrives. So the upper half is h, g, b, d. Joining the two halves without repeating the shared ends gives the fence d, f, c, h, g, b, counterclockwise from the leftmost point. a lies on the stretch from d to f and is left out, and e is inside.
check_point turns each point into an (x, y) pair, and refuses one that has the wrong number of coordinates or a coordinate that is not a finite number. Sorting by (pts[i], i) puts equal points side by side in the order they were stored, so distinct keeps the first of each. The module is hull.py.
The slow rule from the exercise costs about n^3 checks, one for every pair and every other point. Andrew’s method costs O(n \log n), and the \log n factor comes from sorting the points left to right. Then it walks the sorted points twice: left to right for the lower half of the fence, and back from the right for the upper half. Each walk keeps every point once and drops it at most once. One new point can drop many, but each drop is paid for by the step that kept that point, as in the search chapter’s pay in installments. So the two walks together take steps proportional to n.
Computed with ordinary floating-point numbers, the orientation of three nearly collinear points can come out with the wrong sign, and the fence gets a dent. The library’s orient2d computes the sign exactly, and the appendix shows a case where rounding lies.
With the hull built, checking a flat costs one turn test per edge. The library’s hull lists its corners counterclockwise. A flat is inside the hull or on it exactly when the flat lies to the right of no edge. This side test comes back in the second half, where a random cut sorts points by the side on which they fall.
4.5 What is this all about?
Nearest-neighbor and range queries
Through the scan, the range tree and the k-d tree, Mia has been asking two questions about a fixed set of places.
- Everything in this region. Every stored point inside a strip or a rectangle, a range query.
- The nearest one to here, or the k nearest, a nearest-neighbor query.
The hull answered a different question, about the places themselves: whether a given flat lies inside the part she knows. Its side test returns in the second half.
Other services ask the same two questions. A delivery app asks which couriers are within reach of a restaurant, and which one is nearest. A game asks, many times a second, which players are close enough to see each other. A hospital asks which earlier X-rays look most like a new one. And in two weeks, Mia will ask her phone for a café like the one she left in Lisbon.
4.5.1 What “near” is allowed to mean
Distances and similarity
Ranking needs only an order, and squaring keeps the order of distances, so ranking by distance never takes a square root. Integer coordinates then give integer squared distances, and nothing is rounded at the comparison that decides the answer.
In the second half, as the next section shows, a place becomes a long list of d numbers. The squared distance between two lists adds one squared difference per number, as on the map.
\operatorname{dist}(u, v)^2 = (u_1 - v_1)^2 + (u_2 - v_2)^2 + \cdots + (u_d - v_d)^2 \tag{4.4}
Each list can be drawn as an arrow from the origin, and two places are alike when their arrows point the same way. The arrow’s length is left out on purpose, because likeness lies in the direction. The cosine of the angle \theta between two lists measures how alike they are, and it is 1 when they point the same way. Once every list is scaled to length 1 when it is stored, equation (4.4) becomes
\operatorname{dist}(u, v)^2 = 2 - 2\cos\theta . \tag{4.5}
The nearest by squared distance is the most alike by cosine, so every structure built for distance answers the cosine query unchanged.
Under either meaning, the right answer is the scan’s. It is the stored point nearest by that measure, and on a tie it is the one stored first. Every approximate structure in the second half is measured against that answer.
4.5.2 What has been bought so far
Table 4.2 is the ledger for n points on a map.
| structure | prepare | one query | memory | which queries |
|---|---|---|---|---|
| Scan | nothing | every point | the points | nearest, k nearest, ranges |
| Range tree | sort once | two walks of \log_2 n steps, plus one step per point reported | about two nodes per point. With two coordinates, n \log_2 n copies of points | strips, and rectangles with two coordinates |
| k-d tree | sort once per axis | a few dozen regions, and 3.93 points measured per query, at a million uniform points | about two nodes per point | nearest, k nearest, rectangles |
What a structure saves in one column, it costs in another. The scan costs nothing to prepare, and it costs the most on every query. The trees cost one build, and then each query measures almost nothing. On a map, the k-d tree’s row is very good.
Say Zagreb has a thousand cafés. Describe each with ten numbers you choose: price, noise, coffee, plants, opening hours, and so on. Two cafés are “near” when their numbers are near. Does the k-d tree’s trick still work? Picture a ball around your best café so far, the map’s circle with more numbers. Does it still cross only a few cuts? With five hundred numbers?
Five minutes. You’re done when you can say what the ball crosses at ten numbers, and guess what happens at five hundred.
The eternal silence of these infinite spaces frightens me.
Blaise Pascal, Pensées (1670), no. 206 (Brunschvicg), trans. W. F. Trotter
4.6 A place like this one
The curse of dimensionality
4.6.1 From a map to a list of numbers
A month on, the boy is fine, and Mia knows the way to work, to the school and to the pharmacy without looking. What she misses now is a kind of place. In Lisbon there was a small café two streets from her flat: quiet, strong coffee, plants on every sill, cheap, open late. She doesn’t want the nearest café. She wants that one, here.
On the first night the phone knew exactly what to do. “Nearest” is a question about the map, and the map knows where every place is. “Like hers” is a question about what a place is like, and the map knows nothing about that. So describe every place with numbers: price, noise, how strong the coffee is, how many plants, how late it closes. With ten numbers picked by hand, every café becomes a list of ten. Each number is one dimension, one way in which two cafés can differ, just as east–west and north–south were the map’s two dimensions. Mia’s café is a point in a space of ten dimensions, and so is every café in Zagreb. “A place like this one” has become “a place near this one”, with near measured by angle, as What “near” is allowed to mean set up.
Ten numbers chosen by hand miss most of what made the Lisbon café hers. So the service lets an AI read what people have written about each place and turn it into five hundred numbers. Nobody chose any one of them, and places described alike get lists that point the same way. A list like that is an embedding. Mia’s café, and every café on the continent, is now a point in five hundred dimensions.2
From here on, the methods see only points, and all they find is the points nearest a query. A point can be a café, a word, a song or a film. The AI’s numbers are made so that places alike get points near each other. That puts the places that Mia would like among the near points. An answer is good only if the reverse holds too: points near each other belong to places alike. No method below can check either direction. Each finds the near points it promises, and whether their places are alike rests on the numbers.
The request has changed too. On the first night an almost-nearest pharmacy was a longer walk with a sick child. Tonight, nine good matches out of ten is a good evening. A search’s recall, written recall@10, is the share of the true ten nearest points it hands back, averaged over many queries. It is 1 when all ten come back and 0.9 when nine come back. From here on, every index in the chapter is measured by two numbers, its recall and how many queries a second it answers.
4.6.2 When the tree measures everything
The k-d tree got Mia through the first night, so ask it the new question. You guessed, in the last Try first, what its ball crosses at ten numbers and at five hundred. The library’s k-d tree was measured on that question, by counting the share of all points that one search measures as the number of dimensions grows. Among 100,000 points spread evenly at random, the k-d tree’s search measures 0.75% of the points at 8 dimensions, 24.46% at 16, and from 32 up nearly every point. The first 100,000 GloVe words, each squeezed to fewer numbers by the projections of the next subsection, behave the same way. The tree that found Mia’s pharmacy by measuring four places in a million finds her café by measuring all of them, which is slower than a plain scan. The cuts that worked on the map fail in the space of what places are like.
The search was best-first for the ten nearest, one point per leaf, and every share is averaged over 200 queries. For points spread evenly at random, the search measured 0.02% of the points at 2 dimensions, 0.07% at 4 and 0.75% at 8. It measured 24.46% at 16 dimensions and 99.86% at 32, and every point from 64 up. For the GloVe words, it measured 0.02% at 2 dimensions, 0.08% at 4 and 1.26% at 8. It measured 26.21% at 16 dimensions, 94.33% at 32 and 99.82% at 64, and every point at the words’ full 100 dimensions. The words were squeezed to their projections on a few random directions, which the next subsection explains.
Mia’s ten hand-picked numbers sit between the measured 8 and 16 dimensions, so the tree would measure between a little under one in a hundred and one in four. At five hundred, the tree measures every point, as the scan does, which takes about nd steps. On top of that it keeps a queue of up to 2n - 1 regions. On Fashion-MNIST, a set of 60,000 photographs of clothes at 784 numbers each, that made the tree more than ten times slower than the scan.
In many dimensions, space stops behaving the way that your intuition expects. That intuition was trained on two and three dimensions, and every idea built on it so far stops working. This is the curse of dimensionality [8, p. ix]. Figure 4.14 shows four ways in which such space is odd, using 4,096 points spread evenly in a cube and one query. The first two panels are why the tree fails, and the third shows it failing. The last one gives the tool that the rest of the chapter uses.
Slide the figure to ten, as many numbers as the lists picked by hand, and then to five hundred.
Volume runs away from the center. The square stands for the cube, which is the fixed reference. Its side stays 1 at every dimension, and both balls are measured against it. Blue is the largest ball that fits inside it, and red is the smallest ball around it. Blue still touches the middle of every face, yet its share of the cube falls from 79% at two dimensions to 0.25% at ten and 1.9 \times 10^{-68} % at a hundred. Red still touches every corner, yet along an axis it reaches ten times as far as blue at a hundred dimensions.
Most of a ball’s volume lies in a thin outer shell. Picture a third ball that the figure leaves out. Take any ball and shrink it around its own center until it holds half its volume. Call that its half-volume ball. Its radius is 0.71 of the full radius in two dimensions, 0.93 at ten and 0.993 at a hundred. As the dimensions grow, the two radii almost meet, and at a hundred dimensions half the volume sits in a shell only 0.7% of the radius thick.
The drawing is a flat picture of a shape with many directions, so it cannot keep everything. It keeps true lengths in two directions, toward the middle of a face and toward a corner, because those two show best what changes as the dimensions grow. Every direction between is bent to fit the page, which is why the balls stop looking round.
Distances become similar. A squared distance adds up one small squared difference per dimension, by equation (4.4), and a sum of many small random parts lands close to its average. So as the dimensions grow, the distances from one point to all the others come out nearly the same⬢. From the figure’s query, the nearest of the 4,096 points sits at 0.01 of the farthest distance at two dimensions, and at 0.66 at a hundred. For many kinds of random data, the distances to the nearest and the farthest point differ less and less, relative to their size, as the dimensions grow [9], [10, Thm. 2.1]. Clustered data need not bunch this way.
The tree ends up measuring everything. The tree leaves a region closed only when it can tell that every point in that region is farther from the query than the tenth-nearest point found so far. On the 2D map, the ten nearest points were close to the query, so most regions stayed closed. A region is a box like the panel’s cube. In many dimensions, the largest ball that fits inside it fills a smaller and smaller share of it, as the first panel showed. To catch the ten nearest points, the ball around the query has to reach far beyond the query’s own region. On the way it crosses many cuts, and the tree has to open every region beyond them. On the figure’s 4,096 points, the k-d tree measures 16 points at two dimensions, 1,055 points at ten dimensions, and every point from 24 dimensions on. In more dimensions, every point is about as far from the query as every other, so no region is clearly too far, and the tree opens them all. There a linear scan does better, since it measures every point without the queue.
Angles become nearly perpendicular. Pick directions at random and measure the angle between every two. In two dimensions they spread evenly. At a hundred dimensions, 92% of the figure’s pairs lie between 80° and 100°, close to 90° [11, Thm. 2.8, §2.4.2].
Real data often cluster, and the points of a cluster often spread in only a few directions. Their real dimension is then low, whatever the count of numbers, and a tree can still rule regions out [10, Ch. 2–3]. GloVe’s words spread in too many directions, so at their full hundred numbers the tree measured every word. As its box’s Assumes line warned, it was slower than a scan, but never wrong.
In many dimensions, no method is known that finds the exact nearest for general data in much less than one measurement per point, even after any reasonable preparation [12, Sec. 1]. The frontier map says why. So the methods below do approximate nearest-neighbor search. They give up exactness and measure how often they are right.
4.6.3 Random directions
Measuring a squared distance takes a few steps per coordinate, so comparing a point with five hundred coordinates against a million others takes billions of steps. Could each point carry fewer numbers that still keep its distances? The last panel of Figure 4.14 gives the tool: random directions.
A point’s projection on a direction is how far the point reaches along it (Figure 4.15). Take a point of length 1 with a hundred numbers. In many dimensions, random directions are nearly perpendicular, so they act like the axes of a frame turned at random, and each projection catches about a hundredth of the squared length. Squaring the projections, averaging them and multiplying by 100 gives a guess at the squared length, which is 1.
One projection guesses wildly, but the guess settles as projections are added (Table 4.3). The reason is the one that made distances bunch: a sum of many small independent pieces stays close to its average. A squared distance adds one piece per coordinate in equation (4.4), and this guess adds one piece per projection.
| projections | five draws | typically off by |
|---|---|---|
| 1 | 0.13, 0.07, 1.45, 0.20, 1.76 | 1.42 |
| 20 | 0.67, 0.51, 0.73, 0.65, 0.82 | 0.30 |
| 80 | 0.98, 1.05, 1.06, 0.92, 0.85 | 0.16 |
Why random directions, and not twenty you pick? Any fixed choice fails for some data. Keep twenty chosen coordinates, and two points that differ only in the other eighty look the same. Random directions are drawn without looking at the points, so no data can be laid out against them in advance, and what they keep holds for any data, the worst included. Fitting directions to the data is another tool, and the spectral chapter builds it.
Projections keep distances as well as lengths, because a distance is the length of a difference, and the projection of a difference is the difference of the projections. Johnson and Lindenstrauss showed that a constant times \log n / \varepsilon^2 random directions keep every distance among n points within 1 \pm \varepsilon, with high probability, however many coordinates the points have [13], [14]. The appendix proves it. For a million points within 10%, the guarantee asks for more than ten thousand directions. GloVe’s points have only a hundred numbers each, so here the guarantee buys nothing.
The next section keeps only the sign of each projection, and the sign says on which side of a random cut the point is.
4.8 Ask the locals
Graph index
In her first weeks Mia found most things by asking. The woman at the pharmacy sent her to a bakery by the market. The baker said the café by the river was quieter. The river café’s owner named a third, and that one had plants. Nobody she asked knew the whole city, and each of them knew a few places like their own. Each answer took her a step closer to what she wanted. There is something smart and effective in this practical wisdom, and the graph index copies it. Every point is linked to a few points near it, and a query asks its way along the links, and each step goes to the linked point nearest q.
The k-d tree used the points and cut where they are, but in many dimensions its cuts rule nothing out. LSH ignores the points. Its cuts are random, so its promise holds for any set of points, even the worst, but its buckets are untidy and it needs many tables. A middle ground uses the points more than LSH does, through who is near whom.
Twelve points each know the points to which they are linked (Figure 4.21).
Start at a and walk toward q, always stepping to the linked point nearest q, and stop when no linked point is nearer than where you stand. Where do you stop? Is it the nearest point? Which one link would have let you reach it?
Ten minutes. You’re done when you have the stuck walk, the true nearest, and one link that unsticks it.
To check distances by hand: a (2, 15), b (17, 19), c (4, 20), d (6, 6), e (18, 1), f (9, 18), g (1, 10), h (3, 9), i (15, 8), j (19, 3), k (8, 5), l (10, 17).
In the exact case, you could link each point to its neighbors on the map of who is nearest, the dashed links of Figure 4.10. Points and the links between them make a graph, the subject of the graphs chapter. Walk it, always stepping to the linked point nearest q. That walk would always find the exact nearest neighbor [10, Sec. 6.2]. When no linked point is nearer to q than the point where the walk stands, q lies in that point’s own cell, so that point is the nearest. But distances bunch in many dimensions, and for points spread out in hundreds of dimensions a point’s cell can border almost every other cell. That graph would be nearly complete, and each step would be a linear scan again.
Real data are rarely the worst case. They come in clumps, and through links to a few near points a walk can reach the rest of its clump, so a few links can be enough [24]. So, as an approximation, link every point to at most M points near it, 16 in the library. A query walks this graph the same way and stops when no link leads nearer. The query may stop at the nearest point, or only close to it. The graph index gives up LSH’s promise for the worst case and wins speed on the clumpy data that are common.
The first two invariants make the graph flat, a single layer of links. The third adds the layers, which come later, once the flat graph works.
Which M links a point keeps decides whether a walk can leave a clump. If it keeps only its nearest ones, they all lie in its own clump, and a walk that enters the clump finds no link that leads out. Which of a point’s nearest neighbors tell you nothing new?
4.8.1 Keep the neighbors that tell you something
Figure 4.22 uses a separate example, with a point a and six candidates for its neighbors, b to g. a may keep at most M = 3 of them. Go through the candidates nearest first, by squared distance from a: b 2, g 13, d 20, c 37, f 45, e 61. Skip a candidate when a neighbor already picked is closer to it than a is.
- b is the nearest, so a picks it.
- g is at squared distance 13 from a and 13 from b. b is not strictly nearer to g than a is, so a tie keeps g.
- d is at squared distance 20 from a, but only 10 from b. A walk that reaches b is already close to d, so b covers that direction, and d is skipped.
- c is at squared distance 37 from a, 53 from b and 82 from g. Nothing picked is nearer to it than a is, so a picks it.
a has now picked its three neighbors, b, g and c. The last two candidates, f and e, are never looked at. When links are kept this way, a point’s few links point in different directions⬢, and a walk that arrives there can leave toward wherever the target lies. A graph on which such a walk always reaches the nearest is navigable.
In the code, the candidates arrive nearest first, each as a pair of its squared distance and its point number. The whole module is in hnsw.py.
4.8.2 Walking toward the target
Suppose the graph index is already built, and the library has linked these twelve points by the rule above. A query walks it from a toward q = (12, 0), always stepping to the linked point nearest q. This is the greedy walk, the walking downhill of the box’s Assumes line. Here it goes a → d → k and stops there. k links only to d and i, and both are farther from q than k is. The nearest point is e, one link beyond i. One more link would have unstuck the walk, either d–e or k–e, and the insertion further down shows how d lost its link to e.
So keep more than one point in hand. A beam of width 3 keeps the three best points seen so far. The beam expands its points nearest first. To expand a point, it measures all the point’s neighbors and keeps any that beats the worst of the three. It stops when the nearest point not yet expanded is farther than the worst of the three. Here it ends with e, k and j, and finds e.
This is best-first search again, the k-d tree’s queue with the regions replaced by points. The k-d search never skips a nearer point, because a region’s bound is never more than the distance to any point inside it. But a point’s distance says nothing about the points beyond it, so the beam can stop before the nearest.
Press q = (12, 0), set the beam to 1, and step. Then set it to 3 and step again, and before each step, say which point it expands next.
Here dist measures a point’s squared distance to the query, the beam’s width is ef, and lc is the layer, always 0 on a flat graph. found keeps its pairs negated, so its heap has the worst point on top.
The search ends with one more step, finish, which sorts the beam by distance and keeps the k nearest. With ef set to 1 the beam is the greedy walk.
4.8.3 Building it one point at a time
The graph is built by inserting the points one at a time, and each insertion uses the two pieces you already have. A beam finds the new point’s candidates, and the picking rule chooses among them. In the library’s graph a new point picks M neighbors, and each picked neighbor links back to the new point. Every point’s neighbor list on the bottom layer may hold up to 2M, so links back from later points have room. When a list grows past its limit, its owner picks again, by the same rule, from the points it now holds.
Watch i at (15, 8) enter the graph as its ninth point. Here M = 2, so a neighbor list may hold four links. The beam finds i’s candidates, nearest first by squared distance: e 58, d 85, b 125, f 136, h 145, g 200, a 218, c 265. For its two neighbors, i picks e first and then d, which is at squared distance 169 from e and only 85 from i.
Now each picked neighbor links back to i. e had one link, to d, and gets i as its second. d already had four links, to a, e, g and h, and i makes a fifth, one too many. So d picks again from its five, nearest to d first by squared distance: h 18, g 41, i 85, a 97, e 169.
- h is the nearest, so d keeps it.
- g is at squared distance 41 from d but only 5 from h, so d skips it.
- i is at squared distance 85 from d and 145 from h, so d keeps it.
- a is at squared distance 97 from d but only 37 from h, so d skips it.
- e is at squared distance 169 from d but only 58 from i, so d skips it.
d ends with h and i. A re-pick can shrink a list, but never grows it past the limit. One of the links that d dropped was its link to e, the one that the stuck walk needed.
Look at e and d afterwards. e still links to d, but d no longer links to e. Links are made in both directions, as the box says, but a re-pick can drop one of them. That is why Figure 4.21 draws e’s link to d with one arrowhead.
Press Next step to watch the twelve points go in, from a to l, with M = 2 and the top layers of Highways, below, drawn from seed 2. Before each step, say which points the new one keeps, and whether any list overflows. The ninth insertion is the one above, number for number.
The code already handles the layers of the next subsection. Its loop runs over every layer that the new point reaches, from the top one down. On a flat graph that is only layer 0, and the search starts from entry_points, which holds the first point inserted.
The lines left out give the new point an empty list on each of its layers. For the very first point, they make it the entry and stop there. Otherwise they walk greedily down from the top layer to the first one on which the new point is.
4.8.4 Highways
So far every walk starts at the first point inserted, wherever that is. In a city, nobody walks to the other side of town through the side streets. You take a highway most of the way, and you take the side streets only at the end.
The library’s graph builds its own highways. Each point draws its top layer at random when it is inserted, and few draw a high one. Each layer up keeps a random few⬢ of the one below, about one point in M. A point is linked on its top layer and on every layer below it. A search starts at the single entry point on the top layer. On each layer above the bottom it walks greedily until it is stuck, then drops to the layer below where it stands. It runs the beam only on the bottom layer, among all the points. This is the hierarchical navigable small world graph, HNSW [25]. The same layering over sorted keys is the skip list, in the search chapter’s frontier map.
Build the twelve points this way, with M = 2 and the top layers drawn from seed 2. d alone reaches layer 2 and becomes the entry. Layer 1 holds d, a, b, c, g, h and j, linked as Figure 4.27 draws them. Layer 0 holds every point, with the same links as the flat graph from the start of this section. Walk to q = (12, 0) again. On layer 2, d has no links, so the walk stays at d, at squared distance 72. On layer 1, d’s links are h at squared distance 162 and j at 58, so the walk steps to j. From j, the links lead to d at squared distance 72 and b at 386. Both are farther from q than j, so the walk drops a layer at j. On the bottom layer, a beam of 3 starts from j and ends with e at squared distance 37, k at 41 and j at 58, so the search returns e. The highway moved the start from a to j, close enough that even the greedy walk would now reach e, since j’s links include e.
On GloVe, the layered graph and the flat one reach the same recall at the same speed, within a few percent at every beam width. That holds with M = 16 and a beam of 200 while building, over all 1,183,514 words and all 10,000 queries. Building the same layered graph a second time changes its speed by a few percent as well. At this size and in a hundred dimensions, the highways buy nothing that can be measured.
Munyampirwa and co-authors found the same on their data, and traced it to hubs. In many dimensions a few points turn up in almost every list, and they are highways already [26]. The library ships the layers anyway, as the standard design does, since the flat graph saves so little.
4.8.5 What it costs
The beam’s width, ef, is the setting a service tunes. The default graph has M = 16 and was built with a beam of 200. Table 4.6 shows what each width buys on GloVe.
| ef | 10 | 40 | 160 | 640 | 1,280 | 2,560 |
|---|---|---|---|---|---|---|
| recall@10 | 0.467 | 0.699 | 0.849 | 0.936 | 0.964 | 0.983 |
| queries a second | 12,168 | 4,712 | 1,413 | 416 | 222 | 118 |
From a beam of 10 up to 640, each fourfold widening leaves about a third of the speed, and each doubling after that leaves about half. Each widening buys less recall than the one before.
The graph’s other setting is M. A larger M gives each point more neighbors, which makes the graph faster at high recall but takes more memory and longer to build. Figure 4.28 draws it at M = 8, 16 and 32.
At LSH’s recall of 0.976, read between two measured beam widths, the graph answers more than eight times as many queries a second as LSH.
Every measurement so far kept each point’s list of numbers, its vector, in memory. On a phone asks what happens when the vectors don’t fit.
Mia’s phone can’t hold five hundred numbers for every place on a continent. The library keeps every number in 8 bytes, so GloVe’s hundred numbers take 800 bytes a word, and they take 947 MB for all the words. So keep one bit per number instead.
First rotate every vector at random around the data’s center, so that no coordinate is special. Then keep only the sign of each rotated number, SimHash’s bit again, with the cuts now at right angles to one another. Rounding numbers to a few bits like this is quantization.
Bits alone get distances wrong, so keep two more numbers per vector to correct them. With those, RaBitQ [27] estimates every distance without bias, which means it is right on average. The bits and the two numbers make a vector’s short code, which takes 32 bytes instead of 800. The 100 bits fill two 64-bit words, 16 bytes, and each correcting number takes 8. The walk ranks points by these estimates and measures exactly only the ef points it holds at the end.
When the vectors fit in memory, the estimates lose recall, and the beam must be wider to make up for it. So the full vectors are up to about twice as fast at equal recall. With memory capped at 450 MB, a little under half of what the vectors need, the walk reads the full vectors back from the disk, and the codes are about three and a half times faster.
The paper uses its error bound to decide which points to re-check exactly, and proves that safe for an index that groups the vectors into clusters. That proof doesn’t carry over to a graph. Short codes built from clusters return in the spectral chapter.
4.8.6 What it cannot promise
The index returns up to k points, nearest first, each measured exactly. Nothing in the design says the walk reaches the true nearest, and for this kind of graph no such guarantee is known. For several popular graph indexes, inputs can be built on which the time that a query needs to reach reasonable accuracy grows in proportion to the size of the data, as a scan’s time does. HNSW, the design built in this chapter, is among them [28], a result to which the search chapter’s frontier map also points. So recall is measured instead, on a named dataset, and it holds for that data only. When the walk stops at a point that is not the nearest, the answer is wrong and looks exactly like a right one.
The library states each design in the proof assistant Lean, with one file per structure, KDTree/Spec.lean and GraphIndex/Spec.lean for the two halves of this chapter.
For the k-d tree, the build is proved to keep both of its cut invariants, and the search is proved to return the k nearest on any points.
For the graph, every insertion is proved to keep the limit on every list and the layers nested. That proof does not depend on the walk being any good. Every choice of neighbors is proved to follow the rule. And the search’s last step is proved to return the beam’s k nearest, each measured exactly. Whether the walk finds the true nearest is not a theorem but a measurement, and that measurement is recall.
The first half’s answers are proved to be the nearest. The second half’s answers are measured against the nearest. And no proof says whether five hundred numbers from an AI capture what Mia’s café was like. Whoever asks has to judge that.
4.9 ✎ When assumptions change practice
Every number that a box gives holds only while two conditions hold: the one in its Goal and the one in its Assumes line. Each check below changes one of them.
A service holds ten million descriptions, 768 numbers each, and must return the ten most alike in a few milliseconds. A colleague proposes a k-d tree, “because it measured about four points out of a million, on a map of points spread evenly”. Say whether it fits, and what you would measure first, on which data, before anyone writes code.
This check needs the fold On a phone in the graph index’s section, so read it first. The same service moves to phones. The vectors no longer fit in memory, and most of them stay on the disk. Which of the chapter’s measurements stop describing it, and which design comes out ahead instead? Say what the short codes of On a phone cost when the vectors do fit, and why that trade turns from a loss into a gain when they don’t fit.
The places start to move. Delivery drivers each report where they are every few seconds, and a restaurant asks for the nearest five. For each structure in the chapter, say which condition of its box this breaks, in its Goal or its Assumes line, and whether the answers become slow or wrong. Then say which structure you would rebuild from scratch every few seconds, and what that costs.
4.10 ◆ What these are actually made of big picture
This chapter built a scan, two trees, a fence, a hash and a graph. Opened up, they are made of a handful of small ideas. Several of them turn up twice inside the chapter, and you met some of them earlier in the book, doing other jobs.
Scan = measure everything. No preparation, nothing to keep true, and every query measures every point. Every structure after it is a way not to measure everything, and every one of them is checked against it.
Range tree = spatial partition + a few whole pieces. Spatial partition: sort once and split the line in halves, so any range is a few whole subtrees and two paths. A few whole pieces: each subtree between the two paths is reported without testing any of its keys.
k-d tree = spatial partition + bound and prune + best-first. The partition cuts the map itself, by turns. Bound and prune: a region’s bound is never more than any of its points’ distances, so a region whose bound is already too far stays closed. Best-first: open the region with the smallest bound next, so a good answer comes early and the bounds stop the search soon after.
Convex hull = which side + keep an invariant. Which side: the sign of one number says whether three points turn left. Keep an invariant, here a loop invariant: the kept chain turns left at every point, and each new point restores that before the next one comes.
LSH = which side + random directions + collide on purpose + check every candidate. Which side is the hull’s question again, asked of a cut through the origin. Random directions: the cuts know nothing about the points, so no set of points can fool them every time. Collide on purpose: where an ordinary hash scatters, this one files near points together. Check every candidate: a shared bucket only makes a point a candidate, and only an exact distance decides, as Rabin–Karp’s match was checked against the text in the strings chapter.
Graph index = navigable graph + best-first + keep it in layers. Navigable graph: a few links per point, leading off in different directions, so a walk that always steps nearer gets somewhere. Best-first again: the beam is the k-d tree’s queue, with points where the regions were. Keep it in layers: a random few on each layer up, so a search starts on a small layer and ends on the full one, as the LSM-tree in the search chapter put a small table in front of its large levels. On a phone, the graph index with short codes adds random directions, since it rotates every point at random and keeps one bit per number. The walk compares candidates by distances estimated from those bits, and at the end it checks every candidate it kept, measuring each exactly.
Some of these parts can be swapped for another part that does the same job. Figure 4.30 shows three, each beside the choice that this chapter made. The k-d tree could search depth-first instead of opening the closest region first, and the graph index could keep one flat layer instead of layers. Both keep the promise and change only how fast, or how often, the true nearest is found. The third swap breaks it. If LSH ranked its candidates by the buckets they share instead of measuring them, the point reported might not be the nearest of the candidates.
4.10.1 Choosing one, under pressure
The parts decide what a structure can promise, so choosing a structure means choosing its parts. Every structure here makes a promise. When what a right answer needs breaks, the answers are wrong. When what makes it a good choice breaks, the answers are still right, but you are paying for the wrong thing. Each row is a short contract, in the contracts chapter’s sense. The last column is its failure mode, what you see when either condition breaks. In most rows you see no error at all, just an answer that looks exactly like a right one.
| structure | a right answer needs | it is a good choice when | if it breaks |
|---|---|---|---|
| Scan | nothing | the points are few, or change all the time, or are asked about once, or an index would still measure a large share of them | it is never wrong, only slow |
| Range tree | the points don’t change after the build | “everything in this strip”, or in this rectangle with two coordinates, is asked often | a point added after the build is never reported |
| k-d tree | the points don’t change after the build | the nearest point on a map, asked millions of times, where the points really spread in only a few directions | a point added after the build is never found. With many real dimensions it stays right but slows down, and on points spread evenly it measures nearly every point at 32 numbers and every point from 64 |
| LSH | cuts drawn at random, knowing nothing about the points, for its miss rate to hold | you need a risk bounded in advance: a nearest within the angle you name is missed at most as often as you set | a farther point, silently, when the true nearest shares a bucket in no table |
| Graph index | walking downhill through the neighbors leads to the nearest | millions of points, hundreds of numbers each, at a recall you choose and measure | a farther point, silently, for instance when a condition like open now removes points through which the walk needed to pass |
4.10.2 What each one costs
This finishes the ledger of What has been bought so far. There are n points of d numbers each, and k of them are reported. LSH keeps L tables with keys of K bits, and the graph keeps M links per point.
| structure | prepare | one query | memory | measured |
|---|---|---|---|---|
| Scan | nothing | \Theta(nd) | the points, \Theta(nd) | about 39 queries a second, on GloVe, 1,183,514 words of 100 numbers, the first 1,000 queries |
| Range tree, two coordinates | O(n \log n) | O(\log^2 n + k) | O(n \log n) | not measured |
| k-d tree, one point per leaf | O(dn \log n), a sort per axis first | O(n) regions in the worst case, all 2n - 1 | \Theta(n) nodes, plus the points | 3.93 points measured per query, about 830,000 queries a second, on 1,000,000 points spread evenly over a square |
| LSH, 8 bits, 64 tables | \Theta(nLKd), a key per table per point | \Theta(LKd) for the keys, plus d per candidate | \Theta(nL) entries, plus the points | 39% of the data measured, recall 0.976, less than half the scan’s speed, on GloVe, the first 1,000 queries |
| Graph index, M = 16 | no proven bound, each insertion a beam search | no proven bound | \Theta(nM) links, plus the points | more than eight times LSH’s speed at LSH’s recall of 0.976, on GloVe, all 10,000 queries |
| Graph index with short codes | a code per point | the graph’s walk on the codes, then an exact check | 32 bytes a point, beside the graph | about three and a half times the full vectors’ speed at equal recall, when the vectors must be read from disk, on GloVe, 200 queries at each beam width, with the process held to 450 MB |
Only the top half of the table is exact. The scan, the range tree and the k-d tree return the true answer every time, and their costs differ. LSH and the graph index return an answer measured exactly. How often that answer is the true one is one more number, recall, and it holds only for the data on which it was measured.
The k-d tree’s row is a fact about a map. On the first 100,000 GloVe words, at their full hundred numbers, the same tree measured every word. Fashion-MNIST holds 60,000 photographs of clothes at 784 numbers each. Over its first 1,000 queries, the tree ran more than ten times slower than the scan. Each row of this table holds only for its own data.
Memory decides the last row. With every vector in memory the full vectors walk faster. With the vectors on the disk, the codes walk faster.
Fewer distances is not less time. LSH measured 39% of GloVe and still ran at less than half the scan’s speed on the same queries. Count distances to compare designs. Time them before you choose.
4.10.3 Where they run
Each of these runs inside programs in daily use.
| structure | where it runs |
|---|---|
| k-d tree | the nearest-neighbor routines of scientific libraries, such as SciPy’s KDTree |
| R-tree, a B-tree for rectangles | the spatial indexes of databases, such as PostGIS |
| Convex hull | geometry libraries, such as SciPy’s ConvexHull, which calls the Qhull library |
| Graph index | vector search in databases and search engines, such as pgvector’s HNSW index and the vector search of Lucene |
| Short codes with an exact check | vector search libraries, such as Faiss, which offers RaBitQ’s codes |
The range tree is missing from the table. Databases answer strips and rectangles with B-trees and R-trees. Those trees keep their nodes in blocks the size of a disk page, as the B-tree in the search chapter did, and they can change after the build.
4.10.4 The same ideas, over and over
| primitive | where else it turns up |
|---|---|
| spatial partition | quadtrees behind map tiles, octrees in 3D graphics, the grids of a physics simulation |
| bound and prune | alpha–beta pruning in chess programs, the solvers of integer programs |
| best-first | Dijkstra’s shortest paths, A* in games, the graph index’s beam |
| which side | the SimHash bit, a linear classifier’s decision, the exact tests inside mesh generators |
| random directions | the sketches of the streaming chapter, randomized methods for large matrices, RaBitQ’s rotation |
| collide on purpose | catching spam sent in many slightly different copies, the buckets of MUVERA, which describes a document by several lists, in the frontier map |
| check every candidate | Rabin–Karp’s match in the strings chapter and the exact recomputation behind orient2d. The Bloom filter in the search chapter made the opposite choice |
| navigable graph | small-world networks, routing between machines on a network |
When a problem arrives that no structure here fits, ask which of these ideas it needs. What can be cut into regions? What bound can rule a region out? Which question is answered by a sign? And what can you check exactly, once something cheaper has narrowed the field?
4.11 ◆ Where that leaves the pharmacy big picture
Months on, a neighbor knocks late in the evening. The neighbor’s daughter has a fever. Mia types pharmacy, open now, and five pharmacies appear before her thumb leaves the screen. She knows three of them by name now, and she knows which one has the short queue. The city has stopped being foreign.
The phone answered her two questions in two different ways. On the first night it answered exactly. Nearest meant nearest, and the map made that cheap, because one measurement told the search about a whole region. A month later it answered well enough. It returned nine or more of the ten places most like the café in Lisbon, at a speed that the service could afford. In five hundred dimensions one measurement rules out almost nothing, so the conclusions that the map gave away free had to be bought back, with tables and candidates in LSH and with links and a wider beam in the graph. The share bought back is measured as recall.
Open now in her search is a filter. On the map a filter never makes the answer wrong. A k-d search can measure a closed pharmacy and pass over it, and every bound still holds, so the answer is still the nearest open pharmacy. On the graph a filter breaks the walk. If the walk skips the closed places, the paths that ran through them are gone. If it walks through them, the beam fills with places it may not report. The walk still breaks there today, and the frontier map below picks the problem up.
Most of what this chapter named is what the rest of the world calls it too: range query, nearest-neighbor query, range tree, split node, k-d tree, best-first search, Voronoi diagram, convex hull, orientation, embedding, recall, locality-sensitive hashing, SimHash, candidate, HNSW, beam, priority queue, greedy walk, curse of dimensionality, quantization. A few words were this chapter’s own. Projections onto many random directions, once scaled, together make a random projection. A place like this one is approximate nearest-neighbor search. The real dimension is the intrinsic dimension. The locals are a graph index, and its highways are the layers of HNSW. The picking rule is what HNSW’s paper calls its neighbor-selection heuristic. They were scaffolding, and the ideas underneath keep their standard names.
Near is not the same as equal. For a quotation, a citation, or a check that a model copied its training text, a passage that means the same is not evidence. Only an exact match is evidence, and that is the strings chapter’s job.
In two dimensions you can afford exact. In five hundred you choose how wrong you are willing to be, and measure it.
4.12 ✎ Hands-on projects practice
Projects come first. In each one you build something, measure something, or explain something to another person. They have no single right answer, so judge them against the checks each one asks you to build. After them come the self-check problems, numbered exercises that each come with an answer you can check. Do some of each. The exercises show what you know, and the projects show what you can do. Where a project needs code, let an AI write it, and the times given assume that the AI writes it. Three things are still your job when the AI helps. You say what the code must do, build the check that shows it does so, and judge what comes back. In this chapter that check is almost always the same. Compare with the scan, and say on what data you compared.
Project 1 · the k-d tree · hard · ~2 hours
Build Mia’s “near me”. Take the pharmacies, or the cafés, of a city you know from a public map extract, or scatter synthetic points over a square and say that you did so. Have an AI build a service that answers “the nearest one to here” with a k-d tree. Before you ask, write down these checks.
- on a thousand random queries, the answer is the scan’s answer, and a tie goes to the lower number;
- a map with no points answers nothing;
- a query asked exactly at a point answers that point, or the lower-numbered of two points in the same spot.
Run the checks before you believe a single answer. Then count the points measured per query, and put that number beside the scan’s n. Say on what points you counted.
Project 2 · the range tree · ~1 hour
Pay for the second coordinate. Have an AI build the two-coordinate range tree from Two coordinates at once. Specify the check first. For every rectangle you try, the tree returns exactly the points that a plain filter over all the points returns, each of them once. Then, for 1,000, 10,000 and 100,000 random points, predict how many entries the tree stores, counting every point once in every second tree to which it belongs. Count them, put each count beside n \log_2 n, and say in one sentence what the second coordinate cost and what it bought.
Project 3 · the convex hull · ~45 min
Your rule, as a test. Turn the rule you wrote in the hull’s Try first into a slow check. A pair of points is an edge of the fence when every other point lies on one side of the line through them. Have an AI write Andrew’s chain. Then break it on purpose, twice. First, keep a point when the turn is a left turn or straight (>= 0 instead of > 0). Second, compute the turn in plain floating point, on points a rounding step apart near a line, as in When the sign lies. Say which of your tests catches which broken version, and whether either escapes all of them.
Project 4 · the curse · ~1.5 hours
Measure the curse on your own data. Pick a dataset of lists of numbers you care about: photos, songs, sensor readings, word vectors. Measure the share of points that a k-d search for the ten nearest measures, as you keep more and more of the numbers, the way Figure 4.13 does. Then take points spread over a plane, two numbers each, and turn them into lists of 100 numbers by one random rotation, so they still lie on a flat sheet. Before running either, predict both curves. Hand in the two curves, your predictions, and one paragraph on the difference between how many numbers a point has and in how many directions the points really spread.
Project 5 · LSH · ~1.5 hours
Tune the two settings. On the first 100,000 GloVe words, measure recall@10 and candidates per query for keys of 4, 8 and 12 bits combined with 4, 16 and 64 tables, which makes nine settings in all. The true ten nearest come from the scan over those 100,000 words, which you run first. Before measuring, predict which of the nine settings will reach recall 0.9, from equations (4.8) and (4.9). Hand in the grid of measurements beside your predictions, and say which setting you would ship, and why.
Project 6 · the graph index · ~1 hour
Do highways pay? Build the graph index flat and with layers on 10,000 points, once with 2 numbers each and once with 100, and measure both at the same recall on your own machine. Say in one sentence whether your measurements agree with Highways, and if not, what differs between your data and GloVe.
Project 7 · filters · ~1 hour
“Open now”. Build a graph index over your places, then close half of them at random. Walk the same graph without ever stepping on a closed place, and measure recall@10 at beam widths 10, 40 and 160, against the scan over the open places only. Then walk through closed places but never report them, and measure again. Hand in both tables and one paragraph on why the first walk breaks.
Project 8 · design · hard · ~3 hours
Design an index for “places like this one”, with an AI. Mia’s service answers “places like this one” over places that are each a list of numbers, and it has a memory budget. The scan’s ten nearest are the reference. Find a design that computes at most half the scan’s distances per query, finds on average at least nine of the true ten nearest (recall@10 of at least 0.9), and stays under the memory cap. It has to do all three on every set of points on which you test it. The AI writes the code. You specify, check and judge.
The companion library holds a bench for this problem. Every set in it has 10,000 points of 100 numbers each, drawn from a seed. The sets come in two families. One is clustered. The other is skewed and built to be hard, with clusters of very different sizes, near-copies of points, and queries that fall between clusters. Each set comes with 100 queries. The bench charges one unit for every distance and every inner product that a design computes, for whatever reason it computes them. The bench’s cap counts the index alone, which may hold at most as many numbers as the stored points themselves have.
- Write the problem first. Write the top half of a box: the goal, the promise, the cost and the assumptions. The promise says what every answer must be, with recall measured against the scan’s ten nearest. The cost counts distances and inner products per query, plus memory. Leave the idea and the invariants empty. They are what the search will find.
- Check the promise where a machine holds it. Read
Contractin the library’slean/AlgoDesign/Geometry/Workbench/Spec.lean, what every answer owes and how recall is counted. Check that each line says what your promise says, and change the contract where a line does not say what your promise says. - Hand the top half to an AI, with the bench,
python/algodesign/geometry/workbench.py. A design sees the points and each query only through the bench’s countedPointsandQuery. Ask for the code in one language and for its box. The AI may tune onPRACTICE_SEEDS. Keep some seeds to yourself. - Judge what comes back. Run
judgeon your own seeds and read itsreport: recall on the worst seed, distances per query against the scan’s, memory against the cap. Judge the chapter’s own structures beside it,scan_candidate,kdtree_candidate,lsh_candidateandhnsw_candidate. - Repair, and say why. Each time something is wrong, decide whether it is the code, the box, or the design, and write one line saying which and why.
Hand in the whole final box, the lines from step 5 and the measurements. ★ Prove in Lean that your design meets Workbench.Contract.
Another brief or another AI gives another run. This is one.
Round 1. Checked against Contract, the promise matched it field for field, and nothing changed. The check did show that an answer of no points at all keeps the contract, and only recall stops it. The box asked for at most half the scan’s distances and inner products per query. The AI picked fifty landmark points and gave every point fifty-one numbers worked out from its distances to them. That came to 510,153 numbers in all, about half the cap. A query measures the landmarks and, from those numbers, works out a lower bound on its distance to every point. Then it measures points in order of their bounds until no unmeasured point has a bound below the tenth nearest distance found so far. On the hidden seeds it found all ten every time, at 83 or 84 distances a query on clustered points and 610 distances a query on the worst skewed set, and every check passed. Its own box said what the count leaves out. Every query works out a bound for all 10,000 points, from numbers the bench does not count. It kept the promise and missed the goal, which was to find similar points without measuring them all. Fix the box: the cost now counts every point that a query touches, measured or only read, and what the bench cannot count is checked by reading the code.
Round 2. The AI returned a graph. Each point links to the sixteen nearest points it finds, with every link going both ways. A query measures 100 starting points spread over the clusters, then walks from the nearest of them, reading links only of points it has already measured. So every point it touches costs a distance that the bench counts, and the code shows that. On the hidden seeds it passed. Its recall@10 was 0.931 on its worst set, it computed 1,630 distances a query on its costliest set, and its index held 259,507 numbers in all. Nothing to repair. Beside it, on the same sets, the chapter’s graph index with layers touched 398 points on its worst set, about a quarter as many as the AI’s graph. The chapter’s graph index reached recall 0.913, closer to the bar. LSH passed with recall 0.958, at 4,825 distances and inner products a query. That is 48.3% of the scan’s count, against the bar’s limit of half. The k-d tree computed 10,094 distances a query, more than the scan’s 10,000. Both graphs lost recall on the seeds kept back. The AI’s graph fell from 0.983 on the practice seeds it was tuned on, and the chapter’s graph fell from 0.954. A bar checked only on your tuning seeds claims more than it keeps.
Along the way the AI noted that the memory check catches coordinates copied as they are, but it does not catch the same points written along other directions. Enough landmarks would hold nearly all of every point and still stay under the cap. Round 2’s box already charges for that, since a query that reads those numbers touches the point. A check catches only what it looks for, and the check you build is part of the design too.3
Here is the range query from Where the two ends part, written the way that many people first write it. Two tests have changed. The walk to the split node goes left when hi is at most the node’s key, and hi’s walk reports a left child only when the node’s key is strictly smaller than hi.
while isinstance(v, Node) and (hi <= v.split or v.split < lo):
v = v.left if hi <= v.split else v.right
...
w = v.right # hi's walk, right of the split node
while isinstance(w, Node):
if w.split < hi:
found.append(w.left)
w = w.right
else:
w = w.leftIt reads naturally. A node’s key is the largest key on its left, so a range that ends at that key seems to lie wholly on the left. Every test with distinct keys passes, which is why this version gets published.
- Before running anything, say which keys this version can leave out of an answer, and why no test with distinct keys can catch it. Keys in the leaves has the reason.
- Write the smallest input that shows it, the keys and one range. Smallest means fewest keys.
- Now take the keys 3, 3, 3, 3, 3, 1, 5. Say what this version returns for the range from 3 to 3, and for the range from 0 to 3, and what each should return. Then say why the ranges from 3 to 5 and from 2 to 4 come out right.
Only after you have your own answer, hand the lines to an AI and ask what is wrong with them. Does its answer find the problem? Whether <= is wrong here depends on where the build puts copies of a node’s key. That rule lives in another function, which the AI was not shown.
4.13 ✎ Self-check problems practice
Transfer 1 · middling · ~30 min
Which log lines? A group of servers writes one log line per event, with the minute it happened and a severity from 1 to 5. The lines are stored the way that the search chapter’s LSM-tree stores writes. They collect in memory and go to disk in batches of four, and a batch on disk is never changed. Some lines arrive late, from a server that lost its connection for a while. Three batches are on disk. Each line is written as (minute, severity), and the lines are listed in the order they arrived.
- Batch 1: (1, 2), (3, 5), (4, 1), (6, 3)
- Batch 2: (7, 4), (2, 4), (9, 2), (10, 5)
- Batch 3: (12, 3), (13, 1), (5, 4), (15, 5)
- How many lines fall between minutes 4 and 10, ends included? Answer it with two binary searches per batch, on that batch’s minutes in sorted order. Which batches could you skip by their smallest and largest minute alone, for this count and for minutes 11 to 14?
- Now count only the lines of severity at least 3, in the same minutes. Which of this chapter’s queries is this, and why may each batch build that structure once and never rebuild it? What does one query cost, with b batches of up to n lines each?
- The LSM-tree’s read takes the newest record it finds and stops. Here you add up over every batch. Why is that right for log lines? For minutes 4 to 10, which of these could you also get by combining one answer per batch: the count of all lines, the highest severity, or how many different severities appear?
- Six. Batch 1’s minutes sorted are 1, 3, 4, 6. One binary search finds the two minutes before 4, the other finds all four minutes up to 10, so 4 - 2 = 2 lines fall between. Batch 2’s minutes are 2, 7, 9, 10: one before 4, four up to 10, so 3 lines. Batch 3’s minutes are 5, 12, 13, 15: none before 4, one up to 10, so 1 line. That makes 2 + 3 + 1 = 6. No batch can be skipped for minutes 4 to 10, since each batch’s span from its smallest to its largest minute overlaps them. Batch 3 overlaps them only because of its late line at minute 5. Without that line it would cover only minutes 12 to 15 and would be skipped. For minutes 11 to 14, batch 1 (minutes 1 to 6) and batch 2 (2 to 10) are skipped, and only batch 3 is searched.
- Four lines, (6, 3), (7, 4), (10, 5) and (5, 4). With minutes across and severity up, each line is a point and the query is a rectangle, minutes 4 to 10 and severities 3 to 5. That is the range tree with two coordinates. The range tree’s goal holds when the points don’t change, and every batch on disk is sorted and never changed afterwards. So each batch builds its tree once, when it is written. Counting needs no list. A whole subtree inside the range adds the number of its leaves, without reading their keys. One query costs about b (\log_2 n)^2 steps, and the LSM-tree keeps b small, since only a few batches pile up. When a merge combines batches, the merged batch builds one new tree and the old trees go.
- A log line is never overwritten. Two lines are two events, not an old and a new value of one key, so every line in every batch still counts, and the count is the sum. The newest-first read is for keys whose later write replaces the earlier one. The count of all lines combines the same way, 2 + 3 + 1 = 6, which is part 1. The highest severity combines too. The batches’ highest severities are 3, 5 and 4, so the answer is 5. The number of different severities does not combine. The batches have 2 different severities (1 and 3), 3 (2, 4 and 5) and 1 (just 4), which adds to 6. Only five different severities appear, because 4 is in two batches. It combines only if each batch hands back which severities it has, not how many it has, and those sets are joined across batches.
Transfer 2 · middling · ~30 min
Can a fence sort? Take five numbers, 7, 2, 9, 4 and 1, and turn each number x into the point (x, x^2), on the curve y = x^2.
- Build the convex hull of the five points with Andrew’s monotone chain, and read its corners counterclockwise from the leftmost. What do you get? Why would the same happen for any different numbers, whatever method built the hull?
- So any method that builds hulls can also sort. Suppose every test it makes, an orientation or a comparison, has at most three answers. Use the contracts chapter’s count to find at least how many tests any such method needs for five different numbers, and say how that number grows for n of them. Can all three answers actually come back?
- Andrew’s method spends almost all its time sorting, and part 2 says no method of that kind can do much better. When can a hull still be built in time that grows only like n, and which assumption of the count does that case break?
- The corners are (1, 1), (2, 4), (4, 16), (7, 49), (9, 81), so the numbers come out as 1, 2, 4, 7, 9, sorted. For any three numbers a < b < c, the orientation of their points works out to (b - a)(c - a)(c - b), which is positive, a left turn. For 2, 4 and 7 it is (4 - 2)(49 - 4) - (16 - 4)(7 - 2) = 90 - 60 = 30. So every point is a corner, whatever method built the hull. Every point also lies below the line from the leftmost point to the rightmost point, so the upper side is that one edge and every corner is on the lower side. Counterclockwise from the leftmost corner, the fence first runs left to right along its lower side, in increasing x.
- At least seven. The five numbers can arrive in 5! = 120 orders. The hull’s corners come back as positions in the input, and each order needs a different list of positions. Three answers per test would give 3^w leaves after w tests, and 3^4 = 81 < 120 suggests five. But the third answer never comes. No two x-coordinates are equal, and part 1 showed that no orientation of three of the points is zero. So every test really has two answers, and 2^6 = 64 < 120 \le 128 = 2^7 gives seven. For n points it is at least \log_2(n!) tests, the sorting bound itself, which grows like n \log_2 n. For a million points that is about 18.5 million tests.
- When the points already arrive sorted left to right, as readings taken at rising times and plotted with time across. Then Andrew’s two walks are all that is left, and they take steps proportional to n. The count needed all n! orders to be possible inputs, each with its own answer. When the input is already sorted, only one order can arrive, so the tests have nothing to tell apart. Another way out breaks the other assumption. When the coordinates are small integers, a counting sort puts each point straight into the bucket of its x. Placing each point takes one step with as many possible answers as there are buckets. The whole hull takes time that grows like n plus the number of buckets.
Transfer 3 · middling · ~20 min
Close first, or deep first? The k-d tree’s search opens the region with the smallest bound next. Swap that one part for the depth-first search from The closest region first: go down to your own region first, and on the way back cross a cut whenever the circle around you reaches it.
- Can the answer change? Which line of the box says why?
- What can change, and why?
- No. Both searches skip a region only when its bound is farther than the best found so far, so even a point at the same distance stays in reach. That is invariant 3, and with the chapter’s tie rule both give the scan’s answer.
- How many regions are opened, and how many points are measured. The depth-first search opens the region you stand in first, and that region need not hold the answer, so its best so far can stay poor for longer and rule out fewer regions. Being right comes from the bound. Being fast comes from the order in which the regions are opened.
Here are thirty-nine exercises. Each shows roughly how long it takes, and everything you need for them is in the chapter so far. The answers are on a page of their own.
If you only do four, do Exercises 2, 5, 10 and 12.
They are grouped by kind of task, not by structure. To practice one structure, here are the exercises for each section:
- Everything between two streets: 1, 2, 16, 22, 39
- The nearest one, now: 3, 4, 5, 17, 25, 26, 27, 37, 38
- The part of town she knows: 6, 7, 28
- A place like this one: 8, 29
- Near points share a code: 9, 10, 11, 18, 20, 23, 30, 31, 34, 36
- Ask the locals: 12, 13, 14, 15, 19, 21, 24, 32, 35
- What these are actually made of: 33
4.13.1 Run it and report the state
Exercise 1 · gentle · ~10 min
Build the range tree over the keys 84, 71, 69, 42, 20, 46, 86, 30, 54, 36, 75, 40. Sort the keys and hang them in the leaves. Every inner node splits the keys below it in half, the left half taking the extra key when the count is odd, and holds the largest key of its left half. Give the key of every inner node, level by level from the root, and the tree’s depth.
Exercise 2 · middling · ~15 min
In the tree of Exercise 1, query the range [65, 86]. At a node, go left when 86 is smaller than its key and right when its key is smaller than 65. The first node where neither holds is the split node. Which node is it, and which nodes does the walk pass on the way? Then follow 65 down the left side and 86 down the right side: which nodes does each path visit, which whole subtrees does each report, and which keys come out?
Exercise 3 · gentle · ~15 min
Build the k-d tree over the points a (8, 10), b (19, 8), c (4, 15), d (15, 5), e (7, 17), f (3, 1), g (13, 7), h (18, 9), i (20, 16), j (17, 6). Cut on x at the root, then on y, taking turns. At each node the left side takes the first half of its points along the axis (the extra point when the count is odd), and the cut is the coordinate of the last of them. A leaf holds one point. Draw the tree: the cut at every node, and the point in every leaf. How deep is it?
Exercise 4 · middling · ~15 min
In the k-d tree of Exercise 3, find every point with 12 ≤ x ≤ 19 and 3 ≤ y ≤ 12. Keep the region that each node covers, bounded by the cuts above it and running on without end where no cut bounds it (not the smallest box around its points): report a region whole when it lies inside the rectangle, skip a side that the rectangle does not reach, and open the rest. Which regions are reported whole, which are skipped, which leaves do you check one point at a time, and which points come out?
Exercise 5 · hard · ~25 min
In the k-d tree of Exercise 3, find the point nearest to (9, 11) by best-first search, in squared distances.
- Every waiting region carries a bound: the sum of the squared distances from the query to the region along each axis.
- Always open the waiting region with the smallest bound. Opening a node queues its far side first, then its near side, which keeps the parent’s bound, and equal bounds come out in the order they went in.
- Stop when the smallest bound waiting is larger than the best distance found.
In what order are the regions opened, which points are measured, which regions are skipped, and why?
Exercise 6 · middling · ~15 min
Run Andrew’s monotone chain on the points a (9, 7), b (0, 10), c (3, 4), d (12, 9), e (7, 11), f (4, 5), g (5, 2), h (1, 8). Sort them by x, build the lower chain left to right and the upper chain right to left, and keep dropping the last kept point while it, the one before it and the new point do not make a strict left turn. Which points are dropped, and when? What is the hull, counterclockwise from the leftmost point?
Then: The turn test is written >= 0 instead of > 0. Which point is now kept that the promise says must be left out, and why?
Exercise 7 · gentle · ~5 min
Walking from a to b, is c on the left, on the right, or on the line? Give the sign of the orientation test, once for a (1, 9), b (0, 4), c (3, 0), and once for a (7, 1), b (6, 2), c (0, 8).
Exercise 8 · middling · ~15 min
A box runs from -2 to 2 along every axis. In each of its corners sits a ball of radius 1, centered at the point whose every coordinate is 1 or -1, so it touches the box’s walls at that corner and the balls in the neighboring corners. A ball at the center of the box is made as large as it can be without overlapping any corner ball. What is its radius when every point has 2 numbers, 10 numbers, and 100 numbers? From how many numbers on does the center ball reach outside the box, though every corner ball stays inside it?
Exercise 9 · gentle · ~10 min
A table’s cuts are lines through the origin, given by the directions (2, 2), (-1, -3), (1, -1). A point’s bit for a cut is 1 when the dot product of the point with the direction is zero or more, and 0 when it is negative. Its key is its three bits in the order of the cuts. Hash the points a (-4, -3), b (3, 4), c (0, -5), d (4, -3), e (3, -4), f (-3, 4), g (0, 5), h (-5, 0). What is each point’s key, and which points share a bucket?
Exercise 10 · middling · ~15 min
Add a second table to the points of Exercise 9, with the cuts (3, 1), (2, -1), (3, 3). The query is (-3, -4). What is its key in each table, which points share a bucket with it in some table, and which point is the answer after measuring each of them exactly? What would the answer have been with the first table alone?
Exercise 11 · middling · ~25 min
An LSH index uses keys of K = 4 cuts and L = 8 tables. With what probability does a point at 60° from the query share the query’s key in one given table, and with what probability does it become a candidate? Answer the same for a point at right angles to the query.
Then: Choose K and L so that a point at 45° becomes a candidate with probability at least 0.99, and one at 90° becomes a candidate with probability at most 0.05, with as few tables as you can. Try key lengths from 4 up, and for each find the fewest tables that let the 45° point in. Keep four decimal places.
Exercise 12 · middling · ~10 min
The point a (9, 8) picks at most 3 neighbors from the candidates b (6, 0), c (0, 12), d (12, 9), e (11, 2). Take them nearest first, in squared distances, and skip a candidate when a neighbor already picked is strictly nearer to it than a is. Which are picked, in order, and which is skipped, because of which neighbor?
Exercise 13 · middling · ~15 min
A flat graph index holds the points a (14, 17), b (4, 19), c (5, 9), d (13, 10), e (1, 11), f (8, 1), g (15, 8), h (16, 16), i (9, 7), j (11, 6), with the links a: b, d, h; b: a, c, e; c: e, i; d: g, i, h, j; e: c, b; f: c, g; g: d, f; h: a, d; i: c, d, j; j: i, d. Walk greedily from a toward the query (12, 0): at each point, measure every neighbor and step to the nearest one if it is nearer than where you stand. Stop when none is nearer. Which points does the walk visit, with their squared distances, and where does it stop? Is that the nearest point?
Then: Walk again from a, but keep the 3 nearest points seen so far: each time, take the nearest kept point you have not yet expanded, measure its neighbors you have not measured, and keep the 3 nearest of all you have seen. Stop when the nearest point not yet expanded is farther than the worst of the 3 kept. Which kept point is nearest to the query?
Exercise 14 · middling · ~20 min
A flat graph index with M = 2, so a list may hold four, holds the points a (11, 7), b (14, 12), c (15, 0), d (4, 1), e (8, 5), f (0, 17), g (13, 9), h (6, 11), with the links a: g, e, c; b: a, g, h; c: a; d: a, e; e: a, d, f, h; f: e; g: a, b; h: e, b. Insert i (9, 3): the beam finds all eight points as candidates. Pick by the rule of Exercise 12, in squared distances: which two does i pick, in order? Which lists get i as a link back, which of them grows past four, and what does its owner keep when it picks again?
Exercise 15 · middling · ~15 min
The graph index’s table in What it costs gives, for each beam width ef, recall@10 and queries a second on GloVe: ef 10: 0.467, 12,168; ef 40: 0.699, 4,712; ef 160: 0.849, 1,413; ef 640: 0.936, 416; ef 1,280: 0.964, 222; ef 2,560: 0.983, 118. Mia’s service needs recall@10 of at least 0.9 and at least 300 queries a second. Which beam width from the table do you ship, and why not the others? LSH answers 17 queries a second at recall 0.976, and the chapter says that at that recall the graph answers more than eight times as many. Is that a figure from the table? If not, where does it come from?
Then: Read the speed at exactly recall 0.9 between the two measured beam widths around it, on a log scale of speed, the same way. What do you get, and what would you run before you promised it?
4.13.2 Which promise broke
Each item hands you something that a program produced and claims is correct. Say whether it is, and if it is not, name the invariant it breaks and the smallest change that would mend it. One of them is correct, and saying so is the answer.
Exercise 16 · middling · ~10 min
A range tree over 3, 9, 11, 14: the root has key 8; its left child has key 3 over the leaves 3 and 9; its right child has key 12 over the leaves 11 and 14.
Exercise 17 · middling · ~10 min
A k-d tree over a (2, 7), b (5, 1), c (9, 4), d (11, 8), e (14, 3): the root cuts at x ≤ 2, with a alone on its left; its right side cuts at y ≤ 3, then b, e below and c, d above are each cut on x.
Exercise 18 · middling · ~10 min
An LSH table over the points of Exercise 9, with its cuts, has the buckets 111: {d}; 100: {b, f}; 011: {c, e}; 010: {a, g, h}.
Exercise 19 · middling · ~10 min
The point a (0, 0) picks at most 3 neighbors from b (3, 1), c (5, 2), d (1, 4), e (-4, 2), and picks b, d, e.
Exercise 20 · middling · ~10 min
The one-table index of Exercise 9 answers the query (-3, -4) with c, at squared distance 10. The nearest stored point is a, at 2.
Exercise 21 · middling · ~10 min
A flat graph index built with at most 4 links per point gives d the links g, i, h, j, a.
4.13.3 You supply the input
Exercise 22 · middling · ~10 min
Over the keys of Exercise 1, give a query [lo, hi] with lo < hi, both between the smallest and the largest key, for which the split node is a leaf: the walk from the root reaches a leaf without stopping on the way.
Then: Say what every such query has in common, and why.
Exercise 23 · middling · ~15 min
With only the first table of Exercise 9 (cuts (2, 2), (-1, -3), (1, -1)), find a point with integer coordinates, as close to the query (-5, -3) as you can, that does not share the query’s bucket. How close can it be? You’re done when you can show no integer point outside the bucket is closer.
Then: Say exactly when two points share a bucket.
Exercise 24 · middling · ~10 min
Place four candidates around a point at the origin, at different distances from it, so that picking at most 3 neighbors keeps only one.
Then: Say what every such set of candidates has in common.
4.13.4 Which idea do you reach for
The first eight of these exercises describe a situation, most of them far from maps, and ask which of the eight primitives of Table 4.10 you would use. Each has four options: pick the one you would reach for first. The last puts the whole chapter on one map.
Exercise 25 · gentle · ~5 min
A game world holds a million objects that barely move, and every frame the game asks which of them lie inside the area that the camera sees. The world can be prepared once, before the game starts.
- random directions
- navigable graph
- spatial partition
- check every candidate
Exercise 26 · middling · ~5 min
A delivery planner tries routes one at a time. Halfway through building a route, its cost so far is already higher than the cheapest complete route found, and the planner still finishes it.
- bound and prune
- random directions
- navigable graph
- collide on purpose
Exercise 27 · middling · ~10 min
A file archive keeps folders inside folders, and each folder is labeled with the earliest date of anything inside it. You want the oldest file that matches a search, and opening a folder is slow.
- check every candidate
- best-first
- which side
- random directions
Exercise 28 · gentle · ~5 min
A drawing app must decide, exactly and for every click, whether the click landed inside a triangular button, even when the click is a hair from an edge.
- best-first
- navigable graph
- which side
- bound and prune
Exercise 29 · middling · ~10 min
Every customer is described by ten thousand numbers. You need the distances between them only roughly, but computing on ten thousand numbers is far too slow.
- random directions
- bound and prune
- check every candidate
- which side
Exercise 30 · middling · ~10 min
A photo service wants to find near-duplicates among a billion photos, each already turned into a list of numbers, without comparing every photo with every other.
- best-first
- collide on purpose
- which side
- spatial partition
Exercise 31 · gentle · ~5 min
Airport security cannot hand-search every passenger. A walk-through scanner is fast but raises false alarms, and a hand search is slow but certain.
- random directions
- navigable graph
- check every candidate
- bound and prune
Exercise 32 · middling · ~10 min
A music app links every song to a handful of songs that sound like it. Given a new song, it must find similar ones quickly among millions, with no other index.
- navigable graph
- which side
- best-first
- collide on purpose
Exercise 33 · middling · ~20 min
Without looking back, write each structure of this chapter as what it is made of: the range tree, the k-d tree, the convex hull, LSH, the graph index and the graph index with short codes. Write each as a sum of ideas from this list: spatial partition, a few whole pieces, bound and prune, best-first, which side, keep an invariant, random directions, collide on purpose, check every candidate, navigable graph, keep it in layers. Where one structure is built on another, the whole structure counts as one part. Then draw it as a map: a dot for each structure and each idea, and a line from each structure to every idea it uses. Which ideas have lines to two structures or more, and what does each one do in each? Three of the ideas did other jobs in earlier chapters. Which, and where?
4.13.5 The tests pass. What did they miss?
Code that fails its tests is easy to catch. The costly kind passes every test, because nobody wrote a test for the requirement it breaks.
Exercise 34 · middling · ~15 min
A team ships an LSH index for finding similar products. Its tests pass: for a thousand queries, the index’s answer is the true nearest product every time. In production, shoppers search with photos of products that the shop does not sell, and the answers are often far from the best. What requirement did the tests miss?
Then: Write the requirement as a sentence that a test could check.
Exercise 35 · hard · ~20 min
A graph index over restaurant reviews passes its tests: on a million points spread evenly, its recall@10 is 0.99. After launch, the reviews turn out to fall into tight clusters, one per city, and searches for a dish in one city often return a dish from another. What requirement did the tests miss?
Then: Write the test: on what data, against which reference, and at what beam width.
4.13.6 Fix the code, the box, or the design?
Each item starts from code that an AI wrote from one of the chapter’s design boxes, and something it did that looks wrong. Decide which of three things happened. The code breaks a promise in the box: fix the code. The code keeps the box but misses what you wanted: fix the box. The design keeps its promise, but its assumptions or its cost no longer fit the job: change the design. Say why.
Exercise 36 · middling · ~10 min
You give an AI the LSH design box and ask for the code. On the two tables of Exercise 10, asked for the point nearest to (-3, -4), its index answers c, at squared distance 10, though a, at 2, shares a bucket with the query too. Its tests had passed. Which of the three is it, and why?
Then: Suppose the box had stopped at invariant 1. Which would it be then? Write the line you would add, and a test you would keep from the AI that checks it.
Exercise 37 · middling · ~10 min
The same AI’s k-d tree holds 2,000 points, every check of the box’s invariants passes, and every answer equals the scan’s. On points given by 2 numbers, a search measures about 4 points. Then the points are described by 32 numbers each, and a search measures about 2,000 of the 2,000. A colleague says the pruning is broken. Which of the three is it, and why?
Then: Name the design you would switch to, and say what you would measure to check it.
Exercise 38 · middling · ~10 min
An AI builds a map app’s rectangle search on the k-d tree of Exercise 3. Asked for the places with 12 ≤ x ≤ 19 and 3 ≤ y ≤ 12, it returns b, d, g, h, j. The app lists them in that order as running west to east, and b is not the westernmost. Which of the three is it, and why?
Then: Rewrite the line of the box that has to change, say what the change costs, and name a test you would keep from the AI.
4.13.7 Every place in a rectangle, two trees deep
Exercise 39 · hardest in the chapter · ~90 min
You already have:
- the 1D range tree’s query, printed in the chapter
- the chapter’s paragraph on the 2D tree: a range tree on x whose every inner node also carries a range tree on the y of the points below it
- the range tree’s invariants: every inner key separates its two sides, and every inner node splits the points below it in half
Write query(lo, hi) for the 2D range tree, as code or as precise steps: every stored point with lo ≤ (x, y) ≤ hi on both axes, where lo = (x_lo, y_lo) and hi = (x_hi, y_hi), each once. Your answer must say what happens at the split node, what you do with a whole subtree that hangs off either path, and what you do with the leaf where a path ends.
Three checks tell you whether you got it right, on the points a (29, 30), b (21, 14), c (15, 23), d (3, 7), e (4, 15), f (26, 10), g (25, 13), h (0, 5), i (18, 22), j (6, 16), k (1, 19), l (16, 28), and the rectangles 14 ≤ x ≤ 25 with 17 ≤ y ≤ 26, 16 ≤ x ≤ 28 with 1 ≤ y ≤ 13, 12 ≤ x ≤ 22 with 18 ≤ y ≤ 28:
- On these points and rectangles, the answer is exactly the points that a scan of every point finds, each once.
- Each query searches at most two associated trees per level of the tree on x.
- A rectangle with lo > hi on either axis returns nothing.
Stretch: Show that a query costs O(log² n + k), and that the whole tree takes O(n log n) memory.
Put this somewhere you’ll see it in about a week, and when you see it, answer from memory first, with no scrolling back and no AI. Getting it wrong and then looking is the point.
Name the structures in this chapter in order, and for each, which of Mia’s questions it answered and what it could not handle.
Why may the range tree report a whole subtree without reading its keys, and what guarantees that every key in it is inside the range?
What does a k-d tree compare before it leaves a region closed, and why does that leave about four points measured out of a million on a map?
Why does the same k-d tree measure every point when each point has a hundred numbers?
In LSH, why must every candidate be measured, and what does a second table add?
A colleague’s graph index reports recall 0.99. What three things do you ask before believing it?
NoteAnswerOn what data it was measured, against which reference (the scan’s true ten nearest, on that same data), and at what beam width, with the speed at that width. Recall holds for the data it was measured on and no other, and a wider beam buys recall with speed, so 0.99 alone says nothing about cost.
Pick one of the chapter’s design boxes and write it from memory. Say what it promises, its idea and invariants, and on what its cost depends. If it assumes anything, say what you would see if that assumption broke. Then open the box and compare.
Whichever of those you couldn’t reconstruct is the one to reread, and only that one. If you got all seven, come back again in a month instead.
4.14 ★ Frontier map advanced
What follows is optional. It is a short tour of ideas just past the edge of this chapter. Skip it now if you’d rather move on, and come back later.
One thread runs through it. This chapter took a fixed set of places with one list of numbers for each, a distance everyone agreed on, and a question with no conditions attached. Current research changes each of those: what is being searched, whether one list per thing is enough, how few numbers a list can be squeezed into, whether the places stay put and the question comes without a filter. The rest asks what a guarantee for a graph would cost. Each entry ends with a question you can now ask of any system that makes the same choice.
4.14.1 The chatbot’s memory is a nearest-neighbor search
LSH and graph search inside attention
A language model writing a long answer looks back at everything it has read. For each word read it keeps a list of numbers, a key. For each new word it compares one query list with all of the keys, and that scan is repeated for every word it writes. With a hundred thousand words in view, that scan is the cost. MagicPIG samples the keys with LSH instead of reading them all, because the keys that matter are spread more widely than the top few would catch [29]. RetrievalAttention walks a graph index over the keys, and found that indexes built in the usual way do poorly here, because the model’s queries and its keys are not spread alike [30]. A preprint reads one step of the computation as a range query that asks for every key on one side of a cut, and it builds a new index for that query [31].
When a model looks back, what is it searching, and what happens when it misses a neighbor?
4.14.2 What one list of numbers can’t say
Limits of single-vector embeddings
“A place like this one” became “a place near this one” when every place became one list of numbers. The size of that list limits which sets of ten any query can ever bring back as its top ten. That holds even when the lists are fitted freely to the test queries. On a dataset built to show it, strong models fail at tasks that look simple [32]. One way out describes each document by several lists, one per piece. The method then combines a document’s lists into one long list, using SimHash’s buckets, so that the single-list indexes of this chapter can still search the documents [33].
Which pairs of things can no embedding of this size put near the same query?
4.14.3 Rotate, then round
Quantization with error bounds
The On a phone fold kept one bit per number after a random rotation. RaBitQ’s paper proves how far its estimate can stray [27], and a later one keeps more bits per number for a tighter estimate [34]. TurboQuant rotates and rounds too, and reports large savings in a model’s memory [35]. A preprint by RaBitQ’s authors reports that, when the two were run in one matched setup, TurboQuant did worse than RaBitQ in most settings they tested, and that some of its reported results could not be reproduced [36]. That preprint has not been reviewed yet. Another paper keeps part of each code in memory and reads the rest from a disk, which is the regime in which the chapter’s codes won [37].
A paper reports a faster code. On what data, against which baseline, and has anyone reproduced it?
4.14.4 “Open now”
Filtered and changing data
A filter removes points that the walk needed. ACORN adds links while building, so that the points passing any filter still form a graph that a walk can cross [38]. Filtered-DiskANN builds links that know each point’s labels [39]. Measured inside a production database, graph methods with filters can spend so many filter checks that they often lose their advantage over a simpler index of clusters [40]. Points also change. Removing one from a graph is harder than adding one, because nothing records who links to a point. Recent work repairs the graph in place at each deletion, instead of collecting deletions and repairing them in periodic batches [41].
Your filter removes half the points. What does your index still promise?
4.14.5 Why exact is out of reach
Hardness of nearest-neighbor search
In many dimensions, no method is known that finds the exact nearest in much less time than one measurement per point, even after a preparation that takes any reasonable time [12, Sec. 1]. A method that fast would break a widely believed conjecture, the Orthogonal Vectors conjecture. The strings chapter’s wall for edit distance rests on the same conjecture.
Take n lists of 0s and 1s, each a few times \log_2 n long. Call two lists orthogonal if they never have a 1 in the same position. The conjecture says that finding an orthogonal pair cannot be done much faster than checking every pair [42, Conj. 2.3]. Finding that pair can be turned into a nearest-neighbor search. So a search much faster than the scan would find the pair too fast, and the conjecture would be false.
The wall used to rest on a stronger conjecture about satisfiability, the Strong Exponential Time Hypothesis (SETH). SETH implies the Orthogonal Vectors conjecture [43]. SETH in turn can only be true if a weaker statement, the Exponential Time Hypothesis (ETH), is true too. In 2026 OpenAI and Anthropic each announced a proof, found by an AI model, that ETH is false [44], [45]. If ETH is false, SETH is false too. Both proofs await independent checks. Even if the proofs hold, the Orthogonal Vectors conjecture can still be true, and nobody has proved that conjecture. So the wall is conditional.
The door in that wall is approximation. If any point within twice the nearest distance is accepted, a hash looks at about n^{1/4} of the n points. Instead of cutting space with random planes, that hash projects the points onto a few random directions and carves that smaller space into balls [12, Thm. 2.6, §2.3]. With too little slack, within 1 + \varepsilon for a small enough \varepsilon, the wall is back [42, Cor. 1.3].
How much slack does your question really allow, and would any less make it as hard as a scan?
4.14.6 How many links does it take?
Building navigable graphs
The search chapter’s frontier map gave the price in links of a graph on which a greedy walk always reaches the nearest. Building one is now well understood. Any n points have such a graph with about \sqrt{n \log n} links per point on average, and that is nearly the best possible. On random points, even with only a constant times \log n numbers each, such a graph needs nearly \sqrt{n} links per point on average, with high probability [46]. Finding the sparsest one is the set-cover problem in disguise. A graph within a logarithmic factor of the sparsest can be built, and doing much better is NP-hard [47]. A build that takes time about n^2 for a graph within that logarithmic factor is as fast as possible, unless the Orthogonal Vectors conjecture is false [48]. For graphs that only need to work for most queries, a preprint shows that the known construction is as small as possible [49]. DiskANN’s graph, Vamana, keeps some longer links on purpose when it picks neighbors, so a walk that reads its points from a disk takes fewer steps [50].
Someone says their graph always finds the nearest. How many links did that cost, and how long did it take to build?
4.14.7 Faster strips
Fractional cascading
The rectangle query of Two coordinates at once runs one search on the second coordinate in every whole subtree it reports. Each of those is a binary search of about \log_2 n steps, and all of them look for the same range of y. The lists in which those searches run are pieces of one another. Fractional cascading searches the first list once and follows pointers stored beside each entry into the next, so the whole query takes O(\log n + k) time instead of O(\log^2 n + k) [1, Sec. 5.6]. For decades the method was taken to work only along a line. It has since been carried partway to the plane. For subdivisions whose edges are axis-aligned, a query pays about an extra \sqrt{\log n} steps for each subdivision it searches, and no method can do better in general [51]. For arrangements of lines there is a two-dimensional version too, built to count where points and lines meet [52].
When does one shared search beat many separate ones, and who still ships it?
4.14.8 Could the machine choose the neighbors?
Where this may be going
The picking rule of Keep the neighbors that tell you something keeps links by distance alone, and the searches that use the graph are judged by whether the answers were useful. A recent preprint lets a language model swap a graph’s weak links for ones it judges more useful, keeping the graph as sparse as before, and reports better answers than the walk alone [53]. Put one question to whatever makes that choice for you. What would it have to show you before you believed its choice? It would have to show what it assumed about your points, what would break that assumption, and what happens to the answers when the assumption breaks.
4.14.9 Small questions
You can’t picture five hundred dimensions. Any flat picture of them has to stretch some distances. You can ask the points questions with small answers, though. Which points are near this one? What do the points look like seen along one direction? How far along a named direction does this point sit? Every structure in this chapter asked questions like those, and little else. In many dimensions almost every pair of directions is nearly at right angles, and that one fact made every distance look the same to the k-d tree. The same fact is the leading explanation for how a neural network can keep far more features than it has numbers, each along a direction of its own. Small toy models are seen doing exactly that [54].
4.15 ★ Appendix: why the shortcuts are safe advanced
This appendix is part of the chapter. It proves why the k-d tree may leave regions closed, shows where plain arithmetic gives the hull a wrong turn, proves why random projections keep a distance, and shows the grid on a line that LSH uses for straight-line distance. The code for each is in the companion library, in its geometry folder.
4.15.1 Why leaving a region closed is safe
The best-first search of The closest region first stops when the region at the front of its queue has a bound strictly larger than the k-th best distance found. Two facts make that stop safe.
A region’s bound is never more than the squared distance of any point inside it. The bound is the sum of the squared offsets, one per axis, so it is enough to carry a stronger fact. For every point in a region, each offset is at most that point’s distance from q along its axis. At the start every offset is 0, and no distance is less than 0. A region’s near side keeps its parent’s offsets and holds some of its parent’s points, so it keeps the fact. On the far side of a cut at s along axis a, the offset along a becomes s - q_a. Say q is on the left, q_a \le s. Every point p on the right has p_a \ge s, by invariant 1, so
(s - q_a)^2 \;\le\; (p_a - q_a)^2 , \tag{4.10}
and the mirror case is the same with the sides swapped. Every other offset is unchanged, and was already at most that point’s distance from q along its axis. Adding up the axes, as equation (4.4) does, gives a bound of at most \operatorname{dist}(p, q)^2 in every dimension. On a map, with two axes, that is equation (4.2).4
Every point not yet measured sits in exactly one waiting region. At the start the whole map waits, holding every point. Opening a cut takes one region out of the queue and puts its two sides in, and each of its points lies on exactly one side. Opening a leaf takes it out and measures its points.
Now the stop. The queue hands out the smallest bound first, so when the front region’s bound is larger than the k-th best distance, every waiting region’s bound is larger too. Every point not yet measured sits in one of them, and by the first fact its squared distance is at least that region’s bound, so it is strictly farther than the k-th best. None of them could enter the k best, not even on a tie. In the trace, the search stopped with g and f waiting at 16 and everything else at 90 or more, all farther than e at 10.
4.15.2 When the sign lies
Andrew’s chain repeatedly checks the sign of the orientation of three points. In ordinary floating-point arithmetic every subtraction and every product is rounded, and near a line the true value is so small that the rounding can outweigh it. The example below is a smaller version of one by Kettner and colleagues [55].
Fix two points on the line y = x, (12, 12) and (24, 24). Take a grid of 64 \times 64 points near (0.5, 0.5), with neighbors one rounding step apart. For each point p, ask on which side of the fixed line it lies. The true line runs exactly along the grid’s diagonal. The library’s plain version, orient2d_fast, computes the same number as equation (4.3), but arranges the formula to subtract the third point from the other two, as (a - c) \times (b - c). This is Shewchuk’s form, which the library’s filter below uses.
Asked as the hull asks, with the new point last, \operatorname{orient}((12, 12), (24, 24), p), the plain version names the wrong side for 112 of the 4,096 points, and calls 2,052 more “on the line” when they are not. Asked with the point first, \operatorname{orient}(p, (12, 12), (24, 24)), it never names the wrong side. Which position is exposed depends on which point the formula subtracts, not on the geometry. When the formula is written as in equation (4.3), subtracting the first point, the 112 wrong sides move to the other call (Table 4.11).
| formula | point last, as the hull asks | point first |
|---|---|---|
| the library’s plain version, subtracting the third point | 112 wrong side, 2,052 false “on the line” | 0 wrong side, 1,442 false “on the line” |
| equation (4.3), subtracting the first point | 0 wrong side, 1,330 false “on the line” | 112 wrong side, 2,052 false “on the line” |
Both kinds of error hurt the hull. A false “on the line” is not a left turn, so when the turn is really left, the chain drops a real corner, and that corner ends up outside the fence. A wrong side keeps a point that makes a dent, or drops a corner.
The library’s orient2d keeps the speed of the plain version and the answer of the exact one. It computes the plain value first, and trusts the sign only when the value is farther from zero than Shewchuk’s error bound says rounding could have moved the value [56, Sec. 4]. Otherwise it computes the same determinant again in exact fractions. Away from a line the plain sign clears the bound and is used as it is. The exact step is paid for only near a line. The library’s Rust does the second step with Shewchuk’s adaptive arithmetic instead of fractions. Its floats can overflow or underflow, so wherever a step could do that, it answers “cannot decide”. Every input whose coordinates are zero or of size between 2^{-400} and 2^{500} is always decided.
4.15.3 Why random projections keep a distance
A place like this one claimed that about \log n / \varepsilon^2 random directions, times a constant, keep every distance among n points within a factor of 1 \pm \varepsilon, with high probability. Here is the proof for one pair of points, and then for all of them, with the bell-curve directions of Indyk and Motwani and the steps of Dasgupta and Gupta [14], [17, Lemma 7].
Take k random directions r_1, \ldots, r_k, each coordinate drawn from the bell curve, the standard normal distribution, all independently. Each r_i points in a random direction, as the directions of Figure 4.14 do. Its length only sets the scale, and the next step shows the scale comes out right. A point v’s projection along r_i is the dot product s_i = r_i \cdot v, and its new description is f(v) = (s_1, \ldots, s_k) / \sqrt{k}, as the library’s projection computes it. In this appendix a projection is the plain dot product. That is the projection of A place like this one times the direction’s length, which is about 10 for a hundred numbers, so s_i^2 already carries that section’s “multiply by 100”. Dot products add, so f(u) - f(w) = f(u - w), and the distance between two projections is the length of one vector’s projection, v = u - w. Scaling v scales f(v) by the same factor, so take v of length 1.
Right on average. s_i = \sum_j r_{ij} v_j is a sum of independent bell-curve numbers, each scaled by v_j, and such a sum is again a bell-curve number whose variance is the sum of the squared scales: \sum_j v_j^2 = 1. So each s_i^2 averages 1, and
|f(v)|^2 = \frac{1}{k} \sum_{i=1}^{k} s_i^2 = \frac{X}{k} \tag{4.11}
averages 1 too. The question is how far X strays from k.
Rarely far off. For a bell-curve number s and any t < 1/2, the average of e^{t s^2} is 1/\sqrt{1 - 2t}, a standard integral. The s_i are independent, so the average of e^{tX} is (1 - 2t)^{-k/2}. A number that is never negative exceeds m times its average with probability at most 1/m (Markov’s inequality). Apply it to e^{tX}, which is never negative. For t > 0, X \ge (1 + \varepsilon) k exactly when e^{tX} \ge e^{t (1 + \varepsilon) k}, so
P\big(X \ge (1 + \varepsilon) k\big) \le \frac{(1 - 2t)^{-k/2}}{e^{t (1 + \varepsilon) k}} . \tag{4.12}
The choice t = \varepsilon / (2(1 + \varepsilon)) makes the right side \big((1 + \varepsilon) e^{-\varepsilon}\big)^{k/2}, and since \ln(1 + \varepsilon) \le \varepsilon - \varepsilon^2/2 + \varepsilon^3/3, that is at most e^{-k(\varepsilon^2/4 - \varepsilon^3/6)}. The same steps with e^{-tX}, whose average for one s is 1/\sqrt{1 + 2t}, and t = \varepsilon / (2(1 - \varepsilon)) give P\big(X \le (1 - \varepsilon) k\big) \le \big((1 - \varepsilon) e^{\varepsilon}\big)^{k/2}, and since \ln(1 - \varepsilon) \le -\varepsilon - \varepsilon^2/2, that is at most e^{-k \varepsilon^2 / 4}. For \varepsilon \le 1/2 both are at most e^{-k\varepsilon^2/6}, so
P\Big(|f(v)|^2 \notin \big[1 - \varepsilon,\; 1 + \varepsilon\big]\Big) \;\le\; 2\, e^{-k \varepsilon^2 / 6} . \tag{4.13}
When the squared length stays inside 1 \pm \varepsilon, the length itself stays inside it too. That settles one pair.
All the pairs. n points make fewer than n^2/2 pairs. By the union bound, the chance that at least one of them strays is at most the sum of their chances, which is at most n^2 e^{-k\varepsilon^2/6}. With k \ge 18 \ln n / \varepsilon^2 that is at most 1/n. The count of directions depends on n and \varepsilon, and not on how many numbers each point had at the start. For a million points kept within 10%, these constants ask for about 25,000 directions. The two bounds above, taken before they were merged into one, ask for about 18,000 directions. Either way it is tens of thousands.
4.15.4 A grid on a line
p-stable LSH
SimHash measures angle. For straight-line distance, LSH uses a different hash. Draw a random direction a, each coordinate from the bell curve, a random offset b between 0 and w, and cut the line into cells of width w. A point’s cell is
\Big\lfloor \frac{a \cdot v + b}{w} \Big\rfloor , \tag{4.14}
the cell in which its projection lands [21, Sec. 3.2]. With a = (1, 2), b = 0.5 and w = 4, the points (3, 1) and (2, 2) have projections 5 and 6 and share cell 1, and (1, 4), with projection 9, lands in cell 2.
Two points in one cell have projections less than w apart.5 The reverse fails. Two near points can sit on either side of a cell’s edge, and the random offset is what makes that a matter of chance. Projections t apart, with t < w, are split by an edge with probability t / w, so they share a cell with probability 1 - t/w.
How far apart are the projections? By the same fact as in the last proof, the projection of u - v is a bell-curve number scaled by the distance c = |u - v|. That is what stable means here. So the chance that u and v share a cell is the average, over a bell-curve number Z, of \max(0,\, 1 - c|Z|/w). It falls as c grows, so near points share a cell more often than far ones, which is all LSH asks of a hash. From there the frame is SimHash’s: K cells make a key, L tables give second chances, and every candidate is measured exactly.
On GloVe, over the first 1,000 queries, the best setting of this hash that the library measured reached recall 0.843, at less than half the scan’s speed.
In the companion library’s Lean,
time_queryM_leinlean/AlgoDesign/Geometry/RangeTree/proves this for the walk as written, counting its steps one by one, at most 2\lceil \log_2 n \rceil + k + 1 for k keys reported.↩︎Where the rest of the chapter measures words, the numbers come from a standard set of word embeddings, GloVe [6]: 1,183,514 words, 100 numbers each, with 10,000 test queries and their true ten nearest neighbors, as packaged by ann-benchmarks [7]. Like the cafés, the words are compared by angle, with every list scaled to length 1. The cafés stay a story, and no number below was measured on them.↩︎
Rounds and numbers from one run of the Python bench, hidden seeds 101, 202 and 303 in both families, 10,000 points and 100 queries each. Practice numbers on seeds 1, 2 and 3. The same AI wrote both rounds, given only the bench and each round’s brief, and the second brief came with the judge’s report on the first round. The chapter’s structures had their settings picked on the practice seeds.↩︎
In the library’s Lean,
far_side_bound,far_side_bound_leftandboxSqDist_leinKDTree/Prune.lean.↩︎In the library’s Lean,
pStableKey_eqinLSH/Families.lean.↩︎