My RAG bot had one favorite answer. Ask it about refunds, it cited the cookie policy footer. Ask it about API rate limits, cookie policy footer. Ask it how to reset a password, footer again, now at position #1.
The bug was one missing line. I had built the index with FAISS IndexFlatIP and fed it raw embeddings. IndexFlatIP does exactly what its name says: it ranks by inner product. I thought I was getting cosine similarity. I was getting cosine similarity multiplied by vector length, and a handful of chunks had longer vectors than everyone else.
I can't share that corpus, so I rebuilt the failure from scratch with synthetic vectors. 10,000 chunks, 2,000 queries, 20 boilerplate chunks whose vectors are 15% longer than the rest. Those 20 chunks showed up in the top 5 for 854 of 2,000 queries. With normalized vectors: 2.
TL;DR
-
faiss.IndexFlatIPscores with the raw dot productq · d = |q| × |d| × cos(θ). It is only cosine similarity if every vector has length 1. - The query's length doesn't change the ranking. The document's length does: a chunk with a 15% longer vector gets a 15% bonus on every single query.
- In my reproduction, 20 boilerplate chunks out of 10,000 landed in the top 5 for 854 of 2,000 queries and took #1 for 198. Normalized: 2 and 0.
- Fix: call
faiss.normalize_L2()on the vectors beforeindex.add()and on every query beforeindex.search(), or encode withnormalize_embeddings=True. Then rebuild the index. -
faiss.normalize_L2works in place and returnsNone.emb = faiss.normalize_L2(emb)is its own bug.
Is FAISS IndexFlatIP the same as cosine similarity?
No. FAISS IndexFlatIP computes the inner product, and inner product equals cosine similarity only when both vectors are unit length. FAISS has no cosine metric. The documented way to get cosine is to L2-normalize your vectors yourself and then use inner product.
Here's the code I had. It looks completely fine:
import faiss
emb = model.encode(chunks) # sentence-transformers
index = faiss.IndexFlatIP(emb.shape[1])
index.add(emb) # raw vectors go in
q = model.encode([question])
scores, ids = index.search(q, 5)
Nothing errors. Scores come back in a plausible range. Most queries return sensible chunks. That's what makes it nasty: the damage is spread across a few thousand searches as "the answer was slightly worse," and only shows up when one chunk gets greedy enough for you to notice.
And SentenceTransformer.encode() defaults to normalize_embeddings=False. Some models ship a Normalize layer in their pipeline and come out unit-length anyway. Some don't. If you never checked, you don't know which one you have.
Why does inner product favor long chunks?
Because inner product is |q| × |d| × cos(θ), and for a single query |q| is a constant. So the ranking for that query is really sorted by |d| × cos(θ). Document length is a multiplier on relevance, applied to every query, forever.
A concrete pair, with cosines in the same range as my reproduction:
| chunk | cosine to query | vector length | inner product rank score |
|---|---|---|---|
| actually relevant chunk | 0.64 | 1.00 | 0.64 |
| cookie policy footer | 0.58 | 1.15 | 0.67 |
The footer is less similar. It still wins.
Two things make boilerplate the worst offender:
- It already has a decent cosine to everything. Embedding spaces are anisotropic: most vectors lean toward a shared direction. Generic text like footers, nav menus, license blurbs and "Last updated" banners sits close to that shared direction, so it scores a middling cosine against every query. In my run the boilerplate's best cosine averaged 0.58 against queries whose best real match averaged 0.68. Not close enough to win alone.
- Its vector length differs from normal chunks. Vector length out of mean pooling isn't a relevance signal. It reflects things like how uniform the token vectors are. Repetitive, templated text can land at a different norm than varied prose. Give it a 10 to 20% bump and that middling cosine becomes a winning score.
How bad does it get? The numbers from my reproduction
I generated 10,000 chunk vectors (384 dimensions, 500 topics, all leaning toward a shared direction), gave normal chunks lengths around 1.00 (standard deviation 0.04), and made 20 "boilerplate" chunks that sit mostly on the shared direction. Then I swept the boilerplate vector length and ran 2,000 queries against both a raw inner product index and a cosine one.
| boilerplate length | in top 5 (IP) | at #1 (IP) | precision@5 (IP) | in top 5 (cosine) |
|---|---|---|---|---|
| 1.05 | 29 | 2 | 0.996 | 2 |
| 1.10 | 254 | 24 | 0.962 | 2 |
| 1.15 | 854 | 198 | 0.825 | 2 |
| 1.20 | 1,601 | 697 | 0.552 | 2 |
| 1.30 | 1,994 | 1,830 | 0.094 | 2 |
Read the curve, not just the headline row. A 5% norm difference is noise. At 15%, 0.2% of the corpus contaminates 43% of result sets. At 30%, retrieval is basically a constant function that returns the footer.
The cosine column doesn't move, because cosine doesn't look at length. That column is the whole argument for normalizing.
Here's the core of the script if you want to poke at it (numpy only):
import numpy as np
rng = np.random.default_rng(42)
D, N, T, Q = 384, 10_000, 500, 2_000
unit = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)
shared = unit(rng.normal(size=D))
topics = unit(rng.normal(size=(T, D)))
label = rng.integers(0, T, N)
docs = unit(0.6*shared + 0.6*topics[label] + 0.5*unit(rng.normal(size=(N, D))))
norms = rng.normal(1.0, 0.04, N)
junk = rng.choice(N, 20, replace=False)
label[junk] = -1
docs[junk] = unit(0.9*shared + 0.45*unit(rng.normal(size=(20, D))))
norms[junk] = 1.15
raw = docs * norms[:, None] # what IndexFlatIP stores
qlabel = rng.integers(0, T, Q)
q = unit(0.6*shared + 0.45*topics[qlabel] + 0.65*unit(rng.normal(size=(Q, D))))
for name, M in [("inner product", raw), ("cosine", docs)]:
top5 = np.argsort(-(q @ M.T), axis=1)[:, :5]
hit = np.isin(top5, junk)
print(name, hit.any(1).sum(), hit[:, 0].sum(),
(label[top5] == qlabel[:, None]).mean())
Output:
inner product 854 198 0.825
cosine 2 0 1.000
Synthetic data, so treat the exact numbers as an illustration of the mechanism, not a prediction for your corpus. Your real norm spread is the number that matters, and you can measure it in one line (below).
Does normalizing only the query fix it?
No. Normalizing the query alone changes nothing about the ranking. Scaling q multiplies every document's score by the same constant, so the order stays identical. I checked: multiplying every query by 3 produced the exact same top 5 for all 2,000 queries.
What query normalization does change is the score scale. If you have a relevance cutoff like if score > 0.75, an unnormalized query makes that threshold mean something different for every question. So you want both sides normalized: documents for ranking, queries for stable thresholds.
How do I check if my FAISS index is affected?
Pull the stored vectors and look at their lengths:
import numpy as np
emb = index.reconstruct_n(0, index.ntotal) # works for flat indexes
n = np.linalg.norm(emb, axis=1)
print(n.min(), np.percentile(n, [1, 50, 99]), n.max())
If everything prints 1.0 (give or take float noise), you're fine. If the 1st and 99th percentiles are more than a few percent apart, inner product is mixing length into your rankings. Then sort by norm and read the top 20 chunks. In my case it was exactly the chunks I'd have deleted by hand if I'd seen them.
How do I fix FAISS IndexFlatIP to use cosine similarity?
Normalize before adding and before searching, then rebuild the index from scratch. Vectors already in the index stay unnormalized until you re-add them.
import faiss, numpy as np
emb = np.ascontiguousarray(model.encode(chunks), dtype="float32")
faiss.normalize_L2(emb) # in place. Returns None.
index = faiss.IndexFlatIP(emb.shape[1])
index.add(emb)
q = np.ascontiguousarray(model.encode([question]), dtype="float32")
faiss.normalize_L2(q)
scores, ids = index.search(q, 5)
Or let the encoder do it: model.encode(chunks, normalize_embeddings=True), and the same for queries.
Three gotchas I hit or nearly hit:
-
emb = faiss.normalize_L2(emb)setsembtoNone. The function mutates its argument. Don't assign the result. -
It wants float32 and C-contiguous arrays. A float64 array or a non-contiguous slice can trip it up. Wrap with
np.ascontiguousarray(..., dtype="float32")first. -
It's not just IndexFlatIP.
IndexHNSWFlatorIndexIVFFlatbuilt withMETRIC_INNER_PRODUCThave the same problem, and so does pgvector's<#>operator. pgvector has a real cosine operator (<=>); FAISS does not.
Should I just switch to IndexFlatL2 instead?
Only if your vectors are normalized, and then the switch buys you nothing. For unit vectors, squared L2 distance is 2 - 2·cos(θ), so L2 and inner product produce the same ranking. For raw vectors, L2 has the opposite bias: the |d|² term penalizes long vectors. In my reproduction, a raw L2 index put boilerplate in the top 5 for 0 queries, but it would also push down any legitimately relevant chunk that happened to have a long vector. Swapping one length bias for another isn't a fix. Normalize, and pick whichever metric you like.
So, why did 20 chunks hijack 854 queries?
Because FAISS IndexFlatIP ranks by inner product, which is cosine similarity multiplied by each document vector's length, and without normalize_L2 those lengths are whatever your embedding model happened to produce. A few boilerplate chunks with vectors 15% longer than average got a 15% score bonus on every query, enough to beat genuinely relevant chunks with higher cosine, and in my 10,000-chunk reproduction they landed in the top 5 for 854 of 2,000 queries. Normalize every vector before index.add() and every query before index.search(), rebuild the index, and the same 20 chunks drop to 2 appearances.
Written by the developer behind Preterview, an interview prep platform.
Top comments (0)