{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"nearest-neighbour-search-arithmetic","title":"Finding the closest vector among ten million: the arithmetic of approximate search","url":"https://addaly.com/learn/maths-you-need/nearest-neighbour-search-arithmetic","position":65,"of":76,"minutes":10,"answer":"Exact nearest-neighbour search costs n × d per query and n × d × 4 bytes to hold, which is fine to about a hundred thousand vectors and impossible at ten million.","keyIdea":"Exact nearest-neighbour search costs n × d per query and n × d × 4 bytes to hold, which is fine to about a hundred thousand vectors and impossible at ten million, so every method past that shrinks the vectors, searches a fraction of them or walks a graph, and each pays for its speed in measured recall."},"body":{"format":"markdown","text":"## The version: compare with everything\n\nGiven a query embedding and a store of `n` embeddings of dimension `d`, the exact way to find the nearest is to compute all `n` similarities. That is `n × d` multiply-adds per query, and the store occupies `n × d × 4` bytes in float32.\n\n```\nn = 100,000, d = 768:   1.5 × 10^8 FLOPs per query, 300 MB\nn = 10,000,000:         1.5 × 10^10 FLOPs per query, 30 GB\n```\n\nAt a hundred thousand, one query is about a millisecond on a laptop and the store fits in RAM. Brute force is the right answer, and building an index for it is wasted effort that also costs recall. The course `machine-learning-foundations` builds a working search at this scale with NumPy; nothing more is needed until the numbers change.\n\nAt ten million, one query is around 150 milliseconds on a CPU, tolerable for one user and hopeless for a thousand, and the store is 30 GB, which is beyond a laptop and beyond most graphics cards. Something has to give, and there are exactly four things that can.\n\n## Shrink the vectors\n\nDrop dimensions. Module 2's singular values, or a model trained to put its important dimensions first, let you keep 256 of 768 with a modest loss in ranking quality: threefold less memory and compute. Then shrink each number. Float32 to int8 is fourfold at almost no loss. Product quantisation goes further: split the vector into sub-vectors, replace each with the index of its nearest entry in a small learned codebook, and store perhaps 64 bytes per vector instead of 3,072:\n\n```\n10^7 vectors × 64 bytes = 640 MB\n```\n\nThe 30 GB store now fits in a phone. The similarity computed from codes is approximate, which is the first place recall is spent.\n\n## Search fewer of them\n\nPartition the store into clusters, module 4's k-means will do, with about `√n` centres: 3,000 or so for ten million. A query is compared first with the 3,000 centres, then only with the vectors in the nearest few clusters. Probe 32 clusters and you examine about one per cent of the store:\n\n```\n3,000 centre comparisons + 1% of 10^7 = about 130,000 comparisons, against 10,000,000\n```\n\nRoughly a hundredfold faster. The cost is that the true nearest neighbour sometimes sits in a cluster you did not probe; at one per cent probed, expect to miss it a few times in a hundred, and to find it nineteen times in twenty. Probing more clusters buys recall with time, and the curve between them is the thing you tune.\n\n## Walk a graph instead\n\nBuild a graph in which each vector links to a few dozen near neighbours, with sparser long-range links layered on top. A query starts at an entry point and greedily hops to whichever neighbour is closest to it, descending the layers, until no neighbour is closer. This is HNSW, and a query typically touches a few hundred to a thousand vectors:\n\n```\n~1,000 comparisons per query, against 10,000,000: ten-thousandfold\n```\n\nThe price is memory for the links, around 100 to 300 bytes per vector on top of the vector itself, and a build time that is itself a nearest-neighbour problem, hours for ten million on a laptop. Recall is typically above 95 per cent and adjustable with a search-width parameter. Most hosted vector databases run this.\n\n## What recall costs you\n\nEvery approximate method returns the true nearest neighbour some fraction of the time, and the fraction is measured, not guaranteed. A retrieval system at 95 per cent recall silently gives the wrong first passage to one query in twenty. Whether that matters depends on what sits downstream: a recommender barely notices; a system answering questions from a single retrieved document notices every time. Measure recall on your own queries against brute force on a sample, because the number in the library's documentation was measured on a different dataset.\n\n## The rule of thumb\n\n```\nunder 10^5 vectors:   brute force, NumPy, no index\n10^5 to 10^6:         brute force on a GPU or with int8; index only if latency demands\nabove 10^6:           IVF or HNSW, with quantisation once memory bites\nabove 10^8:           quantise first, then partition, and expect to tune for weeks\n```\n\nEvery one of those lines is a consequence of `n × d` and `n × d × 4`. Do the two multiplications for your own `n` before choosing a tool.\n\n## Free tools, and one more number\n\n`faiss` on a CPU implements everything above and is free; `hnswlib` is a small, fast HNSW; NumPy is brute force. All run on a laptop. The one further number to know is that the query embedding must be produced by the same model, with the same normalisation, as the stored ones; module 1's cosine lesson explained why, and a store of unit vectors searched with an un-normalised query returns confidently wrong answers at any scale, with a perfect index."},"check":{"question":"A team with 40,000 document embeddings sets up a hosted vector database with an HNSW index before building anything else. What does the arithmetic say?","options":[{"text":"Brute force is a millisecond per query and 120 MB; the index only costs recall.","correct":true},{"text":"The index is essential, because 40,000 pairwise comparisons per query is far too slow.","correct":false,"tempting":"40,000 dot products of length 768 is about 60 million FLOPs, well under a millisecond on a laptop; the quadratic fear does not apply to a single query against a store."},{"text":"An index is needed for memory, because 40,000 vectors will not fit in a laptop's RAM.","correct":false,"tempting":"40,000 × 768 × 4 bytes is about 120 MB, which fits comfortably; memory becomes the constraint around ten million vectors, not forty thousand."},{"text":"HNSW gives exact results, so there is no downside beyond the setup cost.","correct":false,"tempting":"HNSW is approximate; it trades a measured recall below 100 per cent for speed, which is a bad trade when brute force was already fast."}]},"prev":{"slug":"graphs-as-matrices","title":"A graph is a matrix, and its paths are its powers","url":"https://addaly.com/learn/maths-you-need/graphs-as-matrices"},"next":{"slug":"fermi-estimates-for-ml","title":"Estimating anything to within a factor of three","url":"https://addaly.com/learn/maths-you-need/fermi-estimates-for-ml"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Finding the closest vector among ten million: the arithmetic of approximate search', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/nearest-neighbour-search-arithmetic (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Finding the closest vector among ten million: the arithmetic of approximate search","courseTitle":"The Maths You Actually Need","module":{"index":7,"slug":"cost-and-scale","title":"Counting the cost: complexity and the arithmetic of scale"},"answer":null,"keyIdea":"Exact nearest-neighbour search costs n × d per query and n × d × 4 bytes to hold, which is fine to about a hundred thousand vectors and impossible at ten million, so every method past that shrinks the vectors, searches a fraction of them or walks a graph, and each pays for its speed in measured recall.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-version-compare-with-everything","runs":[{"text":"The version: compare with everything"}]},{"t":"p","runs":[{"text":"Given a query embedding and a store of "},{"text":"n","code":true},{"text":" embeddings of dimension "},{"text":"d","code":true},{"text":", the exact way to find the nearest is to compute all "},{"text":"n","code":true},{"text":" similarities. That is "},{"text":"n × d","code":true},{"text":" multiply-adds per query, and the store occupies "},{"text":"n × d × 4","code":true},{"text":" bytes in float32."}]},{"t":"code","lang":"","label":"Text","text":"n = 100,000, d = 768:   1.5 × 10^8 FLOPs per query, 300 MB\nn = 10,000,000:         1.5 × 10^10 FLOPs per query, 30 GB"},{"t":"p","runs":[{"text":"At a hundred thousand, one query is about a millisecond on a laptop and the store fits in RAM. Brute force is the right answer, and building an index for it is wasted effort that also costs recall. The course "},{"text":"machine-learning-foundations","code":true},{"text":" builds a working search at this scale with NumPy; nothing more is needed until the numbers change."}]},{"t":"p","runs":[{"text":"At ten million, one query is around 150 milliseconds on a CPU, tolerable for one user and hopeless for a thousand, and the store is 30 GB, which is beyond a laptop and beyond most graphics cards. Something has to give, and there are exactly four things that can."}]},{"t":"h2","id":"shrink-the-vectors","runs":[{"text":"Shrink the vectors"}]},{"t":"p","runs":[{"text":"Drop dimensions. Module 2’s singular values, or a model trained to put its important dimensions first, let you keep 256 of 768 with a modest loss in ranking quality: threefold less memory and compute. Then shrink each number. Float32 to int8 is fourfold at almost no loss. Product quantisation goes further: split the vector into sub-vectors, replace each with the index of its nearest entry in a small learned codebook, and store perhaps 64 bytes per vector instead of 3,072:"}]},{"t":"code","lang":"","label":"Text","text":"10^7 vectors × 64 bytes = 640 MB"},{"t":"p","runs":[{"text":"The 30 GB store now fits in a phone. The similarity computed from codes is approximate, which is the first place recall is spent."}]},{"t":"h2","id":"search-fewer-of-them","runs":[{"text":"Search fewer of them"}]},{"t":"p","runs":[{"text":"Partition the store into clusters, module 4’s k-means will do, with about "},{"text":"√n","code":true},{"text":" centres: 3,000 or so for ten million. A query is compared first with the 3,000 centres, then only with the vectors in the nearest few clusters. Probe 32 clusters and you examine about one per cent of the store:"}]},{"t":"code","lang":"","label":"Text","text":"3,000 centre comparisons + 1% of 10^7 = about 130,000 comparisons, against 10,000,000"},{"t":"p","runs":[{"text":"Roughly a hundredfold faster. The cost is that the true nearest neighbour sometimes sits in a cluster you did not probe; at one per cent probed, expect to miss it a few times in a hundred, and to find it nineteen times in twenty. Probing more clusters buys recall with time, and the curve between them is the thing you tune."}]},{"t":"h2","id":"walk-a-graph-instead","runs":[{"text":"Walk a graph instead"}]},{"t":"p","runs":[{"text":"Build a graph in which each vector links to a few dozen near neighbours, with sparser long-range links layered on top. A query starts at an entry point and greedily hops to whichever neighbour is closest to it, descending the layers, until no neighbour is closer. This is HNSW, and a query typically touches a few hundred to a thousand vectors:"}]},{"t":"code","lang":"","label":"Text","text":"~1,000 comparisons per query, against 10,000,000: ten-thousandfold"},{"t":"p","runs":[{"text":"The price is memory for the links, around 100 to 300 bytes per vector on top of the vector itself, and a build time that is itself a nearest-neighbour problem, hours for ten million on a laptop. Recall is typically above 95 per cent and adjustable with a search-width parameter. Most hosted vector databases run this."}]},{"t":"h2","id":"what-recall-costs-you","runs":[{"text":"What recall costs you"}]},{"t":"p","runs":[{"text":"Every approximate method returns the true nearest neighbour some fraction of the time, and the fraction is measured, not guaranteed. A retrieval system at 95 per cent recall silently gives the wrong first passage to one query in twenty. Whether that matters depends on what sits downstream: a recommender barely notices; a system answering questions from a single retrieved document notices every time. Measure recall on your own queries against brute force on a sample, because the number in the library’s documentation was measured on a different dataset."}]},{"t":"h2","id":"the-rule-of-thumb","runs":[{"text":"The rule of thumb"}]},{"t":"code","lang":"","label":"Text","text":"under 10^5 vectors:   brute force, NumPy, no index\n10^5 to 10^6:         brute force on a GPU or with int8; index only if latency demands\nabove 10^6:           IVF or HNSW, with quantisation once memory bites\nabove 10^8:           quantise first, then partition, and expect to tune for weeks"},{"t":"p","runs":[{"text":"Every one of those lines is a consequence of "},{"text":"n × d","code":true},{"text":" and "},{"text":"n × d × 4","code":true},{"text":". Do the two multiplications for your own "},{"text":"n","code":true},{"text":" before choosing a tool."}]},{"t":"h2","id":"free-tools-and-one-more-number","runs":[{"text":"Free tools, and one more number"}]},{"t":"p","runs":[{"text":"faiss","code":true},{"text":" on a CPU implements everything above and is free; "},{"text":"hnswlib","code":true},{"text":" is a small, fast HNSW; NumPy is brute force. All run on a laptop. The one further number to know is that the query embedding must be produced by the same model, with the same normalisation, as the stored ones; module 1’s cosine lesson explained why, and a store of unit vectors searched with an un-normalised query returns confidently wrong answers at any scale, with a perfect index."}]}],"check":{"question":[{"text":"A team with 40,000 document embeddings sets up a hosted vector database with an HNSW index before building anything else. What does the arithmetic say?"}],"options":[{"text":[{"text":"Brute force is a millisecond per query and 120 MB; the index only costs recall."}],"correct":true,"tempting":null},{"text":[{"text":"The index is essential, because 40,000 pairwise comparisons per query is far too slow."}],"correct":false,"tempting":[{"text":"40,000 dot products of length 768 is about 60 million FLOPs, well under a millisecond on a laptop; the quadratic fear does not apply to a single query against a store."}]},{"text":[{"text":"An index is needed for memory, because 40,000 vectors will not fit in a laptop’s RAM."}],"correct":false,"tempting":[{"text":"40,000 × 768 × 4 bytes is about 120 MB, which fits comfortably; memory becomes the constraint around ten million vectors, not forty thousand."}]},{"text":[{"text":"HNSW gives exact results, so there is no downside beyond the setup cost."}],"correct":false,"tempting":[{"text":"HNSW is approximate; it trades a measured recall below 100 per cent for speed, which is a bad trade when brute force was already fast."}]}],"order":[1,2,3,0],"why":null},"prev":{"slug":"graphs-as-matrices","title":"A graph is a matrix, and its paths are its powers","minutes":9},"next":{"slug":"fermi-estimates-for-ml","title":"Estimating anything to within a factor of three","minutes":9}}}