{"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":"sparse-dense-and-one-hot","title":"Sparse and dense, and the memory each costs","url":"https://addaly.com/learn/maths-you-need/sparse-dense-and-one-hot","position":9,"of":76,"minutes":9,"answer":"Sparse representations record which items are present and dense ones record what they are like, and the arithmetic of storing each explains why serious search systems use both.","keyIdea":"Sparse representations record which items are present and dense ones record what they are like, and the arithmetic of storing each explains why serious search systems use both."},"body":{"format":"markdown","text":"## Two ways to write down a document\n\nSuppose your vocabulary has 50,000 words and you want to represent the sentence \"the train was late\".\n\n**The sparse way.** Make a vector with 50,000 slots, put a count in the slot for each word present, and zeroes everywhere else. Four non-zero entries out of 50,000. Stored naively that is 50,000 numbers; stored sensibly it is four `(index, value)` pairs, because the zeroes carry no information and need not exist.\n\n**The dense way.** Run the sentence through an embedding model and get 768 numbers, almost none of them zero, none of them individually interpretable.\n\nNeither is a better idea in general. They record different things. The sparse vector says *exactly which words are here*. The dense vector says *what this is roughly about*.\n\n## One-hot, the simplest sparse form\n\nThe atom of sparse representation is one-hot encoding: a vector with a single 1 and zeroes elsewhere. Word 8,417 in a 50,000-word vocabulary becomes a vector with 1 in position 8,417.\n\nIts properties are worth stating because they explain what came next. Every one-hot vector has length 1. The dot product between any two different one-hot vectors is 0, so every word is exactly as unrelated to every other word: `cat` and `dog` are as distant as `cat` and `parliament`. And the space needed grows with the vocabulary, one dimension per word.\n\nThe embedding table fixes all three at once. Multiply a one-hot vector by a 50,000 × 768 matrix and you select row 8,417 of that matrix. That is the entire mechanism: **an embedding lookup is a one-hot multiplication that somebody optimised into an array index.** The rows are learned, so related words end up with related rows, and the representation is 768 numbers instead of 50,000.\n\n## The memory arithmetic\n\nDo the sums, because they decide architecture.\n\nOne million documents, dense 768-dimensional embeddings, 4-byte floats:\n\n```\n1,000,000 x 768 x 4 bytes = 3,072,000,000 bytes = 3.07 GB\n```\n\nThat fits in the RAM of an ordinary laptop, which is why in-memory vector search is practical at this scale. At ten million documents it is 30.7 GB and you are buying a server or quantising. Store the same vectors as 1-byte integers instead of 4-byte floats and it falls to 768 MB, a point returned to in the module on quantisation.\n\nThe same million documents, sparse, averaging 120 distinct terms each, stored as an index plus a value at 8 bytes per pair:\n\n```\n1,000,000 x 120 x 8 bytes = 960,000,000 bytes = 0.96 GB\n```\n\nLess than the dense version, and it grows with document length rather than with vocabulary size. An inverted index (the structure behind every keyword search engine since the 1970s) makes this smaller still and queries very fast, because you only ever touch the postings lists for the words in the query.\n\n> Figure: Storing one million documents. Bars (GB for one million documents): Dense, 1,536 numbers at 4 bytes 6.14; Dense, 768 numbers at 4 bytes 3.07; Sparse, 120 terms at 8 bytes a term 0.96; Dense, 768 numbers at 1 byte 0.77. Sparse storage grows with document length, dense storage with the width of the model. Multiply every figure by ten for ten million documents, and the first two lines stop fitting on a laptop.\n\n## TF-IDF: making sparse counts behave\n\nRaw counts are a poor sparse representation because common words dominate. The classical repair is TF-IDF: multiply each term's count in a document by the inverse document frequency,\n\n```\nidf(t) = log( N / df(t) )\n```\n\nwhere `N` is the number of documents and `df(t)` how many contain the term. A word in every document gets `log(1) = 0` and vanishes. A word in one document in a thousand gets `log(1000) = 6.9` and dominates. BM25, the default in Lucene, Elasticsearch and SQLite's FTS5, is a refined version with saturation on term frequency and a correction for document length.\n\nThis is worth knowing because BM25 is a strong baseline that costs nothing to run and is hard to beat on queries containing rare exact terms: a part number, a surname, an error code, `NullPointerException`. A dense model has to have learned that token to represent it; a sparse index matches it.\n\n## Why real systems use both\n\nThe failure modes are complementary, which is the whole argument for hybrid search.\n\n- Sparse fails on synonyms and paraphrase. A query for \"cheap flights\" does not match a document saying \"budget airfare\" if no word overlaps.\n- Dense fails on rare exact strings. Ask for order `AX-99182` and the embedding has no idea; the token was probably never seen.\n\nHybrid search runs both and combines the rankings, typically with reciprocal rank fusion, which merges by rank position rather than by score and so avoids the problem that the two systems' scores are on incompatible scales. It reliably beats either alone on mixed query workloads.\n\n## The free path\n\nNone of this needs a paid service. `scikit-learn` gives you `TfidfVectorizer` in one line. SQLite ships FTS5 with BM25 built in and runs on a phone. `rank_bm25` is a small pure-Python implementation. For dense vectors, `sentence-transformers` runs a compact model on a CPU, and FAISS or `hnswlib` index them locally. A hybrid search system over a few hundred thousand documents runs on a laptop with no account anywhere.\n\n## The rule to keep\n\nSparse records identity, dense records similarity, and the memory arithmetic tells you which is affordable at your scale. If your queries contain names, codes or numbers, you need the sparse half no matter how good the embedding model gets."},"check":{"question":"A support team replaces their keyword search with dense embedding search. Overall satisfaction improves, but agents complain that searching for a specific error code such as `ERR_SSL_PROTOCOL_ERROR` now returns nothing useful. What is the mechanism?","options":[{"text":"The embedding model has a token limit and the long code is being truncated before it is embedded.","correct":false,"tempting":"Truncation happens with long documents, but a single short code is well within any model's limit; the failure is about representation, not length."},{"text":"Dense vectors are normalised, so the rare code contributes very little to the direction of the query vector and cannot dominate the match.","correct":false,"tempting":"Normalisation is real but is not the cause; even un-normalised, the model has no distinctive representation for a token it barely saw."},{"text":"The code is a rare token the model has little or no learned representation for, so its embedding carries almost no distinguishing signal, whereas an inverted index matches it exactly.","correct":true},{"text":"Cosine similarity cannot represent exact matches, only approximate ones, so exact-string queries always fail.","correct":false,"tempting":"Cosine returns 1.0 for identical vectors and handles exact matches fine; the problem is upstream, in what the model encoded."}]},"prev":{"slug":"high-dimensional-strangeness","title":"Why your 3-D intuition is wrong in 768 dimensions","url":"https://addaly.com/learn/maths-you-need/high-dimensional-strangeness"},"next":{"slug":"matrix-multiplication-by-hand","title":"Doing a matrix multiplication yourself, once","url":"https://addaly.com/learn/maths-you-need/matrix-multiplication-by-hand"},"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) 'Sparse and dense, and the memory each costs', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/sparse-dense-and-one-hot (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":"Sparse and dense, and the memory each costs","courseTitle":"The Maths You Actually Need","module":{"index":1,"slug":"vectors-and-space","title":"Vectors, and the space they live in"},"answer":null,"keyIdea":"Sparse representations record which items are present and dense ones record what they are like, and the arithmetic of storing each explains why serious search systems use both.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"caption":"Sparse storage grows with document length, dense storage with the width of the model. Multiply every figure by ten for ten million documents, and the first two lines stop fitting on a laptop.","series":[{"label":"Dense, 1,536 numbers at 4 bytes","value":6.14},{"highlight":true,"label":"Dense, 768 numbers at 4 bytes","value":3.07},{"label":"Sparse, 120 terms at 8 bytes a term","value":0.96},{"label":"Dense, 768 numbers at 1 byte","value":0.77}],"title":"Storing one million documents","type":"bars","unit":"GB for one million documents"},"alt":"Figure: Storing one million documents. Bars (GB for one million documents): Dense, 1,536 numbers at 4 bytes 6.14; Dense, 768 numbers at 4 bytes 3.07; Sparse, 120 terms at 8 bytes a term 0.96; Dense, 768 numbers at 1 byte 0.77. Sparse storage grows with document length, dense storage with the width of the model. Multiply every figure by ten for ten million documents, and the first two lines stop fitting on a laptop."}},"blocks":[{"t":"h2","id":"two-ways-to-write-down-a-document","runs":[{"text":"Two ways to write down a document"}]},{"t":"p","runs":[{"text":"Suppose your vocabulary has 50,000 words and you want to represent the sentence “the train was late”."}]},{"t":"p","runs":[{"text":"The sparse way.","b":true},{"text":" Make a vector with 50,000 slots, put a count in the slot for each word present, and zeroes everywhere else. Four non-zero entries out of 50,000. Stored naively that is 50,000 numbers; stored sensibly it is four "},{"text":"(index, value)","code":true},{"text":" pairs, because the zeroes carry no information and need not exist."}]},{"t":"p","runs":[{"text":"The dense way.","b":true},{"text":" Run the sentence through an embedding model and get 768 numbers, almost none of them zero, none of them individually interpretable."}]},{"t":"p","runs":[{"text":"Neither is a better idea in general. They record different things. The sparse vector says "},{"text":"exactly which words are here","i":true},{"text":". The dense vector says "},{"text":"what this is roughly about","i":true},{"text":"."}]},{"t":"h2","id":"one-hot-the-simplest-sparse-form","runs":[{"text":"One-hot, the simplest sparse form"}]},{"t":"p","runs":[{"text":"The atom of sparse representation is one-hot encoding: a vector with a single 1 and zeroes elsewhere. Word 8,417 in a 50,000-word vocabulary becomes a vector with 1 in position 8,417."}]},{"t":"p","runs":[{"text":"Its properties are worth stating because they explain what came next. Every one-hot vector has length 1. The dot product between any two different one-hot vectors is 0, so every word is exactly as unrelated to every other word: "},{"text":"cat","code":true},{"text":" and "},{"text":"dog","code":true},{"text":" are as distant as "},{"text":"cat","code":true},{"text":" and "},{"text":"parliament","code":true},{"text":". And the space needed grows with the vocabulary, one dimension per word."}]},{"t":"p","runs":[{"text":"The embedding table fixes all three at once. Multiply a one-hot vector by a 50,000 × 768 matrix and you select row 8,417 of that matrix. That is the entire mechanism: "},{"text":"an embedding lookup is a one-hot multiplication that somebody optimised into an array index.","b":true},{"text":" The rows are learned, so related words end up with related rows, and the representation is 768 numbers instead of 50,000."}]},{"t":"h2","id":"the-memory-arithmetic","runs":[{"text":"The memory arithmetic"}]},{"t":"p","runs":[{"text":"Do the sums, because they decide architecture."}]},{"t":"p","runs":[{"text":"One million documents, dense 768-dimensional embeddings, 4-byte floats:"}]},{"t":"code","lang":"","label":"Text","text":"1,000,000 x 768 x 4 bytes = 3,072,000,000 bytes = 3.07 GB"},{"t":"p","runs":[{"text":"That fits in the RAM of an ordinary laptop, which is why in-memory vector search is practical at this scale. At ten million documents it is 30.7 GB and you are buying a server or quantising. Store the same vectors as 1-byte integers instead of 4-byte floats and it falls to 768 MB, a point returned to in the module on quantisation."}]},{"t":"p","runs":[{"text":"The same million documents, sparse, averaging 120 distinct terms each, stored as an index plus a value at 8 bytes per pair:"}]},{"t":"code","lang":"","label":"Text","text":"1,000,000 x 120 x 8 bytes = 960,000,000 bytes = 0.96 GB"},{"t":"p","runs":[{"text":"Less than the dense version, and it grows with document length rather than with vocabulary size. An inverted index (the structure behind every keyword search engine since the 1970s) makes this smaller still and queries very fast, because you only ever touch the postings lists for the words in the query."}]},{"t":"h2","id":"tf-idf-making-sparse-counts-behave","runs":[{"text":"TF-IDF: making sparse counts behave"}]},{"t":"p","runs":[{"text":"Raw counts are a poor sparse representation because common words dominate. The classical repair is TF-IDF: multiply each term’s count in a document by the inverse document frequency,"}]},{"t":"code","lang":"","label":"Text","text":"idf(t) = log( N / df(t) )"},{"t":"p","runs":[{"text":"where "},{"text":"N","code":true},{"text":" is the number of documents and "},{"text":"df(t)","code":true},{"text":" how many contain the term. A word in every document gets "},{"text":"log(1) = 0","code":true},{"text":" and vanishes. A word in one document in a thousand gets "},{"text":"log(1000) = 6.9","code":true},{"text":" and dominates. BM25, the default in Lucene, Elasticsearch and SQLite’s FTS5, is a refined version with saturation on term frequency and a correction for document length."}]},{"t":"p","runs":[{"text":"This is worth knowing because BM25 is a strong baseline that costs nothing to run and is hard to beat on queries containing rare exact terms: a part number, a surname, an error code, "},{"text":"NullPointerException","code":true},{"text":". A dense model has to have learned that token to represent it; a sparse index matches it."}]},{"t":"h2","id":"why-real-systems-use-both","runs":[{"text":"Why real systems use both"}]},{"t":"p","runs":[{"text":"The failure modes are complementary, which is the whole argument for hybrid search."}]},{"t":"ul","items":[[{"text":"Sparse fails on synonyms and paraphrase. A query for “cheap flights” does not match a document saying “budget airfare” if no word overlaps."}],[{"text":"Dense fails on rare exact strings. Ask for order "},{"text":"AX-99182","code":true},{"text":" and the embedding has no idea; the token was probably never seen."}]]},{"t":"p","runs":[{"text":"Hybrid search runs both and combines the rankings, typically with reciprocal rank fusion, which merges by rank position rather than by score and so avoids the problem that the two systems’ scores are on incompatible scales. It reliably beats either alone on mixed query workloads."}]},{"t":"h2","id":"the-free-path","runs":[{"text":"The free path"}],"role":"free"},{"t":"p","runs":[{"text":"None of this needs a paid service. "},{"text":"scikit-learn","code":true},{"text":" gives you "},{"text":"TfidfVectorizer","code":true},{"text":" in one line. SQLite ships FTS5 with BM25 built in and runs on a phone. "},{"text":"rank_bm25","code":true},{"text":" is a small pure-Python implementation. For dense vectors, "},{"text":"sentence-transformers","code":true},{"text":" runs a compact model on a CPU, and FAISS or "},{"text":"hnswlib","code":true},{"text":" index them locally. A hybrid search system over a few hundred thousand documents runs on a laptop with no account anywhere."}]},{"t":"h2","id":"the-rule-to-keep","runs":[{"text":"The rule to keep"}]},{"t":"p","runs":[{"text":"Sparse records identity, dense records similarity, and the memory arithmetic tells you which is affordable at your scale. If your queries contain names, codes or numbers, you need the sparse half no matter how good the embedding model gets."}]}],"check":{"question":[{"text":"A support team replaces their keyword search with dense embedding search. Overall satisfaction improves, but agents complain that searching for a specific error code such as "},{"text":"ERR_SSL_PROTOCOL_ERROR","code":true},{"text":" now returns nothing useful. What is the mechanism?"}],"options":[{"text":[{"text":"The embedding model has a token limit and the long code is being truncated before it is embedded."}],"correct":false,"tempting":[{"text":"Truncation happens with long documents, but a single short code is well within any model’s limit; the failure is about representation, not length."}]},{"text":[{"text":"Dense vectors are normalised, so the rare code contributes very little to the direction of the query vector and cannot dominate the match."}],"correct":false,"tempting":[{"text":"Normalisation is real but is not the cause; even un-normalised, the model has no distinctive representation for a token it barely saw."}]},{"text":[{"text":"The code is a rare token the model has little or no learned representation for, so its embedding carries almost no distinguishing signal, whereas an inverted index matches it exactly."}],"correct":true,"tempting":null},{"text":[{"text":"Cosine similarity cannot represent exact matches, only approximate ones, so exact-string queries always fail."}],"correct":false,"tempting":[{"text":"Cosine returns 1.0 for identical vectors and handles exact matches fine; the problem is upstream, in what the model encoded."}]}],"order":[1,0,2,3],"why":null},"prev":{"slug":"high-dimensional-strangeness","title":"Why your 3-D intuition is wrong in 768 dimensions","minutes":10},"next":{"slug":"matrix-multiplication-by-hand","title":"Doing a matrix multiplication yourself, once","minutes":8}}}