advanced27 min studyLesson 662 in Engineering

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

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.

sIP(q,d)=EQ(q)⊤ED(d),scos⁡(q,d)=EQ(q)⊤ED(d)∥EQ(q)∥2∥ED(d)∥2s_{\mathrm{IP}}(q,d)=E_Q(q)^\top E_D(d),\qquad s_{\cos}(q,d)=\frac{E_Q(q)^\top E_D(d)}{\|E_Q(q)\|_2\|E_D(d)\|_2}
Encoder outputs lie in the same finite-dimensional space. Cosine requires both norms to be nonzero. These dimensionless learned scores have no automatic calibration as relevance probabilities, and their equivalence requires the appropriate normalization.↔ Scroll wide equations horizontally.

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.

∥u−v∥22=2−2u⊤v,∥u∥2=∥v∥2=1\|u-v\|_2^2=2-2u^\top v,\qquad\|u\|_2=\|v\|_2=1
For real unit vectors, minimizing squared Euclidean distance is equivalent to maximizing their inner product. The identity does not hold in this form for arbitrary norms, and an approximate index can still differ from the exact ordering.↔ Scroll wide equations horizontally.

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.

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.

  1. Raw inner products are one for A and two for B, so maximum inner product ranks B first.

  2. 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.

  3. 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 result

The metric and normalization policy jointly define retrieval; identical vector dimensions do not make them interchangeable.

Explore the model

Interactive lab

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.

Unit-vector similarity as a projectionPlayback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Current readings: x component: 1.393; y component: 0.975; Magnitude: 1.7. All parameters are adjustable with the labeled controls below.−7.46−3.7303.737.46−3.5−1.7501.753.5xyvvₓ = 1.39
Vectorx / y projectionsTrace marker
x component
1.393
y component
0.975
Magnitude
1.7
t = 0 s

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.

Check your understanding

A retriever was trained with raw inner products. What should be checked before normalizing all document vectors for deployment?

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.

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.