Indexing Dense Embeddings Without Fooling Yourself

Handwritten derivation of TF-IDF and the Word2Vec skip-gram loss
Term frequency times inverse document frequency, then the skip-gram objective. The typeset versions below are the ones we check the code against.

We had 186,412 help-center articles and a search box that still ranked them by raw term counts. A query for "reset password" returned pages that said "password" often and never said "reset." That is the formula, not a mystery.

TF-IDF, with the numbers filled in

TF-IDF(t, d, D) = TF(t, d) × IDF(t, D)

TF(t, d) = (count of t in d) / (terms in d)

IDF(t, D) = log( |D| / (1 + documents containing t) )

Document A is "reset password link", three terms. Across a toy corpus of 1,000 documents, "reset" appears in 12 and "password" appears in 400.

For "reset" in A, TF is 1/3. IDF is log(1000 / 13), about 4.34. The product is about 1.45. For "password" in A, TF is 1/3. IDF is log(1000 / 401), about 0.91. The product is about 0.30.

"Reset" outranks "password" even though each word occurs once. The log is doing the work. A raw count cannot. We still compute this score for queries that contain an exact rare token: an invoice id, an error code, a SKU. Dense retrieval is worse at those. A search box that cannot find the page named after the error code is not a semantic improvement. It is a regression we then have to explain to support.

What the skip-gram is optimizing

L = (1/T)  Σ_t  Σ_{−c ≤ j ≤ c, j ≠ 0}  log P(w_{t+j} | w_t)

P(w_o | w_t) = exp(u_o · v_t) / Σ_{w=1}^{W} exp(u_w · v_t)

u and v are two vectors for the same word, one when it is context and one when it is the center. W is the vocabulary size. The dot product u_o · v_t should be large when the context word really does sit next to the center word, inside a window of c tokens. The loss L averages that log probability over every center word in the corpus.

The denominator sums over every word in the vocabulary. That is why a faithful implementation of the formula does not finish. gensim, and the original word2vec code, draw a handful of negative samples instead of computing the full sum. Same objective, a cheaper estimate. If your training loop sums over W because the formula says so, you have not found a bug in gensim. You have found the reason the sampling trick was published.

Those vectors are static. "Bank" is one point, river or paycheck. Sentence-BERT-style pooling, which we started using after the 2019 paper, gives a vector for the whole sentence, so "reset the password" and "change the login credentials" land near each other. We mean-pool the last layer, L2-normalize, and search by inner product. Inner product on normalized vectors is cosine. Skip the normalize step and ask the index for L2 distance, and you rank by vector length. Longer articles win for no reason a reader would accept.

The index bug the demo hid

IndexFlatIP over 186k vectors of 768 dimensions took about 40ms on one core. Acceptable for a demo, tight for the traffic we expected. IndexIVFFlat with 1,024 lists and nprobe 16 brought the same queries back in under 10ms, with recall@10 around 0.95 on 300 queries a person had labeled. We then turned on product quantization to shrink the index. Recall on short queries ("change invoice email") fell to about 0.8. The residual that quantization throws away was the signal. Quantization came back off. The bytes were cheaper than the missed articles.

The bug that paged us was the filter. Billing search returned shipping articles, because the nearest vector does not know the product column. The inverted file will happily return a close neighbor from the wrong product.

Two changes, both dull, both enough:

  • Over-fetch. Ask for 80 neighbors, drop the ones whose product does not match, return 8. We measured how often 80 was short. On this corpus it was not. If it becomes short, raise it because the measurement moved, not because a round number feels safe.
  • Once a product has more than about 20,000 articles, give it a separate index. There is then nothing from the other product to filter out.

The integer that comes back from the index is a row number. The article id lives in a side array written in the same directory as the index, swapped in together. We lost an afternoon by treating the row number as the id. Nightly rebuild, atomic directory swap, previous directory kept for an hour in case the new index is short. We did not offer online adds into the IVF index. We did not trust them, so they were not a feature.

Milvus was the other system we stood up that month, mostly because owning Faiss plus a map plus a filter was more code than we wanted. The same three problems came along: recall versus nprobe, quantization eating short queries, and filters applied after the neighbors return. A different server does not change the formula.