AI Wiki中文/EN

Dense retrieval: separate representation errors from search errors

稠密检索

Probe a tiny vector index, measure two recalls and expose a stale encoder cache.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The nearest point can still be the wrong document

A reader searches for bicycle brake-cable repair. A useful note says “cycle stopping wire replacement,” while an unhelpful note says “car brake cable repair.” A lexical baseline can miss the first and favor the second. Dense retrieval tries to learn a representation in which useful query–document pairs receive high similarity. It does not make geometric proximity synonymous with relevance.

A dense vector has learned coordinates rather than one explicit coordinate for each vocabulary term. A query encoder and a document encoder map text into the same scoring space. DPR uses separate BERT encoders and an inner product; SBERT shows how shared encoders and pooling can create reusable sentence embeddings. Their objectives and tasks differ. Neither paper establishes that any generic embedding is a good retriever for every collection. DPR, section 3 SBERT, section 3

This article studies the search and maintenance stage. Bi-encoders covers learning the representation. Start an application with a lexical baseline such as BM25, explicit relevance judgments and a latency budget; replacing that baseline needs evidence on the actual queries.

Exact-neighbor agreement and relevance recall answer different questions.
Exact-neighbor agreement and relevance recall answer different questions.

Two kinds of recall answer different questions

Let f and g encode query q and document d into h-dimensional vectors. Inner product retrieval ranks by:

s(q,d)=f(q)⊤g(d).s(q,d)=f(q)^\top g(d).

If vectors are nonzero, cosine removes their lengths. Our experiment normalizes both sides; DPR’s cited formulation uses a dot product without requiring this normalization.

v^=v∥v∥2,cos⁡(u,v)=u^⊤v^.\hat v=\frac{v}{\|v\|_2},\qquad \cos(u,v)=\hat u^\top\hat v.

Exact search evaluates every eligible document. Approximate search first narrows the search space, accepting that some high-scoring neighbors may be missed. Let E_k be the exact top k under the same score and tie rule, and A_k the approximate output. For a collection with at least k eligible vectors, measure search agreement by:

ANNRecall@k=∣Ak∩Ek∣k.\mathrm{ANNRecall}@k=\frac{|A_k\cap E_k|}{k}.

This is an index-quality measurement. With an independently judged nonempty relevant set R, measure retrieval quality separately:

RelRecall@k=∣Ak∩R∣∣R∣.\mathrm{RelRecall}@k=\frac{|A_k\cap R|}{|R|}.

Exact search has perfect agreement with itself, yet it can retrieve irrelevant items if the representation or scoring rule is unsuitable. Conversely, an approximate index might accidentally omit an irrelevant exact neighbor and improve a relevance metric on one query. Do not treat that accident as a generally better index.

A rotation provides a cache-consistency test. For an orthogonal matrix U, rotating both sides preserves every inner product:

(Uu)⊤(Uv)=u⊤U⊤Uv=u⊤v.(Uu)^\top(Uv)=u^\top U^\top Uv=u^\top v.

Rotating only the new query and leaving old document vectors unchanged has no such guarantee. Production changes need a compatible encoder, tokenizer, normalization and index version, plus an atomic switchover or a deliberately supported migration path.

Eight eligible vectors and three cells

Run the self-contained Python 3.12 / NumPy 1.26 program. The nine authored vectors correspond to fragments: IDs 0,4,5,7 concern bicycle repair; 1 concerns adjustment, 2 paint, 3 car repair, 6 is empty and 8 concerns a cell cycle. We declare only 0,4,5,7 relevant to the repair need. The vectors are invented to isolate search behavior; no text encoder is trained or evaluated here.

The query is [1,1]. Documents are assigned to the closest of three unit centroids by dot product. A probe budget chooses the best query–centroid matches, then sorts documents in those cells. Centroid ties use the lowest cell ID; document scores are rounded to 14 decimal places for a reproducible tie key, then use ascending document ID. Empty vectors are omitted, and a zero query returns no results. The normalization rescales before squaring to avoid overflow and underflow in its norm calculation.

"""Original authored-vector search experiment; no neural encoder is trained."""
import json
import numpy as np

VECTORS = np.array([[1,.8],[.1,1],[-1,0],[1,.9],[.8,1],[.9,1],[0,0],[1,.7],[-.7,.7]])
RELEVANT = {0,4,5,7}

def unit(x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 2 or not x.size or not np.isfinite(x).all():
        raise ValueError('finite nonempty matrix required')
    scale = np.max(np.abs(x), axis=1, keepdims=True)
    y = np.divide(x, scale, out=np.zeros_like(x), where=scale>0)
    norm = np.sqrt((y*y).sum(axis=1, keepdims=True))
    return np.divide(y, norm, out=np.zeros_like(y), where=norm>0)

def search(query, docs, k=4, probes=None, versions=('v1','v1')):
    if versions[0] != versions[1]:
        raise ValueError('query and index encoder versions differ')
    d = unit(docs); q = unit(np.asarray(query, dtype=float).reshape(1,-1))[0]
    if d.shape[1] != 2 or q.shape != (2,) or not 1 <= k <= 100:
        raise ValueError('two dimensions and k in 1..100 required')
    active = np.flatnonzero(np.any(d != 0, axis=1)).tolist()
    if not np.any(q):
        return dict(ids=[], comparisons=0, centroid_comparisons=0)
    centroids = np.array([[1.,0.],[0.,1.],[-1.,0.]])
    if probes is not None:
        if type(probes) is not int or not 1 <= probes <= 3:
            raise ValueError('probes must be 1..3')
        selected = sorted(range(3), key=lambda j:(-float(centroids[j]@q),j))[:probes]
        cells = np.argmax(d@centroids.T, axis=1)
        active = [i for i in active if int(cells[i]) in selected]
    scores = d@q
    # Quantized tie key makes this deliberately symmetric fixture reproducible.
    ids = sorted(active, key=lambda i:(-round(float(scores[i]),14),i))[:k]
    return dict(ids=ids, comparisons=len(active), centroid_comparisons=3 if probes else 0)

def demo():
    exact = search([1,1],VECTORS)
    rows=[]
    for probes in [1,2,3]:
        row=search([1,1],VECTORS,probes=probes)
        row.update(probes=probes,relevance_recall=len(set(row['ids'])&RELEVANT)/4,
                   exact_overlap=len(set(row['ids'])&set(exact['ids']))/4)
        rows.append(row)
    rotation=np.array([[0.,-1.],[1.,0.]])
    fresh=search(rotation@np.array([1.,1.]),VECTORS@rotation.T)
    stale=search(rotation@np.array([1.,1.]),VECTORS)
    return dict(exact=exact,exact_relevance_recall=len(set(exact['ids'])&RELEVANT)/4,
                probes=rows,fresh_ids=fresh['ids'],unsafe_stale_ids=stale['ids'],
                scope='Authored 2-D vectors; rotation mismatch deliberately bypasses version safety.')

if __name__ == '__main__':
    print(json.dumps(demo(),sort_keys=True,allow_nan=False))

Exact top four are [3,5,0,4]: three are relevant, giving relevance recall 0.75. One probe compares three documents and returns [3,0,7]; agreement with exact top four is 0.5, and relevance recall is also 0.5. Two probes compare seven documents and recover the exact top four. Three probes compare all eight eligible documents. Each probing run also makes three centroid comparisons, so counting document comparisons alone does not prove a speedup. The brute-force implementation even computes full matrix products for clarity; these counts describe the conceptual candidate stage, not measured CPU work.

Rotating both sides keeps the exact ranking. Searching new query coordinates against stale document coordinates instead gives [8,2,1,4]. The demo deliberately bypasses the version guard to expose that error; a mismatched versions pair is rejected by search.

What to measure before replacing the baseline

An exact scan costs O(Nh) scoring work and O(Nh) vector storage, excluding encoding and metadata. This tiny demonstration sorts candidates in O(C log C); production top-k selection can use other algorithms. A partitioned index additionally pays for routing, index construction and updates. Real approximate-index latency depends on memory layout, hardware, filters and recall targets, not just the number of comparisons.

Keep development queries apart from final evaluation queries. Compare BM25, exact dense retrieval and approximate dense retrieval under the same document snapshot, filters and cutoff. Report relevance quality, exact-neighbor agreement, latency distributions, vector memory and refresh cost. Evaluate identifiers, rare names, synonyms and out-of-domain requests separately. A missing document, an embedding failure and an index miss need different repairs. DPR’s use of offline document encoding supports this separation of encoding and retrieval, not our particular three-cell algorithm. DPR, section 3.1

Locate the failure

  1. Two probes agree perfectly with exact search. Why is relevance recall only 0.75?

Answer: The exact top four contain irrelevant car-repair document 3 and omit relevant document 7. The index recovers the representation’s ranking faithfully; it cannot correct that ranking’s meaning.

  1. One probe finds two relevant documents. Compute both recalls at k=4.

Answer: Its list [3,0,7] shares 3 and 0 with exact [3,5,0,4], so ANN recall is 2/4. Relevant hits are 0 and 7 out of four judged relevant documents, also 2/4. The equal values arise from different intersections.

  1. Does rotating only the query preserve scores? What would you test during migration?

Answer: No. The cancellation requires rotating both sides. Compare new-query/new-document scores with the intended reference, reject incompatible versions, and verify the index and encoder become active together.

  1. Propose an experiment that separates a bad encoder from a bad index.

Answer: Fix a judged query set, snapshot and score convention. First evaluate exact dense retrieval against relevance labels and BM25. Then compare approximate results with those exact neighbors and the same labels. This identifies additional index losses without treating exact neighbors as ground truth relevance.

Representation is learned; index agreement is measured

Read DPR’s separate encoders, training loss and offline indexing together. Read SBERT’s tied-weight pooling architecture to see why “two encoders” does not always mean two parameter sets. The original vectors and cell-routing experiment here explain a systems distinction; they reproduce neither paper’s model nor its benchmarks. Continue to hybrid search when lexical and dense results make complementary mistakes.

Make a prediction, then check

If approximate search agrees perfectly with exact search, must all returned documents be relevant?

Choose one answer

Learning objectives

  • Separate semantic relevance from exact-neighbor agreement and budget index refresh.
  • Run the original example and explain its failure case.

Prerequisites & connections

Explore related knowledge →

References

  1. Dense Passage Retrieval for Open-Domain Question Answering — arXiv v1
    Vladimir Karpukhin; Barlas Oğuz; Sewon Min; Ledell Wu; Sergey Edunov; Danqi Chen; Wen-tau Yih · 2020
  2. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks — arXiv v1
    Nils Reimers; Iryna Gurevych · 2019

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. Viewed physical PDF3–4: independent encoders, dot product, loss and negatives. Read PDF5 hybrid-score paragraph; v1 author list differs from final proceedings. Viewed physical PDF2–3: joint BERT comparison, tied encoders, pooling and three objectives; did not reproduce benchmarks. 5 paired equations and four explained exercises. Checked exact/approximate neighbors versus judged relevance, zero/extreme vectors, rotation and stale-cache rejection; counts are conceptual, not runtime.

  • Checked exact/approximate neighbors versus judged relevance, zero/extreme vectors, rotation and stale-cache rejection; counts are conceptual, not runtime.
  • Four computed SVG variants per topic;10 numeric/geometry tests and30 responsive cases passed. Ten selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.