Query-document dual encoders
Align encoder versions, pooling, normalization, and search metric so an indexed vector means the same thing at training and inference.
On this page
The question for today
What you’ll understand
- Distinguish decomposable dual-encoder retrieval from query-document joint scoring.
- Compute inner-product and cosine rankings under explicit normalization.
- Diagnose representation and index mismatch separately from approximate search loss.
A dual encoder represents a query and each document independently, allowing document vectors to be prepared before the query arrives. That decomposition makes large candidate search practical, but it also restricts the interaction used for scoring. DPR’s 2020 formulation uses separately encoded questions and passages with an inner product. Other systems use different pooling and normalization, so a vector’s dimension alone is not enough to establish compatibility.
Define the representation and metric together
An encoder contract includes tokenizer, truncation, prompt or prefix, pooling, model weights, output dimension, dtype, and normalization. Query and document encoders may share parameters or be distinct, but their outputs must be trained to interact through the deployed similarity function. A model trained for unnormalized inner product can use document magnitude as part of its score. Normalizing those vectors afterward can therefore change rankings rather than merely improve numerical stability. A new checkpoint can require re-encoding the corpus rather than reusing vectors with the same shape.
Cosine similarity divides by both nonzero vector norms. On unit-normalized vectors, cosine and inner product coincide, and squared Euclidean distance becomes a monotone inverse transformation of that product. Without those conditions, the rankings need not agree. Faiss’s official metric documentation distinguishes maximum inner product from squared L2 search and describes normalization for cosine. Check whether an API expects larger similarities or smaller distances; a sign or ordering mistake can return the least similar candidates while still producing valid-looking numbers.
Separate representation quality from index approximation
First compare a small exact search over the intended vectors against the production search path. If the exact ranking already misses the relevant document, changing approximate-index settings cannot repair that representation failure. If exact search succeeds but approximate search does not, inspect index construction, metric, search effort, quantization, and version compatibility. Both effects can coexist. Keep a stable vector snapshot and exact reference for debugging instead of attributing every dense retrieval miss to semantic model quality.
Training and deployment also need aligned document units. A passage encoder trained on bounded chunks may not preserve relevance when fed a much longer document that truncates the answer. Query prefixes or language handling can change the embedding distribution. Evaluate identifiers, negation, dates, multilingual queries, and domain-specific vocabulary with appropriate judgments. DPR’s experiments demonstrate a useful method on specific tasks, not a theorem that dense retrieval replaces every lexical signal or succeeds on every new collection.
Version the query path and corpus representation
Publish index metadata that identifies the document encoder and processing pipeline. Ensure the serving query encoder belongs to the intended paired version, and make reindex or migration behavior explicit. A partial rollout that mixes incompatible vector versions can create class-dependent failures difficult to see in averages. Compare exact retrieval, candidate recall, final reranking quality, and latency separately. A successful vector-dimension check catches only one narrow class of mismatch and does not establish that the embeddings inhabit the same learned space.
The vector lab illustrates two-dimensional geometry only. Reset, set angle to 0 degrees and magnitude to 1, predict the horizontal component, then Step: one. Compare a fresh Reset with both angle at 60 degrees and magnitude at 1 before Step: one half. Against a fixed unit query on the horizontal axis, that component equals the inner product. The instrument does not run an encoder, tokenize documents, build an approximate index, or measure semantic relevance.
Work it through
Normalization can reverse the winner
Let the query vector be (1,0), document A be (1,0), and document B be (2,2). Compare raw inner-product and cosine rankings, with exact arithmetic and no approximate index.
Raw inner products are one for A and two for B, so maximum inner product ranks B first.
A has norm one and B has norm √8. Their cosines with the unit query are one and 2/√8 = 1/√2, approximately 0.7071.
Cosine therefore ranks A first. Normalizing the document vectors changes this ranking, so it must match the intended training and inference contract rather than being inserted as an assumed harmless transformation.
The metric and normalization policy jointly define retrieval; identical vector dimensions do not make them interchangeable.
The living notebook
Explore the model
Interactive lab · vectors
Unit-vector similarity as a projection
Reset, set angle θ = 0° and magnitude r = 1, predict x, then Step: x = 1. Compare a fresh Reset with both θ = 60° and r = 1 before Step: x = 0.5. With a fixed unit horizontal query, x is a two-dimensional inner product; no encoder or document search is performed.
- x component
- 1.393
- y component
- 0.975
- Magnitude
- 1.7
Playback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forNormalization and geometry determine a score, while semantic relevance requires a trained representation and evaluation.
Pause & reason
Check your understanding
Your turn
Try it yourself
Use query (1,0), document A = (2,0), and document B = (3,4). Compute raw inner products and cosines. Explain which search errors remain possible after choosing the intended metric.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
B has Euclidean norm five. Distinguish exact geometry from approximate search.
Compare with the solution
Raw products are two and three, so B wins. Cosines are one and 3/5 = 0.6, so A wins after appropriate normalization. Even with the correct metric, the encoder may represent relevance poorly or an approximate index may omit the exact top neighbor. Test those separately with a fixed exact-search reference and the intended document-processing contract.
Keep the idea
Take it with you
- A dual encoder’s representation contract includes much more than dimension.
- Inner product, cosine, and squared L2 agree only under stated conditions.
- Exact-vector quality and approximate-index recall are distinct diagnostic layers.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.