AI Wiki中文/EN

Bi-encoders: compute separately, learn what belongs together

双编码器

Train two small encoders and inspect a false negative through its gradient.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Read the library before the question arrives

A search service cannot reread a million long documents with every question. A bi-encoder computes a document representation without seeing the current query, stores it, and later compares it with a separately computed query representation. The expensive document encoding can be reused. The price is that the final score must work with what those representations retained.

“Bi” describes two encoding paths, not necessarily two parameter sets. DPR uses independent question and passage BERT encoders. SBERT’s siamese architecture ties the weights of its two sentence encoders. Pooling and training objectives also differ: DPR uses a retrieval contrastive loss, while SBERT describes classification, regression and triplet objectives. Do not identify the entire architecture family with one loss. DPR, section 3 SBERT, figures 1–2 and section 3

The practical question here is how learning pulls useful pairs together—and what happens when the label set calls a useful passage a negative. Dense retrieval handles the subsequent index search.

A false-negative label can reverse a relevant passage’s score gradient.
A false-negative label can reverse a relevant passage’s score gradient.

A positive set, not just a diagonal

Let B queries and M documents produce row-vector matrices Q and D, each with h columns. A positive temperature τ changes the scale of the score matrix:

Qi=fθ(qi),Dj=gϕ(dj),S=QD⊤/τ.Q_i=f_\theta(q_i),\qquad D_j=g_\phi(d_j),\qquad S=QD^\top/\tau.

With one marked positive p_i, softmax contrastive learning minimizes negative log probability. Subtracting the maximum score before exponentiation gives the same probabilities while avoiding overflow:

ℓi=−Si,pi+log⁡∑j=1MeSij.\ell_i=-S_{i,p_i}+\log\sum_{j=1}^{M}e^{S_{ij}}.

DPR’s in-batch scheme reuses other questions’ positive passages as negatives for the current question. This is efficient, but its negative labels require care when two queries share relevant passages. The paper describes the training scheme; the false-negative gradient below follows directly from the loss. DPR, section 3.2

Our authored task marks every known relevant document in a nonempty set P_i. We use a set-probability objective:

L=1B∑i=1B[log⁡∑j=1MeSij−log⁡∑j∈PieSij].L=\frac1B\sum_{i=1}^{B}\left[\log\sum_{j=1}^{M}e^{S_{ij}}-\log\sum_{j\in P_i}e^{S_{ij}}\right].

This loss rewards total probability on the positive set. It does not require each positive to receive equal probability; it can focus on an easy positive. An average of separate positive log probabilities is a different objective. When P_i contains one document, the expression reduces to the single-positive loss.

Let p be the softmax over all documents and p⁺ the softmax restricted to positives, extended by zero elsewhere. Differentiating the two log-sum-exp terms gives:

∂L∂Sij=pij−pij+B.\frac{\partial L}{\partial S_{ij}}=\frac{p_{ij}-p^+_{ij}}{B}.

For three equal scores and a single positive at position 0, the score gradient is [−2/3,1/3,1/3]. Gradient descent subtracts it: position 1 is pushed down even if a human would judge it relevant. Marking positions 0 and 1 positive changes the gradient to [−1/6,−1/6,1/3]. The loss follows labels, not unstated meaning.

Our tiny encoders use mean token indicators X and separate matrices W with tanh activation. Backpropagation through their dot products is:

Q=tanh⁡(XqWq),D=tanh⁡(XdWd),GQ=GSD/τ,GD=GS⊤Q/τ.Q=\tanh(X_qW_q),\quad D=\tanh(X_dW_d),\quad G_Q=G_SD/\tau,\quad G_D=G_S^\top Q/\tau.

Multiplying by the derivative of tanh and applying the linear-layer rule yields:

∇WqL=Xq⊤[GQ⊙(1−Q2)],∇WdL=Xd⊤[GD⊙(1−D2)].\nabla_{W_q}L=X_q^\top\left[G_Q\odot(1-Q^2)\right],\qquad \nabla_{W_d}L=X_d^\top\left[G_D\odot(1-D^2)\right].

Here ⊙ is elementwise multiplication. These are derivatives of our toy model, not a substitute for backpropagating through the BERT networks in the papers.

Watch one label reverse a gradient

Run with Python 3.12 and NumPy 1.26. Nine authored fragments include bicycle repair, car repair, a cell-cycle record and an empty document. The three queries use those needs. Positive document sets are {0,4,5,7}, {3} and {8}. Vocabulary comes from the fixture; ASCII lowercase token counts are averaged over known tokens. Unknown tokens are ignored, and text with no known token becomes zero.

The two untied encoders have four output coordinates. Seed 11, temperature 0.5, learning rate 0.6 and 400 full-batch updates are fixed. There is no pretrained model, held-out split or semantic claim about unseen language.

"""Original NumPy dual encoder; fitting the training fixture is not generalization."""
import json
import re
import numpy as np
DOCS=['repair bicycle brake cable','bicycle brake adjustment guide','bicycle paint blue frame',
      'car brake cable repair','cycle stopping wire replacement','repair bicycle brake cable cable cable',
      '', 'brake cable bicycle repair','cell cycle stopping research']
QUERIES=['repair bicycle brake cable','car brake repair','cell cycle research']
POSITIVES=({0,4,5,7},{3},{8})

def features(texts, vocabulary):
    out=np.zeros((len(texts),len(vocabulary)))
    for i,text in enumerate(texts):
        tokens=re.findall('[a-z]+',text.lower())
        known=[vocabulary[t] for t in tokens if t in vocabulary]
        for j in known: out[i,j]+=1/len(known)
    return out

def fixture():
    vocab={t:i for i,t in enumerate(sorted(set(re.findall('[a-z]+',' '.join(DOCS+QUERIES)))))}
    labels=np.zeros((3,9),dtype=bool)
    for i,ids in enumerate(POSITIVES):labels[i,list(ids)]=True
    return features(QUERIES,vocab),features(DOCS,vocab),labels

def contrastive(scores,positive):
    scores=np.asarray(scores,dtype=float); positive=np.asarray(positive,dtype=bool)
    if scores.ndim!=2 or not scores.size or scores.shape!=positive.shape or not np.isfinite(scores).all() or not positive.any(axis=1).all():
        raise ValueError('finite scores and at least one positive per row required')
    z=scores-scores.max(axis=1,keepdims=True); e=np.exp(z); total=e.sum(axis=1,keepdims=True)
    zp=np.where(positive,scores,-np.inf); shift=zp.max(axis=1,keepdims=True)
    ep=np.where(positive,np.exp(zp-shift),0.); mass=ep.sum(axis=1,keepdims=True)
    loss=np.mean(scores.max(axis=1,keepdims=True)+np.log(total)-shift-np.log(mass))
    return float(loss),(e/total-ep/mass)/len(scores)

def objective(wq,wd,xq,xd,positive,temperature=.5):
    if not np.isfinite(temperature) or temperature<=0:raise ValueError('positive temperature required')
    q=np.tanh(xq@wq);d=np.tanh(xd@wd)
    loss,g=contrastive(q@d.T/temperature,positive)
    return loss,(xq.T@((g@d/temperature)*(1-q*q)),xd.T@((g.T@q/temperature)*(1-d*d)))

def train(steps=400):
    if type(steps) is not int or not 0<=steps<=2000:raise ValueError('steps in 0..2000 required')
    xq,xd,y=fixture();rng=np.random.default_rng(11)
    wq=rng.normal(0,.3,(xq.shape[1],4));wd=rng.normal(0,.3,wq.shape)
    initial=objective(wq,wd,xq,xd,y)[0]
    for _ in range(steps):
        _,(gq,gd)=objective(wq,wd,xq,xd,y);wq-=.6*gq;wd-=.6*gd
    q=np.tanh(xq@wq);d=np.tanh(xd@wd);s=q@d.T/.5
    return dict(initial_loss=initial,final_loss=objective(wq,wd,xq,xd,y)[0],
                top1=np.argmax(s,axis=1).tolist(),scores=s.tolist(),
                cached_max_error=float(np.max(np.abs(s-np.array([[a@b/.5 for b in d] for a in q])))))

def demo():
    result=train();scores=np.zeros((1,3));one=np.array([[True,False,False]]);multi=np.array([[True,True,False]])
    result.update(false_negative_gradient=contrastive(scores,one)[1][0].tolist(),
                  multi_positive_gradient=contrastive(scores,multi)[1][0].tolist(),
                  scope='Three training queries, nine authored fragments; untied tanh encoders, not DPR or SBERT.')
    return result

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

The loss falls from about 1.695449 to 0.030167; top documents are [5,3,8], all valid positives for the training queries. Cached document embeddings and pairwise dot products agree to floating-point tolerance, with maximum error below 10⁻¹². The false-negative demonstration uses uniform scores so that its fractions can also be checked by hand. Independent finite differences check both encoder gradients.

Encoding the M documents can be amortized across queries as long as the document encoder and preprocessing remain fixed. A training step forms B×M scores at O(BMh) multiplication cost, in addition to the encoder work and stored activations. In-batch negatives reduce separate encoding work but do not make the score matrix free. Updating the document encoder invalidates its cached embeddings.

A cheap comparison can hide missing information

Our mean-token input discards order, so “Rin helps Sol” and “Sol helps Rin” would be indistinguishable. This is a property of this input representation, not a theorem that all bi-encoders lose word order. Transformer encoders can retain order within each text. A cross-encoder additionally lets the query and candidate interact before their final score.

Negatives can be too easy, genuinely irrelevant but difficult, or actually relevant and mislabeled. Mine difficult candidates on training data, inspect labels and keep development and test data separate. Duplicates and related queries can contaminate batch negatives. The multi-positive objective handles known positives only; unrecognized relevant passages remain possible false negatives. Because it rewards positive-set mass, inspect per-positive recall rather than assuming every positive is learned equally.

What did the model learn from the labels?

  1. Must a bi-encoder have two different parameter sets?

Answer: No. The two paths may share weights, as in the cited SBERT architecture, or use independent weights, as in DPR and this toy model. Independent encoding is the caching requirement.

  1. At uniform scores, compute the gradient for a second relevant document mislabeled negative.

Answer: With one positive among three, its softmax probability is 1/3 and its positive probability is zero, so its score gradient is +1/3 for B=1. Gradient descent pushes the score down. Marking two positives changes it to 1/3−1/2=−1/6.

  1. If one positive already takes nearly all positive-set probability, must the loss raise another positive’s score equally?

Answer: No. The numerator is the sum of positive exponentials. Increasing mass on an easy positive can satisfy the objective; equal treatment would require a different objective or additional checks.

  1. Design a useful evaluation beyond the three training queries.

Answer: Hold out needs and paraphrases before tuning, annotate multiple relevant passages, and compare lexical and dense retrieval under a common snapshot and cutoff. Report candidate recall and errors on rare terms and order-sensitive queries. Training loss alone cannot establish generalization.

Keep the architecture and objective separate

DPR provides the retrieval-specific negative-sampling and inner-product example; SBERT makes shared-weight pooling and several objectives explicit. The miniature tanh model isolates gradient direction and caching. It does not reproduce either pretrained encoder, dataset or reported performance.

Make a prediction, then check

What happens to a known relevant passage treated as a negative in the denominator?

Choose one answer

Learning objectives

  • Derive a multi-positive loss and explain independent document caching.
  • 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. 6 paired equations and four explained exercises. Finite differences verify both encoder gradients; checked multi-positive set probability, false negatives, score shifts, empty/OOV and document caching. Training fixture only.

  • Finite differences verify both encoder gradients; checked multi-positive set probability, false negatives, score shifts, empty/OOV and document caching. Training fixture only.
  • 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.