Comparing every pair of $N$ documents by cosine similarity takes $N(N-1)/2$ comparisons, about 450 million at 30,000 documents. In the course assignment benchmarked here, 30,000 documents took 1,928 seconds with a Python loop, 369 with a parallel version and 56 with a sparse-matrix product (three weighting schemes per run). The inverted index skips pairs that share no term, but in the 10,788 Reuters stories of the NLTK subset 84.2% of pairs share a word after a 33-word stop list. Dropping the 197 words in over 5% of stories leaves 25.3% of pairs touched. On the running example raw counts make the car review and the car-loan page closest (0.563), while TF-IDF and sublinear weights pick the car review and the auto-insurance page (0.376 and 0.632).
Which two documents of this topic's running example are most alike: the car review and the car-loan page, which both repeat car, or the car review and the auto-insurance page, which share the rarer word auto? The answer depends on the weighting. With raw counts it is the first pair, and with TF-IDF or sublinear weights it is the second. A harder problem hides behind it. Four documents have six pairs, but a collection of 30,000 has nearly 450 million. Finding the most similar pairs in a whole collection costs time that grows with the square of its size, and this article measures that cost and the ways to reduce it.
Cosine similarity is symmetric: it compares any two vectors, not only a query with a document. Comparing documents with each other supports many tasks. It can find duplicates and near-duplicates, suggest related articles, offer a "more like this" link (Manning, Raghavan, and Schütze, 2008, §6.3.1), and group documents for clustering. The most demanding form of the task is all-pairs similarity: find the $k$ most similar pairs of documents in an entire collection. That was the third assignment in the course, and this article uses my solution, HW03 on GitHub, to show why the problem is hard and how much the implementation matters.
Here is the route. First we count the pairs and see why the problem is quadratic. Then we look at the assignment's three implementations, their benchmarks, and the memory limit that the fastest one meets. Next we use the inverted index to skip pairs that share no term, and count how much that saves on 10,788 Reuters news stories. Finally we return to the running example, see how the weighting changes which pairs come out on top, and solve the assignment on it in full.
Why all-pairs is quadratic
A collection of $N$ documents has $N(N-1)/2$ distinct pairs:
| Documents | Pairs |
|---|---|
| 1,000 | 499,500 |
| 5,000 | 12,497,500 |
| 30,000 | 449,985,000 |
| 1,000,000 | about $5 \times 10^{11}$ |
Each comparison is a cosine similarity between two sparse vectors. Multiplying the collection size by 30 multiplies the number of pairs by about 900. No amount of constant-factor optimization changes that growth. So the practical questions are how small the constant can be made, and how many of the pairs can be skipped without computing them.
The assignment
HW03 asked for the most similar document pairs in a collection under three weighting schemes:
- tf: raw term frequency;
- tf-idf: term frequency times $\log_{10}(N/\mathit{df})$, as in TF-IDF weighting;
- wf-idf: sublinear term frequency $1 + \log_{10} \mathit{tf}$ times the same IDF, as in variants of TF-IDF.
Each document's vector is weighted and its length precomputed once. Each comparison then reduces to a dot product over the terms the two documents share, divided by the two stored lengths.
I wrote three implementations behind a common interface, with a factory that chooses among them at run time (see designing a modular search engine):
- Standard: a single-process loop over the upper triangle of the pair matrix. Each document is stored as a dictionary of term weights. For each pair, the code intersects the two dictionaries' keys, skips pairs with no common terms, computes the dot product over the shared terms, and keeps the best $k$ pairs in a min-heap.
- Parallel: the same computation divided into tiles, each covering a block of documents compared against another block. Each task copies its blocks' weight vectors to a worker process. The worker returns every pair with nonzero similarity, and the parent process selects the top $k$ with a heap.
- Sparse: the weighted collection as a sparse matrix in compressed sparse row (CSR) format. All pairwise cosines are computed at once by scikit-learn's
cosine_similarity, and the top $k$ are selected with NumPy'sargpartition, which finds the largest values without fully sorting.
The benchmarks below compare the three as the collection grows.
Benchmarks
I measured all three on collections of increasing size, on my own machine. Times are in seconds. The program computes all three weighting schemes on every run, so each time covers three all-pairs passes plus building the model:
| Documents | Standard | Parallel | Sparse |
|---|---|---|---|
| 1,000 | 2.84 | 11.96 | 1.01 |
| 2,000 | 9.90 | 15.17 | 1.99 |
| 3,000 | 18.52 | 18.06 | 3.00 |
| 4,000 | 31.82 | 22.33 | 4.07 |
| 5,000 | 48.57 | 25.76 | 4.97 |
| 15,000 | 449.50 | 101.26 | 20.97 |
| 30,000 | 1,928.29 | 368.93 | 55.89 |
The quadratic growth is visible. From 1,000 to 30,000 documents, the standard implementation's time grew by a factor of 679, approaching the factor of 901 in the number of pairs.
Parallelism has a fixed cost. Starting worker processes, copying weight vectors to them, and returning every nonzero pair to the parent costs several seconds. So the parallel version was four times slower than the standard one at 1,000 documents. The two crossed between 2,000 and 3,000 documents, and beyond that parallelism paid off, reaching a fivefold speedup at 30,000. The factory's threshold of 2,500 documents for choosing the parallel version came from this measurement.
Sparse matrices win twice. The sparse implementation, running in a single process, was the fastest at every size. It beat the standard version by a factor of 35 at 30,000 documents, and the parallel one by nearly 7. Part of the advantage is that its arithmetic runs in compiled routines rather than a Python loop. The other part is that it does less work. Multiplying the weighted document matrix by its transpose only combines documents that share a term, so pairs with nothing in common are never visited. That is the inverted-index strategy described below, carried out by a sparse-matrix library.
Logarithmic axes turn the question "how fast does the cost grow?" into "how steep is the line?". If time is $c N^a$, then $\log(\text{time}) = \log c + a \log N$, a straight line of slope $a$. Over the three largest sizes, the least-squares slopes of $\log(\text{time})$ against $\log N$ are 2.05 for the standard implementation, 1.46 for the parallel one and 1.35 for the sparse one.
The standard implementation is in the quadratic regime already. The other two grow more slowly over this range. The benchmarks do not say why, and the following explanation is a hypothesis, not a measurement. Part of their time goes to work that grows roughly linearly with $N$, such as building the weighted vectors and starting workers. And pairs with no shared term cost the sparse product nothing. If that is right, the quadratic part dominates as $N$ grows and their slopes approach 2 as well. A run at a larger size would test it.
The sparse version is fast, but it has a cost the timings do not show.
The memory wall
The sparse implementation computes the entire similarity matrix at once. Its time is excellent, but its memory grows with the number of document pairs that share at least one term. In a collection where common words survive stop-word removal, a large fraction of pairs share some term, so the "sparse" result can be nearly dense.
Reuters-21578 has 21,578 news stories. The subset distributed with the NLTK toolkit, the one term statistics measures, has 10,788 of them. In those 10,788 stories, 84% of the 58 million pairs share at least one word even after a 33-word stop list is removed. Words such as said occur in most stories (measurements below). At 30,000 documents, a dense matrix of 4-byte floats would need 3.6 gigabytes. A nearly full sparse matrix would need more, since it stores an index alongside each value. At a million documents the dense matrix would need 4 terabytes.
The time cost is quadratic, and so, unless the computation is restructured, is the memory cost. The standard remedy is to process the matrix in blocks of rows, keeping only each block's best candidates before moving on. That preserves the speed of vectorized code while bounding memory.
Skipping pairs with the inverted index
The standard and parallel implementations consider every pair, even pairs that share no terms and whose similarity is therefore zero. They check for shared terms before computing anything, but the check itself is made for every pair. The inverted index lets an algorithm touch only pairs that share a term. Treat each document in turn as a query, and accumulate dot products from the postings lists of its terms, exactly as in computing vector scores. Every pair that shares no term is never visited.
The work then depends on the postings lists rather than on $N^2$. A term with document frequency $\mathit{df}_t$ contributes a partial product to each of the roughly $\mathit{df}_t^2 / 2$ pairs of documents containing it. Rare terms cost almost nothing, while a very common term costs nearly as much as the full quadratic computation. Common terms also have low IDF and contribute little to similarity. So practical systems drop or down-weight them, accepting slightly approximate scores in exchange for a large saving.
Counting the work
The running example of this topic (four documents, introduced in TF-IDF weighting) shows the accounting on a small scale. Its postings lists have document frequencies 2 (auto), 3 (best), 3 (car), 2 (insurance), 1 (loan) and 2 (rate).
Example (more products than pairs). The collection has $4 \times 3 / 2 = 6$ pairs, and the inverted-index method computes more partial products than that, nine. Each list generates one partial product for each pair of documents within it, $\mathit{df}_t(\mathit{df}_t - 1)/2$, so the terms generate $1 + 3 + 3 + 1 + 0 + 1 = 9$. Every one of the six pairs shares at least one term, so the method skips nothing here and does more multiplications than comparing every pair would. A pair that shares $m$ terms receives $m$ partial products, one from each shared term's list.
On a real collection the balance depends on the common terms. The table counts, for the 10,788 documents of the NLTK subset of Reuters-21578 (words lowercased, no stemming), the pairs that share at least one word and the partial products the inverted-index method would compute, $\sum_t \mathit{df}_t(\mathit{df}_t - 1)/2$:
| Terms indexed | Pairs sharing a term | Partial products | Products per pair |
|---|---|---|---|
| all words | 90.0% | 492.6 million | 8.47 |
| 33-word stop list removed | 84.2% | 254.9 million | 4.38 |
| also words in more than 10% of documents (60 words) | 42.0% | 68.4 million | 1.18 |
| also words in more than 5% of documents (197 words) | 25.3% | 31.8 million | 0.55 |
"Products per pair" divides the partial products by all 58,185,078 pairs. Read down the table:
- All words. The inverted-index method skips only the 10% of pairs that share nothing. It computes more than eight partial products for every pair in the collection, because nearly every pair shares of, the or to and each shared word adds a product.
- Stop list removed. The products halve, and said (in 6,784 of the 10,788 stories) becomes the commonest term.
- Common words dropped. Dropping the 197 words that occur in more than 5% of the stories, under 1% of the vocabulary of about 29,000 words, cuts the products by a factor of eight more. Three-quarters of all pairs are then never touched.
The saving that makes the inverted-index method fast comes from setting aside a small number of very common terms. The cost is that similarities are computed without them.
When only pairs above a similarity threshold are wanted, much more can be skipped. Bayardo, Ma, and Srikant (2007) showed how to index only part of each vector, the part needed to guarantee that any pair above the threshold is found. Most low-similarity pairs are then never considered. Their method computes the exact answer, and they report large speedups over the earlier exact methods they compared it with.
Approximate methods
For web-scale collections, even these methods are too slow, and systems accept approximate answers. Locality-sensitive hashing assigns each document short signatures chosen so that similar documents are likely to share them. Candidate pairs are then only those that share a signature, and only they are compared exactly.
- MinHash signatures estimate the overlap between documents' sets of word sequences, the basis of near-duplicate detection on the web (Broder, 1997; Manning, Raghavan, and Schütze, 2008, §19.6).
- Random-projection signatures estimate cosine similarity directly (Charikar, 2002). Locality-sensitive hashing derives the collision probability of these signatures, $1 - \theta/\pi$ for vectors at angle $\theta$, and measures the index built from them.
Both reduce the problem from all pairs to the candidate pairs that share a signature. Speed aside, which pairs count as "most similar" depends on the weights. Back to the running example.
What the weighting changes
The three weighting schemes find different "most similar" pairs. With raw term frequency, documents that share heavily repeated common terms look similar regardless of subject. IDF reduces the influence of terms that appear everywhere, so pairs are matched on distinctive vocabulary. Sublinear weighting further reduces the influence of any one repeated term.
The running example shows all three effects on its six pairs. The cosines below use the three HW03 schemes, each with cosine normalization (nnc, ntc and ltc in the SMART notation of variants of TF-IDF), rounded to three decimals:
| Pair | tf | tf-idf | wf-idf |
|---|---|---|---|
| $d_1$, $d_2$ (headline, car review) | 0.527 | 0.239 | 0.148 |
| $d_1$, $d_3$ (headline, auto insurance) | 0.309 | 0.374 | 0.439 |
| $d_1$, $d_4$ (headline, car loans) | 0.562 | 0.275 | 0.324 |
| $d_2$, $d_3$ (car review, auto insurance) | 0.244 | 0.376 | 0.632 |
| $d_2$, $d_4$ (car review, car loans) | 0.563 | 0.154 | 0.149 |
| $d_3$, $d_4$ (auto insurance, car loans) | 0.087 | 0.011 | 0.031 |
The opening question has three answers, one per column:
- Raw counts. The most similar pair is the car review and the car-loan page, which share the repeated words car and best. The three pairs involving car fill the top.
- IDF. It demotes car and best, which are in three of the four documents, and the pairs linked by rarer words rise. The headline and the auto-insurance page share insurance, and the car review and the auto-insurance page share auto.
- Sublinear weighting. It reduces the car review's five occurrences of car, which makes its vector point more toward auto and best. The review and the auto-insurance page become the clear top pair.
That is a reminder of what these measures see. A tempting reading is that the top pair is about the same thing. It is not. The two documents share two words, one of them rare in this collection, and nothing in the vectors records that one page is about buying a car and the other about insuring one.
In a collection containing exact or near duplicates, those pairs rank at the top under every scheme, with cosine values at or near 1. That is why duplicate detection is often the first practical use of an all-pairs comparison.
Worked problems
The first problem is the course's third assignment, the one whose implementations were benchmarked above, stated for the running example so that it can be solved by hand. The other two are posed on the same example and on the figures of this article. All numbers are computed by tools/experiments/vsm/running_example.py.
Problem 1 (the assignment on four documents). For the four documents of the running example, compute the cosine similarity of every pair under each of three weightings: raw term frequency (tf), term frequency times $\log_{10}(N/\mathit{df})$ (tf-idf), and $1 + \log_{10} \mathit{tf}$ times the same IDF (wf-idf). Report the three most similar pairs under each.
Solution. The most similar pair is the car review and the car-loan page under tf, and the car review and the auto-insurance page under the other two weightings. The method is the one the implementations use: weight every document's vector once, divide it by its length once, and then take the dot product of each pair over the terms the two share.
Raw term frequency. The vectors are the columns of the count matrix. Their lengths are $\sqrt{1 + 1 + 1} = \sqrt{3} \approx 1.732$ for $d_1$, $\sqrt{1 + 4 + 25} = \sqrt{30} \approx 5.477$ for $d_2$, $\sqrt{9 + 1 + 4} = \sqrt{14} \approx 3.742$ for $d_3$ and $\sqrt{4 + 9 + 16 + 9} = \sqrt{38} \approx 6.164$ for $d_4$. Normalized:
| Term | $d_1$ | $d_2$ | $d_3$ | $d_4$ |
|---|---|---|---|---|
| auto | 0 | 0.183 | 0.802 | 0 |
| best | 0 | 0.365 | 0.267 | 0.324 |
| car | 0.577 | 0.913 | 0 | 0.487 |
| insurance | 0.577 | 0 | 0.535 | 0 |
| loan | 0 | 0 | 0 | 0.649 |
| rate | 0.577 | 0 | 0 | 0.487 |
Each cosine is a sum over shared terms, most easily written with the counts and the two lengths:
| Pair | Shared terms | Cosine |
|---|---|---|
| $d_1$, $d_2$ | car | $(1 \times 5)/(\sqrt{3}\sqrt{30}) = 0.527$ |
| $d_1$, $d_3$ | insurance | $(1 \times 2)/(\sqrt{3}\sqrt{14}) = 0.309$ |
| $d_1$, $d_4$ | car, rate | $(1 \times 3 + 1 \times 3)/(\sqrt{3}\sqrt{38}) = 0.562$ |
| $d_2$, $d_3$ | auto, best | $(1 \times 3 + 2 \times 1)/(\sqrt{30}\sqrt{14}) = 0.244$ |
| $d_2$, $d_4$ | best, car | $(2 \times 2 + 5 \times 3)/(\sqrt{30}\sqrt{38}) = 0.563$ |
| $d_3$, $d_4$ | best | $(1 \times 2)/(\sqrt{14}\sqrt{38}) = 0.087$ |
The top three are ($d_2$, $d_4$) at 0.563, ($d_1$, $d_4$) at 0.562 and ($d_1$, $d_2$) at 0.527. The first two are separated only in the fourth decimal, 0.5627 against 0.5620.
TF-IDF. The weighted vectors are the columns of the TF-IDF matrix in TF-IDF weighting, with lengths 0.444, 0.737, 1.093 and 2.611, and the normalized vectors are tabulated in cosine similarity. For the two closest pairs:
- ($d_2$, $d_3$) share auto and best: $0.408 \times 0.827 + 0.339 \times 0.114 = 0.338 + 0.039 = 0.376$.
- ($d_1$, $d_3$) share insurance: $0.678 \times 0.551 = 0.374$.
The third is ($d_1$, $d_4$) at 0.275, through car and rate: $0.282 \times 0.144 + 0.678 \times 0.346 = 0.040 + 0.235$ (products from unrounded weights).
wf-idf. Each count $\mathit{tf}$ is replaced by $1 + \log_{10} \mathit{tf}$ before the IDF is applied. The headline's counts are all 1, so its vector is unchanged. The lengths are 0.444, 0.403, 0.606 and 1.090. Normalized:
| Term | $d_1$ | $d_2$ | $d_3$ | $d_4$ |
|---|---|---|---|---|
| auto | 0 | 0.748 | 0.734 | 0 |
| best | 0 | 0.404 | 0.206 | 0.149 |
| car | 0.282 | 0.527 | 0 | 0.169 |
| insurance | 0.678 | 0 | 0.647 | 0 |
| loan | 0 | 0 | 0 | 0.885 |
| rate | 0.678 | 0 | 0 | 0.408 |
The top pair is ($d_2$, $d_3$): $0.748 \times 0.734 + 0.404 \times 0.206 = 0.549 + 0.083 = 0.632$. Then ($d_1$, $d_3$), $0.678 \times 0.647 = 0.439$, and ($d_1$, $d_4$), $0.282 \times 0.169 + 0.678 \times 0.408 = 0.048 + 0.277 = 0.324$. The complete table of eighteen cosines is the one in "What the weighting changes". The car review's normalized weight on car falls from 0.913 under tf to 0.527 under wf-idf, and its normalized weight on auto rises from 0.183 to 0.748. That shift is what moves its nearest neighbor from the car-loan page to the auto-insurance page.
Problem 2 (one document as a query). Using the inverted index and the normalized TF-IDF vectors, accumulate the similarities of the car review $d_2$ to every other document, listing each partial product.
Solution. Five partial products give $d_3$ 0.376, $d_1$ 0.239 and $d_4$ 0.154. The car review contains auto, best and car, with normalized weights 0.408, 0.339 and 0.848. Reading the three postings lists and skipping $d_2$ itself:
| Postings list | Document | Partial product | Accumulator after |
|---|---|---|---|
| auto | $d_3$ | 0.408 × 0.827 = 0.338 | $d_3$ 0.338 |
| best | $d_3$ | 0.339 × 0.114 = 0.039 | $d_3$ 0.376 |
| best | $d_4$ | 0.339 × 0.096 = 0.032 | $d_4$ 0.032 |
| car | $d_1$ | 0.848 × 0.282 = 0.239 | $d_1$ 0.239 |
| car | $d_4$ | 0.848 × 0.144 = 0.122 | $d_4$ 0.154 |
(Accumulators are computed from unrounded products.) The lists of insurance, loan and rate are never opened, because $d_2$ does not contain those terms. This is CosineScore with a document in the place of the query, and with both sides normalized in advance. Doing the same for every document, and keeping only pairs in which the second document has the larger docID, computes each of the nine partial products of the collection exactly once.
Problem 3 (sizes). (a) A collection of 30,000 documents has one term that occurs in half of them. Find how many partial products that term alone generates in the inverted-index method, as a count and as a fraction of all pairs. (b) Find the memory needed for a dense similarity matrix of 4-byte values for the 10,788 Reuters stories.
Solution. (a) The term generates 112,492,500 partial products, a quarter of the number of pairs. A term in $\mathit{df}$ documents generates one product for each pair of them, $\mathit{df}(\mathit{df} - 1)/2 = 15{,}000 \times 14{,}999 / 2 = 112{,}492{,}500$. The collection has $30{,}000 \times 29{,}999 / 2 = 449{,}985{,}000$ pairs, and the ratio is 0.250. A term in a fraction $f$ of the documents costs about $f^2$ of the full quadratic computation, which is why a few very common terms dominate the work. (b) The matrix has $10{,}788^2 = 116{,}380{,}944$ entries, and at 4 bytes each that is 465.5 megabytes. Storing only the upper triangle, the 58,185,078 pairs, would halve it. At 30,000 documents the same matrix needs $9 \times 10^8 \times 4$ bytes, the 3.6 gigabytes quoted above.
What we have learned
All-pairs similarity is quadratic in the number of documents, in time and, for a one-shot sparse product, in memory. The assignment's benchmarks show the quadratic growth, the fixed cost of parallelism, and the large advantage of sparse-matrix code. The inverted index skips pairs that share no term, but in the 10,788 Reuters stories most pairs share a common word, and the real saving comes from setting the commonest terms aside. On the running example, the weighting decided the top pair, and the winning pair under wf-idf shares words without sharing a subject.
That last point is the model's own limit, not the implementation's. The vectors know which words a document uses, and nothing about what they mean or how they relate. Learned sparse retrieval keeps term vectors and the inverted index but lets a trained model set the weights and add related terms a text lacks. The next article, Strengths and Limits of the Vector Space Model, sets out what else the model assumes, where those assumptions fail, and what came after it.
The running-example cosines and pair counts are computed by tools/experiments/vsm/running_example.py, the Reuters counts by tools/experiments/vsm/reuters_pairs.py (exact, no sampling), and the figure by tools/figures/document-similarity.py, all in the site repository.
References
- Bayardo, R. J., Ma, Y., and Srikant, R. (2007). Scaling up all pairs similarity search. In Proceedings of WWW 2007, 131–140. record
- Broder, A. Z. (1997). On the resemblance and containment of documents. In Proceedings of Compression and Complexity of Sequences 1997, 21–29. record · 3 pages
- Charikar, M. S. (2002). Similarity estimation techniques from rounding algorithms. In Proceedings of STOC 2002, 380–388. record · 3 pages
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 6.3.1 and 19.6. Cambridge University Press. record · 102 pages
Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 8 revisions