Sub topic 14
Common pitfalls: normalization, query and document prefixes, model changes, domain mismatch
This chapter assumes you can run the earlier code in this tutorial. You should know how to encode text with a pretrained model, compute cosine similarity, and build a top-k search over a matrix of document vectors. It also assumes you have seen FAISS indexes and the recall@k metric.
Most failures in semantic search do not come from the algorithm. They come from small mismatches between how documents were embedded and how queries are embedded. This chapter covers four mismatches that produce plausible but wrong results, with no error message:
- Vectors that are not normalized when the metric expects them to be.
- Missing or inconsistent query and document prefixes.
- Mixing vectors from different models, or from different versions of one model.
- A model trained on data that looks nothing like your domain.
Pitfall 1: normalization
Why it matters
Cosine similarity ignores vector length. The dot product does not. If your index scores with a raw dot product (or inner product) but your vectors have varying lengths, long vectors win regardless of meaning. The ranking then reflects vector length as much as direction.
Some models return unit-length vectors by default. Others do not. Many do not state this in the output, so you must check.
Check the norms
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
texts = ["How do I reset my password?", "The weather is sunny today"]
raw = model.encode(texts)
unit = model.encode(texts, normalize_embeddings=True)
print(np.linalg.norm(raw, axis=1)) # may not be 1.0
print(np.linalg.norm(unit, axis=1)) # all close to 1.0For all-MiniLM-L6-v2, the packaged pipeline may already include a normalization step, so the first line can print values near 1.0. Do not rely on that. Measure it for each model you use.
Metric and normalization must agree
The three common metrics behave like this on unit-length vectors:
| Metric | Unit vectors | Non-unit vectors |
|---|---|---|
| Cosine similarity | Reference score | Reference score (length cancels) |
| Dot product | Equal to cosine | Length affects ranking |
| Euclidean distance | Ranks the same as cosine (smaller is closer) | Length affects ranking |
On unit vectors, squared Euclidean distance equals 2 - 2 * cosine. A lower distance therefore means a higher cosine, and the ranking is identical. This is why the FAISS example earlier could use an L2-based HNSW index and still match cosine ranking.
The scores differ even when rankings agree
A flat inner-product index returns similarities, where larger is better. An L2 index returns squared distances, where smaller is better. If you switch index types and keep a fixed score threshold such as "keep results above 0.5", the threshold silently breaks. Convert explicitly:
import numpy as np
def l2_sq_to_cosine(d_sq):
"""Valid only when both vectors have unit length."""
return 1.0 - d_sq / 2.0
print(l2_sq_to_cosine(np.array([0.0, 1.0, 2.0]))) # [ 1. 0.5 0. ]A defensive habit
Normalize once, at encoding time, for both documents and queries. Then every downstream metric agrees. If you cannot control the encoder, normalize afterward:
import numpy as np
def l2_normalize(x, eps=1e-12):
x = np.asarray(x, dtype="float32")
norms = np.linalg.norm(x, axis=-1, keepdims=True)
return x / np.maximum(norms, eps)The eps guard avoids dividing by zero on an all-zero vector, which can happen with empty input text.
Pitfall 2: query and document prefixes
What prefixes are
Some embedding models are trained with instructions or markers that tell them the role of the text. Two families are common:
- Models that expect a short prefix such as
query:andpassage:(the E5 family), orsearch_query:andsearch_document:(Nomic). - Models that expect an instruction only on the query side (the BGE English models document a query instruction for retrieval).
The exact strings are model-specific. Read the model card. Your search quality depends on using the strings the model was trained with.
What goes wrong
Retrieval is asymmetric: a short question on one side, a long passage on the other. During training, these models see the prefixes on every example, so the prefix shifts where the text lands in vector space. If you omit it, the vectors still look normal and cosine scores still land in a reasonable range. Recall just drops, often by a few points, and nothing warns you.
The reverse error also happens. Adding the query prefix to documents makes documents resemble queries instead of passages.
A small wrapper keeps this consistent
Put the prefix rule in one place so no call site can forget it.
import numpy as np
from sentence_transformers import SentenceTransformer
class Embedder:
def __init__(self, name, query_prefix="", doc_prefix=""):
self.model = SentenceTransformer(name)
self.query_prefix = query_prefix
self.doc_prefix = doc_prefix
def embed_queries(self, texts):
texts = [self.query_prefix + t for t in texts]
return self.model.encode(texts, normalize_embeddings=True)
def embed_docs(self, texts):
texts = [self.doc_prefix + t for t in texts]
return self.model.encode(texts, normalize_embeddings=True)
# Symmetric model: no prefixes.
mini = Embedder("all-MiniLM-L6-v2")
# E5-style model: prefixes are required.
# e5 = Embedder("intfloat/multilingual-e5-small",
# query_prefix="query: ", doc_prefix="passage: ")
q = mini.embed_queries(["How do I reset my password?"])
d = mini.embed_docs(["Steps to recover access to your account"])
print(float((q @ d.T)[0, 0]))The E5 lines are commented out because they download a different model. Uncomment them to compare prefixed and unprefixed recall on your own labeled queries.
Checking whether prefixes matter
Do not assume. Run your evaluation set twice, once with the prefixes and once without, using recall_at_k from the evaluation chapter. A gap of several points tells you the model needs them.
Pitfall 3: model changes
Vectors from different models are not comparable
Each model defines its own vector space. Dimension 17 in one model has no relation to dimension 17 in another. Two models with the same dimension count, such as two 384-dimension models, let you run the dot product without an error. The result is meaningless.
This produces several real failure patterns:
- You upgrade the query encoder but keep the old document index.
- Two teams write to one index with different models.
- A hosted API silently updates the model behind a name.
- A library update changes default pooling, truncation, or normalization.
When dimensions differ, you get a shape error, which is the lucky case. When they match, you get wrong rankings with no signal.
Store the model identity with the index
Keep a small metadata record next to the vectors and check it when a query arrives.
import json
def save_index_meta(path, model_name, dim, normalized, query_prefix, doc_prefix):
meta = {
"model_name": model_name,
"dim": dim,
"normalized": normalized,
"query_prefix": query_prefix,
"doc_prefix": doc_prefix,
}
with open(path, "w", encoding="utf-8") as f:
json.dump(meta, f, indent=2)
def check_index_meta(path, model_name, dim):
with open(path, encoding="utf-8") as f:
meta = json.load(f)
if meta["model_name"] != model_name or meta["dim"] != dim:
raise RuntimeError(
f"Index was built with {meta['model_name']} ({meta['dim']}d), "
f"but the query encoder is {model_name} ({dim}d). Re-embed first."
)
return meta
save_index_meta("index_meta.json", "all-MiniLM-L6-v2", 384, True, "", "")
print(check_index_meta("index_meta.json", "all-MiniLM-L6-v2", 384)["dim"]) # 384For hosted models, also record a version or date, since the name alone may not pin the weights.
Plan migrations
Changing models means re-embedding every document. For a large collection, that is a batch job and a storage cost. A safe sequence:
- Build a new index with the new model next to the old one.
- Run your labeled queries against both and compare recall@k and MRR.
- Switch query traffic only after the new index wins.
- Keep the old index until you are confident you will not roll back.
Chunking and truncation are part of the model contract
Every model has a maximum input length, in tokens. Text beyond it is cut off, so the embedding describes only the start of the chunk. Check model.max_seq_length and compare it to your chunk sizes. A change to either the chunker or the model's limit changes what the vectors represent, so treat it as a model change and re-embed.
Pitfall 4: domain mismatch
What it is
General-purpose embedding models are trained on web text, forums, and public question-answer pairs. If your corpus is legal contracts, medical notes, source code, or internal product jargon, the model may not place texts the way your users expect. Typical symptoms:
- Rare terms, part numbers, and acronyms get blurry vectors, since the model saw few examples.
- Distinct concepts in your field land close together because the model sees them as similar everyday words.
- Queries in a language or dialect underrepresented in training fare worse.
Diagnose before you fix
Domain mismatch is an empirical question. Build 50 to 200 real queries with known relevant documents, then measure.
def mean_recall(search_fn, labeled, k=5):
"""labeled: list of (query, set_of_relevant_ids). search_fn returns ranked ids."""
total = 0.0
for query, relevant in labeled:
retrieved = search_fn(query)[:k]
hits = len(set(retrieved) & relevant)
total += hits / len(relevant) if relevant else 0.0
return total / len(labeled)
labeled = [("reset password", {"d1"}), ("office hours", {"d2"})]
fake_search = lambda q: ["d1", "d3"] if "password" in q else ["d9", "d2"]
print(mean_recall(fake_search, labeled, k=2)) # 1.0Replace fake_search with your real search function. Then look at the failures one at a time instead of only reading the average. They usually show a pattern, such as all misses involving product codes.
Options, from cheapest to most expensive
| Option | Cost | When it helps |
|---|---|---|
| Try other pretrained models | Low | Another model may fit your language or domain better |
| Add keyword search (hybrid) | Low | Exact terms, codes, and names matter |
| Add a cross-encoder reranker | Medium | The right document is retrieved but ranked low |
| Fine-tune the embedding model | High | You have many labeled query-document pairs and consistent failures |
Hybrid search is often the first fix for jargon. BM25 matches the literal string ERR-4021 exactly, which a vector may not.
Other quiet failures
- Casing and whitespace. Some models are case-sensitive and others are not. Apply the same text cleaning to documents and queries.
- Duplicate and boilerplate chunks. Headers, footers, and cookie notices produce near-identical vectors that crowd out useful results. Strip them before embedding.
- Float precision. FAISS expects
float32. NumPy defaults tofloat64for many operations, and passing the wrong dtype raises an error or forces a copy. - Score thresholds. A cosine of 0.7 means different things in different models. Pick thresholds from your own data.
Exercises
Exercise
Your index uses faiss.IndexFlatIP and you embed documents with normalize_embeddings=True, but you embed queries without it. Rankings for a single query look fine, yet a rule that drops results scoring below 0.4 behaves erratically across queries. Why, and what is the fix?
Show answer
Inner product on a query of arbitrary length scales all of that query's scores by the query's norm. Within one query the order is unchanged, so rankings look right. Across queries the scores are not on the cosine scale, so a fixed 0.4 threshold keeps too many results for long query vectors and too few for short ones. The fix is to encode queries with normalize_embeddings=True, so the inner product equals cosine similarity.
Exercise
A teammate swaps the query encoder from one 384-dimension model to a different 384-dimension model and leaves the document index unchanged. No exception is raised. Explain why recall collapses and name two safeguards.
Show answer
Each model defines its own vector space, so matching dimension counts do not mean matching meaning. The dot product runs, but it compares unrelated coordinates and returns near-random rankings. Safeguards: store the model name, dimension, prefixes, and normalization flag with the index and check them at query time; and keep a labeled-query regression test that fails when recall drops. Re-embedding all documents with the new model, and evaluating before switching traffic, fixes the problem.
Exercise
A corpus of hardware manuals contains many part numbers like "XR-7720-B". Queries that contain the exact number often miss the right manual page, while natural-language queries work well. What do you try first, and how do you confirm it helped?
Show answer
Add keyword (BM25) search and combine it with the vector results using reciprocal rank fusion, since exact tokens such as part numbers are matched literally by keyword search. Confirm by running the same labeled queries before and after, comparing recall@k and MRR, and checking that the part-number queries improved without hurting the natural-language queries.