{"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":"quadratic-costs-and-pairwise-work","title":"Anything pairwise is quadratic: distances, attention and deduplication","url":"https://addaly.com/learn/maths-you-need/quadratic-costs-and-pairwise-work","position":60,"of":76,"minutes":9,"answer":"Any computation that compares every item with every other costs n² in time and memory, which is fine at ten thousand items and impossible at a million, and the fix is always the same: sort.","keyIdea":"Any computation that compares every item with every other costs n² in time and memory, which is fine at ten thousand items and impossible at a million, and the fix is always the same: sort, bucket, block or approximate so that most pairs are never formed."},"body":{"format":"markdown","text":"## The shape to recognise\n\nEvery time a computation compares each item with every other item, the work is proportional to the square of the item count. It arrives in many disguises: a distance matrix, an attention layer, a deduplication pass, a join without an index, a nested loop over the same list. The disguises differ; the arithmetic does not, and it is the arithmetic that decides when the pipeline stops working.\n\n## Pairwise distances\n\nTen thousand embeddings of dimension 768, and you want every pairwise similarity. That is `n²/2 = 5 × 10^7` pairs, each a dot product of 768 multiply-adds:\n\n```\n5 × 10^7 × 768 × 2 ≈ 7.7 × 10^10 FLOPs   → under a second on a laptop\nmatrix: 10^8 entries × 4 bytes = 400 MB   → fits\n```\n\nNow a million embeddings:\n\n```\n5 × 10^11 pairs × 1536 ≈ 7.7 × 10^14 FLOPs   → about two hours at 10^11 FLOP/s\nmatrix: 10^12 entries × 4 bytes = 4 TB       → does not fit anywhere you own\n```\n\nA hundredfold more items, ten-thousandfold more work and memory. The FLOPs are survivable with patience; the matrix is not. Whatever you were going to do with all the pairs, you have to do it without materialising them.\n\n## Attention\n\nA transformer layer computes, for every token, a score against every other token in the context. For context length `L` and model width `d`, the scores and the weighted sum together cost about `4 × L × d` FLOPs per token per layer. The layer's ordinary linear parts cost about `24 × d²` per token. Set them equal:\n\n```\n4 L d = 24 d²   →   L = 6 d\n```\n\nFor `d = 4096` the crossover is at about 24,600 tokens. Below that, attention is the smaller cost; at `L = 4096` it is a sixth of the linear layers. Above it, attention dominates, and at `L = 100,000` it is four times the rest. A model with a long context is a model whose cost per token grows with how much it has already read.\n\nThe memory is worse than the FLOPs. The score matrix is `L × L` per head. At `L = 32,768` in half precision that is `32768² × 2` bytes: 2.1 GB, per head, per layer. It never fits. The technique called flash attention exists to compute the softmax and the weighted sum in blocks without ever writing that matrix out, and the reason it was necessary is on this page. The course `how-llms-work` covers what was built; this is the number that forced it.\n\n## Deduplication\n\nA corpus of a million documents, and you want to remove near-duplicates. Comparing every pair is `5 × 10^11` comparisons, each of which reads two documents. At a microsecond per comparison, six days. And the corpora people actually deduplicate are a thousand times larger, which makes it sixteen thousand years.\n\nNobody does that. The standard replacement hashes each document into a short signature such that similar documents share signature pieces with high probability, then only compares documents that landed in the same bucket. The hashing lesson explains the mechanism; the effect is to turn `n²` into roughly `n log n`, and sixteen thousand years into an afternoon.\n\n## Four ways out\n\nThe pattern is always the same: the cost comes from *comparing everything with everything*, so stop.\n\n1. **Sort, then scan neighbours.** Exact duplicates, and anything with a total order, fall out of a sort in `n log n`.\n2. **Bucket by a hash.** Put items that could match into the same bucket, then compare within buckets. Works when a cheap key predicts a match.\n3. **Block by structure.** Compare only within the same date, the same language, the same customer. The pairs across blocks were never going to match.\n4. **Accept approximation.** For nearest neighbours, the index structures in the lesson on search find the right answer nineteen times in twenty at a ten-thousandth of the cost.\n\n## Spotting it in code\n\n```python\nfor a in items:\n    for b in items:          # same collection twice: quadratic\n        if similar(a, b): ...\n```\n\nThe give-away is the same collection in both loops, or a call like `distance_matrix`, `pairwise`, `cdist`, or a join with no key. None of these is wrong at a thousand items. All of them are wrong at a million, and the code gives no warning between the two.\n\n## The one honest quadratic\n\nSometimes you need all the pairs, because the answer is about the pairs: a full attention matrix for a short sequence, a correlation matrix among a hundred features, a confusion matrix among fifty classes. The rule is not \"never quadratic\". It is: know the `n`, square it, and multiply by the cost of one pair *before* you run it. If the product is under `10^10`, run it. If it is over `10^14`, you are choosing among the four ways out, and the only question is which."},"check":{"question":"A transformer with width d = 4096 is run at a context length of 4,096 tokens and then at 100,000. What happens to the share of compute spent on attention scores?","options":[{"text":"It stays roughly constant, because attention is a fixed fraction of every layer.","correct":false,"tempting":"Attention cost per token grows with L while the linear layers do not, so the fraction cannot be fixed."},{"text":"It rises from about a sixth of the linear layers' cost to about four times it.","correct":true},{"text":"It rises in proportion to the context, so about 25 times more in absolute terms but the same share.","correct":false,"tempting":"The absolute cost of attention does rise about 25-fold, but the linear layers stay put, so the share rises too; the crossover is at L = 6d."},{"text":"It falls, because a longer context amortises the score computation over more tokens.","correct":false,"tempting":"Each token scores against every other, so a longer context means more work per token, not less."}]},"prev":{"slug":"flops-of-a-matrix-multiply","title":"Counting the floating-point operations in a layer and a training run","url":"https://addaly.com/learn/maths-you-need/flops-of-a-matrix-multiply"},"next":{"slug":"memory-arithmetic","title":"Bytes per parameter, and the arithmetic of what fits on a card","url":"https://addaly.com/learn/maths-you-need/memory-arithmetic"},"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) 'Anything pairwise is quadratic: distances, attention and deduplication', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/quadratic-costs-and-pairwise-work (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":"Anything pairwise is quadratic: distances, attention and deduplication","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":"Any computation that compares every item with every other costs n² in time and memory, which is fine at ten thousand items and impossible at a million, and the fix is always the same: sort, bucket, block or approximate so that most pairs are never formed.","hero":{"kind":"plate","image":null,"alt":null,"caption":null},"blocks":[{"t":"h2","id":"the-shape-to-recognise","runs":[{"text":"The shape to recognise"}]},{"t":"p","runs":[{"text":"Every time a computation compares each item with every other item, the work is proportional to the square of the item count. It arrives in many disguises: a distance matrix, an attention layer, a deduplication pass, a join without an index, a nested loop over the same list. The disguises differ; the arithmetic does not, and it is the arithmetic that decides when the pipeline stops working."}]},{"t":"h2","id":"pairwise-distances","runs":[{"text":"Pairwise distances"}]},{"t":"p","runs":[{"text":"Ten thousand embeddings of dimension 768, and you want every pairwise similarity. That is "},{"text":"n²/2 = 5 × 10^7","code":true},{"text":" pairs, each a dot product of 768 multiply-adds:"}]},{"t":"code","lang":"","label":"Text","text":"5 × 10^7 × 768 × 2 ≈ 7.7 × 10^10 FLOPs   → under a second on a laptop\nmatrix: 10^8 entries × 4 bytes = 400 MB   → fits"},{"t":"p","runs":[{"text":"Now a million embeddings:"}]},{"t":"code","lang":"","label":"Text","text":"5 × 10^11 pairs × 1536 ≈ 7.7 × 10^14 FLOPs   → about two hours at 10^11 FLOP/s\nmatrix: 10^12 entries × 4 bytes = 4 TB       → does not fit anywhere you own"},{"t":"p","runs":[{"text":"A hundredfold more items, ten-thousandfold more work and memory. The FLOPs are survivable with patience; the matrix is not. Whatever you were going to do with all the pairs, you have to do it without materialising them."}]},{"t":"h2","id":"attention","runs":[{"text":"Attention"}]},{"t":"p","runs":[{"text":"A transformer layer computes, for every token, a score against every other token in the context. For context length "},{"text":"L","code":true},{"text":" and model width "},{"text":"d","code":true},{"text":", the scores and the weighted sum together cost about "},{"text":"4 × L × d","code":true},{"text":" FLOPs per token per layer. The layer’s ordinary linear parts cost about "},{"text":"24 × d²","code":true},{"text":" per token. Set them equal:"}]},{"t":"code","lang":"","label":"Text","text":"4 L d = 24 d²   →   L = 6 d"},{"t":"p","runs":[{"text":"For "},{"text":"d = 4096","code":true},{"text":" the crossover is at about 24,600 tokens. Below that, attention is the smaller cost; at "},{"text":"L = 4096","code":true},{"text":" it is a sixth of the linear layers. Above it, attention dominates, and at "},{"text":"L = 100,000","code":true},{"text":" it is four times the rest. A model with a long context is a model whose cost per token grows with how much it has already read."}]},{"t":"p","runs":[{"text":"The memory is worse than the FLOPs. The score matrix is "},{"text":"L × L","code":true},{"text":" per head. At "},{"text":"L = 32,768","code":true},{"text":" in half precision that is "},{"text":"32768² × 2","code":true},{"text":" bytes: 2.1 GB, per head, per layer. It never fits. The technique called flash attention exists to compute the softmax and the weighted sum in blocks without ever writing that matrix out, and the reason it was necessary is on this page. The course "},{"text":"how-llms-work","code":true},{"text":" covers what was built; this is the number that forced it."}]},{"t":"h2","id":"deduplication","runs":[{"text":"Deduplication"}]},{"t":"p","runs":[{"text":"A corpus of a million documents, and you want to remove near-duplicates. Comparing every pair is "},{"text":"5 × 10^11","code":true},{"text":" comparisons, each of which reads two documents. At a microsecond per comparison, six days. And the corpora people actually deduplicate are a thousand times larger, which makes it sixteen thousand years."}]},{"t":"p","runs":[{"text":"Nobody does that. The standard replacement hashes each document into a short signature such that similar documents share signature pieces with high probability, then only compares documents that landed in the same bucket. The hashing lesson explains the mechanism; the effect is to turn "},{"text":"n²","code":true},{"text":" into roughly "},{"text":"n log n","code":true},{"text":", and sixteen thousand years into an afternoon."}]},{"t":"h2","id":"four-ways-out","runs":[{"text":"Four ways out"}]},{"t":"p","runs":[{"text":"The pattern is always the same: the cost comes from "},{"text":"comparing everything with everything","i":true},{"text":", so stop."}]},{"t":"ol","start":1,"items":[[{"text":"Sort, then scan neighbours.","b":true},{"text":" Exact duplicates, and anything with a total order, fall out of a sort in "},{"text":"n log n","code":true},{"text":"."}],[{"text":"Bucket by a hash.","b":true},{"text":" Put items that could match into the same bucket, then compare within buckets. Works when a cheap key predicts a match."}],[{"text":"Block by structure.","b":true},{"text":" Compare only within the same date, the same language, the same customer. The pairs across blocks were never going to match."}],[{"text":"Accept approximation.","b":true},{"text":" For nearest neighbours, the index structures in the lesson on search find the right answer nineteen times in twenty at a ten-thousandth of the cost."}]]},{"t":"h2","id":"spotting-it-in-code","runs":[{"text":"Spotting it in code"}]},{"t":"code","lang":"python","label":"Python","text":"for a in items:\n    for b in items:          # same collection twice: quadratic\n        if similar(a, b): ..."},{"t":"p","runs":[{"text":"The give-away is the same collection in both loops, or a call like "},{"text":"distance_matrix","code":true},{"text":", "},{"text":"pairwise","code":true},{"text":", "},{"text":"cdist","code":true},{"text":", or a join with no key. None of these is wrong at a thousand items. All of them are wrong at a million, and the code gives no warning between the two."}]},{"t":"h2","id":"the-one-honest-quadratic","runs":[{"text":"The one honest quadratic"}]},{"t":"p","runs":[{"text":"Sometimes you need all the pairs, because the answer is about the pairs: a full attention matrix for a short sequence, a correlation matrix among a hundred features, a confusion matrix among fifty classes. The rule is not “never quadratic”. It is: know the "},{"text":"n","code":true},{"text":", square it, and multiply by the cost of one pair "},{"text":"before","i":true},{"text":" you run it. If the product is under "},{"text":"10^10","code":true},{"text":", run it. If it is over "},{"text":"10^14","code":true},{"text":", you are choosing among the four ways out, and the only question is which."}]}],"check":{"question":[{"text":"A transformer with width d = 4096 is run at a context length of 4,096 tokens and then at 100,000. What happens to the share of compute spent on attention scores?"}],"options":[{"text":[{"text":"It stays roughly constant, because attention is a fixed fraction of every layer."}],"correct":false,"tempting":[{"text":"Attention cost per token grows with L while the linear layers do not, so the fraction cannot be fixed."}]},{"text":[{"text":"It rises from about a sixth of the linear layers’ cost to about four times it."}],"correct":true,"tempting":null},{"text":[{"text":"It rises in proportion to the context, so about 25 times more in absolute terms but the same share."}],"correct":false,"tempting":[{"text":"The absolute cost of attention does rise about 25-fold, but the linear layers stay put, so the share rises too; the crossover is at L = 6d."}]},{"text":[{"text":"It falls, because a longer context amortises the score computation over more tokens."}],"correct":false,"tempting":[{"text":"Each token scores against every other, so a longer context means more work per token, not less."}]}],"order":[3,2,0,1],"why":null},"prev":{"slug":"flops-of-a-matrix-multiply","title":"Counting the floating-point operations in a layer and a training run","minutes":9},"next":{"slug":"memory-arithmetic","title":"Bytes per parameter, and the arithmetic of what fits on a card","minutes":9}}}