Embedding model contracts
Identify an embedding space before scoring
Two encoders can both output 768 numbers and still use unrelated coordinate systems. Coordinate 12 in one model need not correspond to coordinate 12 in another; even a model update or changed pooling, prompt, truncation or normalization can alter scores. Maintain a trusted application manifest with an embedding space ID, immutable model/tokenizer revision, dimensionality, metric, preprocessing and retrieval profile. A retrieval profile records the compatible query and document encoding recipes, including role-specific prompts if required. The same approved profile may deliberately use different query and document encoders trained to share a space; arbitrary cross-model comparison is not allowed. The local gate below assumes a single reviewed profile and cosine metric. It rejects missing or different metadata, wrong roles, wrong dimensions, invalid numbers and zero vectors. The fields are illustrative, not provider API fields. All numbers are bounded to keep the offline contract small.
import math
def compatible(query, document): # Application-owned metadata, not trusted fields from a document. fields = ("space", "revision", "dimension", "metric", "profile") if any(query.get(k) != document.get(k) for k in fields): return False if any(not isinstance(query.get(k), str) or not query[k] for k in ("space", "revision", "profile")): return False d = query.get("dimension") if type(d) is not int or not 1 <= d <= 1024: return False if type(document.get("dimension")) is not int: return False if query.get("metric") != "cosine": return False if query.get("role") != "query" or document.get("role") != "document": return False for record in (query, document): v = record.get("vector") if (not isinstance(v, list) or len(v) != d or any(type(x) not in (int, float) or not -1000 <= x <= 1000 for x in v) or not any(v)): return False return True
q = dict(space="demo", revision="r1", dimension=2, metric="cosine", profile="retrieval-v1", role="query", vector=[1, 0])d = dict(q, role="document", vector=[1, 1])print(compatible(q, d))print(compatible(q, dict(d, revision="r2")))print(compatible(q, dict(d, vector=[0, 0])))Encoding and index migration
Record which exact source version and preprocessing produced each vector, along with stable document ID and authorization metadata. For retrieval, some models require different instructions for queries and passages; Sentence Transformers documents query/document-specific encoding methods. Consult the actual selected model documentation and task tests. Do not treat a general text generation model ID as an embedding encoder ID. If an incompatible revision, dimension or recipe changes, create a separately versioned index, re-embed approved source text, evaluate the candidate against the old baseline, route queries using the matching encoder, then switch with rollback available. Do not mix the old and new vectors during migration. Record failures and deletions as well as additions. This lesson performs no model loading or index writes.
Measure relevance against a lexical baseline
A training objective may encourage similar paraphrases or rank relevant passages above negatives; it does not guarantee success on your corpus. Use a held-out query set with independently labeled relevant document IDs. Recall at k is the number of relevant IDs in the first k returned results divided by the total relevant IDs for that query. The denominator is not k; that would be precision at k when k items are returned. This toy baseline counts shared lowercase whitespace-separated English words and sorts by ID on ties. The fictional query forgotten password has two relevant passages, a and b. The irrelevant sticker record c matches both query terms, so lexical rank starts c; the supplied dense ordering starts b. Recall at 1 is 0 for lexical and 0.5 for the invented dense ordering, whose recall at 2 is 1.0. This demonstrates how to compute a metric, not that any real embedding model outperforms lexical search. No-answer queries need separate evaluation rather than division by zero. The baseline intentionally omits stemming, punctuation normalization and BM25.
def lexical_rank(query, documents): # Deliberately simple English whitespace-token overlap baseline. words = set(query.lower().split()) return sorted(documents, key=lambda key: ( -len(words & set(documents[key].lower().split())), key))
def recall_at_k(ranked, relevant, k): if type(k) is not int or k < 1 or not relevant: raise ValueError("positive k and nonempty relevance set required") if len(ranked) != len(set(ranked)): raise ValueError("duplicate document ID") return len(set(ranked[:k]) & relevant) / len(relevant)
docs = {"a": "reset password instructions", "b": "replace forgotten login secret", "c": "forgotten password sticker inventory"}query = "forgotten password"relevant = {"a", "b"} # synthetic human relevance labelslexical = lexical_rank(query, docs)dense_fixture = ["b", "a", "c"] # invented ranking, not model outputprint(lexical)print(recall_at_k(lexical, relevant, 1))print(recall_at_k(dense_fixture, relevant, 1))print(recall_at_k(dense_fixture, relevant, 2))Multilingual and task-specific evaluation
Do not assume English retrieval quality transfers to Persian or other languages. Choose a model with documented language support and evaluate separately on Persian queries against Persian and English documents, and the reverse cross-language direction if needed. Include spelling variations, Persian versus Arabic forms of letters, zero-width non-joiners, mixed-script identifiers, negation, exact names and short queries. Test normalization carefully: changes may remove distinctions. Keep the same held-out query IDs and relevance criteria for fair comparison, report per-language recall and failure cases, and avoid using evaluation labels to tune the final test. Lexical retrieval often helps with exact product codes and rare names; semantic retrieval can help paraphrases. Compare both and consider a separately validated hybrid method. The package is English-only and contains no empirical multilingual evaluation.
Practice and next step
Create two fictional records with identical dimensions and different revision metadata. Reject their comparison even if the numeric vectors match. Evaluate a lexical baseline and a supplied dense ordering against the same three documents at k=1 and k=2, then add a no-answer query to a separate abstention test. Explain why a score is not a probability, why the model objective is not the final retrieval metric, and what evidence would justify an index migration. The next chapter turns this exact ranking baseline into vector-store retrieval, approximate search and access filtering.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Embedding model contracts quiz
Apply embedding similarity and retrieval contracts.
Can two vectors from unrelated encoders be compared merely because both have 768 dimensions?
What is a safe response to an incompatible embedding revision?
Two documents are relevant, and the top result is one of them. What is recall at 1?
What establishes Persian retrieval quality?
What does the supplied dense ranking in this lesson demonstrate?