Search

Search papers and lessons

Cross-Encoder

Level 3 · 11 min read

A cross-encoder feeds a query and a document into one transformer together and reads off a single relevance score, which is more accurate than comparing separate embeddings but costs one model pass per pair.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

A cross-encoder takes a query and a document, joins them into one input, and passes the whole thing through a Transformer together. A small layer on top turns the result into one number, the relevance score for that pair. Because the model reads both texts at once, it can notice fine details, such as a negation or a word that changes the meaning, that a comparison of two separate vectors can miss.

The price is that every query-document pair needs its own model pass. A cross-encoder therefore never searches a whole collection. It re-scores a short list of candidates that a cheaper method has already found, and it sorts that list by score.

Builds on: Transformer, Softmax · Leads to: retrieval-augmented generation pipelines with a re-ranking stage, and it is the accuracy reference for the faster Bi-Encoder

Where it's used

Re-ranking search results. Web and enterprise search engines first pull out a few hundred candidate documents with a fast keyword or vector method, then run a cross-encoder over the top of that list. The model moves the few documents that really answer the query to the top, and the ordering the user sees is the cross-encoder's ordering.

Passage ranking for question answering. Open-domain question answering systems retrieve many passages for a question and then re-rank them, because the passage that contains the answer is often not the one the first stage ranked highest. Nogueira and Cho (2019) showed that a BERT-based cross-encoder gave a large gain over the keyword baseline on the MS MARCO passage ranking benchmark, and this became a standard two-stage pattern.

Retrieval for language-model apps. A retrieval-augmented generation system passes the top few passages to a language model. Re-ranking with a cross-encoder before that step decides which passages the model sees, so a few wrong passages do not crowd out the right one.

How it works

Here is one tiny instance. The query is "cheap flights" and there are two candidate documents: document A, "budget airline fares", and document B, "luxury hotel spa". We want a score for each pair, and we want the more relevant document to get the higher score.

  1. Build the input for pair A. Join the query and the document with special separator tokens: [CLS] cheap flights [SEP] budget airline fares [SEP]. The [CLS] token is a placeholder whose job is to collect a summary of the whole input. Every word is a token, a unit the model reads.
  2. Run the Transformer over the whole input at once. Each token can look at every other token through attention, including the words of the document while it reads the query. This joint reading is what makes the model a cross-encoder.
  3. Read the output vector at the [CLS] position. Pretend the transformer produced hA=[0.5,−1.0]\mathbf{h}_A = [0.5, -1.0]. (These numbers are illustrative, not from a trained model; a real vector has hundreds of entries.)
  4. Apply the scoring layer: multiply the vector by the learned weights w=[2,1]\mathbf{w} = [2, 1] and add the bias b=0.5b = 0.5. The score is 2×0.5+1×(−1.0)+0.5=0.52 \times 0.5 + 1 \times (-1.0) + 0.5 = 0.5. This is the relevance of pair A.
  5. Repeat for pair B, the spa document. Suppose its output vector is hB=[−0.2,0.1]\mathbf{h}_B = [-0.2, 0.1]. The score is 2×(−0.2)+1×0.1+0.5=0.22 \times (-0.2) + 1 \times 0.1 + 0.5 = 0.2.
  6. Sort the candidates by score. A has 0.5 and B has 0.2, so A is ranked first. The scores only mean something when compared with each other for the same query.
flowchart LR
  Q[Query] --> J[Join with separators]
  D[Document] --> J
  J --> T[Transformer reads all tokens together]
  T --> C[Output at CLS position]
  C --> S[Linear layer gives one score]
  S --> R[Sort candidates by score]

The math

Definition: Cross-encoder score

Let qq be a query and dd a document. Let Enc(q,d)\text{Enc}(q, d) be the sequence of tokens [CLS],q1,…,qm,[SEP],d1,…,dn,[SEP]\texttt{[CLS]}, q_1, \dots, q_m, \texttt{[SEP]}, d_1, \dots, d_n, \texttt{[SEP]}. The Transformer maps this sequence to output vectors, and h(q,d)\mathbf{h}(q, d) is the output at the [CLS]\texttt{[CLS]} position. The score is s(q,d)=w⊤h(q,d)+b,s(q, d) = \mathbf{w}^\top \mathbf{h}(q, d) + b, where w\mathbf{w} and bb are learned. Scores are compared only among documents for the same query.

Step 1 in symbols

The input is the concatenation [CLS] q [SEP] d [SEP]\texttt{[CLS]}\ q\ \texttt{[SEP]}\ d\ \texttt{[SEP]}. The model sees L=m+n+3L = m + n + 3 tokens: the two separators and the classification token take three.

Step 2 in symbols

The transformer computes attention over all LL tokens at once. The cost of attention grows with L2L^2, so a long document makes each pass more expensive. Most models of this kind have a maximum input length, often 512 tokens, and longer documents are cut.

Step 3 and 4 in symbols

In the example, hA=(0.5,−1.0)\mathbf{h}_A = (0.5, -1.0) and w=(2,1)\mathbf{w} = (2, 1), so s(q,A)=2×0.5+1×(−1.0)+0.5=0.5.s(q, A) = 2 \times 0.5 + 1 \times (-1.0) + 0.5 = 0.5. For document B, hB=(−0.2,0.1)\mathbf{h}_B = (-0.2, 0.1) gives s(q,B)=−0.4+0.1+0.5=0.2s(q, B) = -0.4 + 0.1 + 0.5 = 0.2.

Step 5 in symbols: turning scores into a ranking

To train or to read the scores as probabilities over a candidate list d1,…,dKd_1, \dots, d_K, apply a Softmax: pi=exp⁡(s(q,di))∑j=1Kexp⁡(s(q,dj)).p_i = \frac{\exp\bigl(s(q, d_i)\bigr)}{\sum_{j=1}^{K} \exp\bigl(s(q, d_j)\bigr)}. Training usually maximises the probability of the one relevant document in the list, which is a Cross-Entropy Loss over the candidates. The loss for one query is −log⁡prel-\log p_{\text{rel}}, where rel is the index of the relevant document.

Worked examples

Example
Tiny: two candidates, one query

Setup: scores s(q,A)=0.5s(q, A) = 0.5 and s(q,B)=0.2s(q, B) = 0.2, as computed above. We turn them into probabilities over the two candidates.

  1. Compute the exponentials: e0.5≈1.649e^{0.5} \approx 1.649 and e0.2≈1.221e^{0.2} \approx 1.221.
  2. Sum them: 1.649+1.221=2.8701.649 + 1.221 = 2.870.
  3. Divide: pA=1.649/2.870≈0.574p_A = 1.649 / 2.870 \approx 0.574 and pB=1.221/2.870≈0.426p_B = 1.221 / 2.870 \approx 0.426.
  4. Check: 0.574+0.426=1.0000.574 + 0.426 = 1.000, as it should.
  5. Ranking: A first, B second.

Interpretation: the model gives A a probability of about 0.57 against 0.43 for B. That is a modest preference, which is typical when the two candidates are both on topic.

Example
Standard: why re-ranking, not searching, is the job of a cross-encoder

Setup: a collection of 1,000,0001{,}000{,}000 documents, a query, and a cross-encoder that takes 10 ms for one pass on a GPU. (The 10 ms is an assumption for this example.)

  1. Search the whole collection with the cross-encoder: 1,000,0001{,}000{,}000 passes, which is 1,000,000×101{,}000{,}000 \times 10 ms =10,000= 10{,}000 s.
  2. Convert to hours: 10,000/3,600≈2.810{,}000 / 3{,}600 \approx 2.8 hours for one query. A search engine answers many queries per second, so this is far too slow.
  3. Re-rank a candidate list of 100 from a fast first stage: 100×10100 \times 10 ms =1= 1 s.
  4. Interpretation: the first stage reduces the work by a factor of 10,000, from a million pairs to one hundred. Whether the right document is in those 100 is a question for the first stage, and the cross-encoder can only reorder what it is given.
Example
Realistic: re-ranking a short list for a question

Setup: a question is answered by document d3. A keyword first stage returns four documents in the order d1, d2, d3, d4. The cross-encoder gives scores d1 = 0.8, d2 = 0.3, d3 = 1.9, d4 = -0.4. We measure the reciprocal rank, which is 1/r1 / r where rr is the position of the relevant document.

  1. Before re-ranking, d3 is at position 3, so the reciprocal rank is 1/3≈0.3331/3 \approx 0.333.
  2. Sort by cross-encoder score, highest first: d3 (1.9), d1 (0.8), d2 (0.3), d4 (-0.4).
  3. After re-ranking, d3 is at position 1, so the reciprocal rank is 1/1=11/1 = 1.
  4. Average the two cases across a set of questions and you get the gain in mean reciprocal rank.
  5. Interpretation: the cross-encoder did not need to see the whole collection. It only had to recognise that d3 answers the question better than the others, and it did.

Try it: the first stage returns d1, d2, d3, d4 in that order, and the relevant document is d3. The cross-encoder scores are d1 = 0.8, d2 = 1.5, d3 = 1.1, d4 = -0.2. What is the reciprocal rank of d3 before and after re-ranking? Answer: before, it is at position 3, so 1/3≈0.3331/3 \approx 0.333. After sorting, the order is d2 (1.5), d3 (1.1), d1 (0.8), d4 (-0.2), so d3 is at position 2 and the reciprocal rank is 1/2=0.51/2 = 0.5.

Common mistakes and tradeoffs

It is tempting to think that a cross-encoder can search a whole collection. In fact it needs one model pass per pair, so it can only score a short list. Searching a million documents with it is many hours per query, as the second example shows. Use a cheaper first stage to pick candidates.

It is tempting to think that the score is a probability, or that a score of 2.0 means the same thing for every query. In fact the raw score is an unnormalised number. It only means something when compared with the other candidates for the same query. The Softmax turns those scores into probabilities over a single list.

It is tempting to think that a cross-encoder gives you an embedding you can store and search with a nearest-neighbour index. In fact it outputs a score for a pair, and the pair cannot be split. A document's representation depends on the query, so there is nothing to precompute. That is the difference from a Bi-Encoder, which embeds each side separately and can index items ahead of time.

It is tempting to think that the cross-encoder always gives better rankings. In fact it is usually the most accurate of the two, but it is slower, and it can only see as much text as its input limit allows. Long documents must be split, and the relevant part may fall outside the window. A common design is to use a Bi-Encoder for recall over the whole collection and a cross-encoder for precision over its top results.

Use a cross-encoder when accuracy matters more than latency and the candidate list is short. Do not use it for the first stage of a large search, and do not use it when the scores need to be stored and reused across queries.

History

Before pre-trained Transformers, ranking models for search used hand-made features such as keyword counts and link structure, combined with learned weights. Neural ranking models existed, but they were hard to train on the small labelled sets that search problems provided.

The BERT model (2018) changed this. It was a transformer pre-trained on large amounts of text, so it already understood word meaning and sentence structure before it saw any search data. Fine-tuning it on a pair-classification task needed only modest labelled data. Nogueira and Cho (2019) used BERT to score query-passage pairs on the MS MARCO benchmark, and the result was a large jump in ranking quality. The two-stage pattern of fast retrieval followed by cross-encoder re-ranking caught on because it gave most of the accuracy at a cost that could be controlled by the length of the candidate list.

Recap

  • A cross-encoder joins the query and document into one input and reads them together with a Transformer.
  • A linear layer on the [CLS] output gives one relevance score per pair.
  • Scores are compared only within one query; a Softmax over the candidates gives probabilities, and training uses Cross-Entropy Loss.
  • The model is accurate but costs one pass per pair, so it re-ranks a short list from a fast first stage.
  • Read next: Bi-Encoder, which trades some accuracy for the ability to index items in advance, and Sentence Embedding, which shows how one vector can summarise a sentence.

Check yourself

QuestionWhat does a cross-encoder receive as input, and what does it output?Show answer

It receives the query and the document joined into one token sequence, with separators, and it outputs one relevance score for that pair.

QuestionA transformer output at the CLS position is h=(1,2)\mathbf{h} = (1, 2), with weights w=(0.5,−1)\mathbf{w} = (0.5, -1) and bias b=0b = 0. What is the score?Show answer

0.5×1+(−1)×2+0=0.5−2=−1.50.5 \times 1 + (-1) \times 2 + 0 = 0.5 - 2 = -1.5.

QuestionWhy is a cross-encoder a poor choice for the first stage of a search over ten million documents, even though it is more accurate than a bi-encoder?Show answer

Each query needs one transformer pass per candidate, so scoring ten million documents would take ten million passes per query. A bi-encoder can embed each document once in advance and answer with a nearest-neighbour lookup, so it is the practical first stage. The cross-encoder then re-ranks a short list.

QuestionTwo queries each get a cross-encoder score of 3.0 for their top document. Can you conclude that both top documents are equally relevant?Show answer

No. Scores are only meaningful among candidates for the same query. Each query may have a different range of scores, so equal numbers across queries do not establish equal relevance.

Sources