AI Wiki中文/EN

Cross-encoder reranking: read the pair, respect the candidate ceiling

交叉编码器重排

Train a joint pair classifier on ordered triples and vary the first-stage depth.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same words can describe opposite relations

“Rin helps Sol” and “Sol helps Rin” contain the same words. A bag-of-words candidate generator cannot distinguish their direction. A reranker can inspect the query and candidate together, ask which actor plays which role, and change the order—provided both candidates reached it.

A cross-encoder computes a score from a joint query–document input. In the cited BERT reranker, the query is sentence A, the passage is sentence B, and a classifier reads the final CLS representation. The query and passage can interact inside the network before the score is produced. The first version describes a query limit of 64 tokens and a combined sequence limit of 512 tokens; those are that experiment’s conditions, not definitions of every cross-encoder. BERT reranker, section 2

A bi-encoder instead creates independent representations suitable for document caching. SBERT explains why repeated joint BERT comparisons become expensive and motivates reusable sentence embeddings. Joint interaction is an architectural opportunity, not an automatic accuracy guarantee. SBERT, sections 2–3

Joint scoring cannot recover a document absent from its candidate pool.
Joint scoring cannot recover a document absent from its candidate pool.

A score for a pair, a ceiling for a pool

Write the joint representation as H(q,d), a scalar logit as z, and a sigmoid output as p:

z(q,d)=w⊤H(q,d)+b,p(q,d)=11+e−z(q,d).z(q,d)=w^\top H(q,d)+b,\qquad p(q,d)=\frac{1}{1+e^{-z(q,d)}}.

Because sigmoid is increasing, sorting by p or z gives the same order, apart from numerical ties. A sigmoid output is not necessarily a calibrated relevance probability. With binary label y, the stable logit form of binary cross-entropy is:

ℓ(z,y)=log⁡(1+ez)−yz,∂ℓ∂z=σ(z)−y.\ell(z,y)=\log(1+e^z)-yz,\qquad \frac{\partial\ell}{\partial z}=\sigma(z)-y.

The implementation evaluates the first term with logaddexp rather than directly exponentiating a large z. The original BERT reranker trains a binary relevance classifier on positive and negative passages from a retrieval pool. Its setup motivates this loss, not our synthetic labels or MLP. BERT reranker, section 2

Our example weights positives more heavily because there are six positive and thirty negative training pairs. If ω_n is a nonnegative example weight, use:

L=∑nωnℓ(zn,yn)∑nωn.L=\frac{\sum_n\omega_n\ell(z_n,y_n)}{\sum_n\omega_n}.

We set positive weight 5 and negative weight 1, giving equal total positive and negative weight. This changes the training objective; it is not a claim that observed class frequencies or predicted probabilities are calibrated.

Let C(q) be the first-stage pool and R(q) the nonempty relevant set. A reranker that only reorders that pool cannot exceed its relevant coverage:

Recallreranked(q)≤∣C(q)∩R(q)∣∣R(q)∣.\mathrm{Recall}_{\mathrm{reranked}}(q)\leq\frac{|C(q)\cap R(q)|}{|R(q)|}.

A short displayed prefix can fall below this ceiling. Increasing the pool may help coverage, but also increases per-pair computation. With K retained candidates, the query needs K joint evaluations, even if they are batched together.

The original teaching model concatenates position-specific token indicators from the query and document, then applies a hidden ReLU layer and a scalar head:

x=[xq;xd],h=max⁡(0,xW1+b1),z=h⊤w2+b2.x=[x_q;x_d],\qquad h=\max(0,xW_1+b_1),\qquad z=h^\top w_2+b_2.

Both texts affect the hidden activation, so the final representation depends on the pair. This is a small joint classifier, not a Transformer or a reproduction of BERT. Gradients pass through active hidden units; the ReLU derivative is set to zero at its kink.

Six sentences, thirty-six pairs

Run with Python 3.12 and NumPy 1.26. The authored corpus contains six ordered triples, including two reversed pairs: Rin/Sol helping and Ada/Bo following. Each triple is also used as a query; its identical document is the only positive. These exact-identity labels deliberately simplify relevance so that the candidate ceiling is visible.

The vocabulary has six tokens: four actors and two verbs. Each of three positions gets a separate six-way indicator vector, giving 18 features per text and 36 per pair. The MLP has 32 hidden units. Seed 19, learning rate 0.3 and 600 full-batch updates are fixed. All 36 pairs are both trained and inspected; the resulting accuracy is resubstitution, not held-out language understanding.

"""Original jointly encoded pair MLP on six ordered triples; not BERT."""
import json
import numpy as np
TRIPLES=[('Rin','helps','Sol'),('Sol','helps','Rin'),('Ada','follows','Bo'),
         ('Bo','follows','Ada'),('Rin','follows','Ada'),('Ada','helps','Rin')]

def fixture():
    vocabulary={t:i for i,t in enumerate(sorted({t for row in TRIPLES for t in row}))}
    features=np.zeros((6,3*len(vocabulary)))
    for i,row in enumerate(TRIPLES):
        for position,t in enumerate(row):features[i,position*len(vocabulary)+vocabulary[t]]=1
    pairs=np.array([np.concatenate([q,d]) for q in features for d in features])
    return pairs,np.eye(6).ravel(),features

def objective(parameters,x,y):
    w1,b1,w2,b2=parameters;z=x@w1+b1;h=np.maximum(z,0);logits=h@w2+b2
    if not np.isfinite(logits).all() or np.shape(y)!=np.shape(logits):raise ValueError('finite matched labels and logits required')
    weights=np.where(y==1,5.,1.);den=weights.sum()
    loss=float(np.sum(weights*(np.logaddexp(0,logits)-y*logits))/den)
    prob=np.exp(-np.logaddexp(0,-logits));g=weights*(prob-y)/den
    gh=g[:,None]*w2[None,:]*(z>0)
    gradients=(x.T@gh,gh.sum(axis=0),h.T@g,np.array(g.sum()))
    return loss,gradients,logits

def initial():
    x,_,_=fixture();rng=np.random.default_rng(19)
    return (rng.normal(0,.25,(x.shape[1],32)),np.full(32,.03),rng.normal(0,.25,32),np.array(0.))

def candidates(query_id,depth):
    if type(query_id) is not int or not 0<=query_id<6 or type(depth) is not int or not 1<=depth<=6:
        raise ValueError('query ID 0..5 and depth 1..6 required')
    q=set(TRIPLES[query_id])
    return sorted(range(6),key=lambda i:(-len(q&set(TRIPLES[i])),i))[:depth]

def train(steps=600):
    if type(steps) is not int or not 0<=steps<=2000:raise ValueError('steps in 0..2000 required')
    x,y,_=fixture();parameters=initial();first=objective(parameters,x,y)[0]
    for _ in range(steps):
        _,grad,_=objective(parameters,x,y)
        parameters=tuple(p-.3*g for p,g in zip(parameters,grad))
    loss,_,logits=objective(parameters,x,y)
    return first,loss,logits.reshape(6,6)

def demo():
    first,last,scores=train();rows=[]
    for depth in [1,2,6]:
        pools=[candidates(i,depth) for i in range(6)]
        chosen=[max(pool,key=lambda j:(float(scores[i,j]),-j)) for i,pool in enumerate(pools)]
        rows.append(dict(depth=depth,pair_evaluations=6*depth,
                         candidate_coverage=sum(i in p for i,p in enumerate(pools))/6,
                         top1_accuracy=sum(i==j for i,j in enumerate(chosen))/6,ids=chosen))
    return dict(initial_loss=first,final_loss=last,first_stage_ids=[candidates(i,1)[0] for i in range(6)],
                depths=rows,scope='Resubstitution on 36 training pairs of six ordered triples; no natural-language generalization measured.')

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

The non-AI first stage ranks by distinct-token overlap and breaks ties by document ID. Its first choices are [0,0,2,2,4,5], so four of six are correct. At depth one, the reranker receives those same singletons and cannot improve them. At depth two, every correct document is present; the trained model returns [0,1,2,3,4,5]. The weighted loss falls from about 0.726830 to 0.009008.

For all six queries, depths 1,2,6 require 6,12,36 joint pair evaluations. Depth two and depth six both achieve training top-one accuracy 1 here. That makes depth two sufficient for this fixture, not a recommended production cutoff. Independent checks use finite differences for both layers and biases, inspect reversed-order features, and confirm the candidate-coverage ceiling.

With input width F and hidden width H, this MLP costs O(FH) work per pair and stores O(FH) parameters, apart from batch activations. A joint Transformer has different costs: ordinary self-attention includes a quadratic term in the combined sequence length, plus projections and feed-forward layers. Batching K pairs can improve throughput, but does not turn them into one document-independent encoding.

A better judge needs the right case file

The bag-of-words collision is not a proof that bi-encoders cannot represent order. An order-aware independent encoder could distinguish these triples too. The demonstration establishes only that this first-stage representation loses direction and that the joint classifier can fit the labeled pairs.

In an application, annotate query-specific relevance, include hard negatives from the actual first-stage distribution, and keep training, development and final evaluation queries separate. Measure candidate recall, MRR or nDCG at the displayed cutoff, latency distributions and truncation failures. Long passages can lose the answer-bearing part before the model sees them. A powerful scorer cannot repair missing, filtered-out or truncated evidence by sorting alone. Compare reranking against the same candidates in their original order to isolate its contribution.

Document tokenization may be cached, but a standard cross-encoder’s final joint representation cannot be reused unchanged across arbitrary queries. Its cost often suits a second stage after lexical, dense or hybrid retrieval. If the pool is empty or a scorer times out, use a declared fallback rather than returning an unmarked mixture of score conventions.

The missing candidate test

  1. Does joint scoring require the numerical score to be a calibrated probability?

Answer: No. Ranking can use logits directly because sigmoid preserves their order. Calibration requires separate evidence and can be affected by training weights and the candidate distribution.

  1. Query 1 is “Sol helps Rin.” Why does the depth-one system fail even after training?

Answer: Its bag-of-words tie is resolved in favor of document 0, “Rin helps Sol.” Document 1 never enters the singleton pool. The reranker can only return document 0, regardless of its training loss.

  1. Why use positive weight 5 in the toy objective? What total weights result?

Answer: Six positives receive total weight 6×5=30, and thirty negatives receive 30×1=30. This balances their aggregate contribution to the objective; it does not change the actual count of examples or establish probability calibration.

  1. The depth-two training result is perfect. Design a test that could still expose a weak model.

Answer: Hold out new actor combinations, verbs and paraphrases before training, label their candidate pools, and vary truncation and first-stage depth. Measure both candidate coverage and ranking conditional on that pool. Fitting exact-identity triples gives no guarantee on these new cases.

Read the two stages together

The BERT reranker paper makes candidate retrieval, joint scoring and answer generation separate stages. SBERT motivates reusable embeddings by examining the cost of pairwise BERT comparisons. Their contrast explains why practical systems often retrieve broadly, then spend more computation on fewer pairs. It does not imply that either architecture always wins on quality or total cost.

Make a prediction, then check

Can a reranker recover a relevant document excluded from its candidate pool?

Choose one answer

Learning objectives

  • Explain pair-dependent interaction, per-candidate cost and the recall ceiling.
  • Run the original example and explain its failure case.

Prerequisites & connections

Explore related knowledge →

References

  1. Passage Re-ranking with BERT — arXiv v1
    Rodrigo Nogueira; Kyunghyun Cho · 2019
  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 PDF1–2: cascade, joint query/passage input, truncation, CLS classifier and binary loss. Historical experiment conditions, not current rankings. Viewed physical PDF2–3: joint BERT comparison, tied encoders, pooling and three objectives; did not reproduce benchmarks. 5 paired equations and four explained exercises. Finite differences verify both MLP layers and biases; checked order collision, weighted loss stability, candidate ceiling and pair costs. Resubstitution only, not BERT.

  • Finite differences verify both MLP layers and biases; checked order collision, weighted loss stability, candidate ceiling and pair costs. Resubstitution only, not BERT.
  • 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.