Sub topic 3
How a cross-encoder reads query and passage together
This chapter assumes you know what a text embedding is, how vector similarity search works, and roughly what a transformer is. It also assumes basic Python and the retrieval vocabulary of query, document, and relevance. You will see how a cross-encoder is built, why joint reading catches relevance that a bi-encoder misses, and how to run one.
The core idea: one pass over both texts
A bi-encoder turns the query and the passage into two separate vectors. The two texts never see each other. Relevance is then a distance between vectors, such as a dot product or cosine similarity.
A cross-encoder works differently. It concatenates the query and the passage into one input sequence and runs the whole sequence through a single transformer. Every token in the query can attend to every token in the passage, and the reverse. The model then outputs a relevance score for that pair.
| Property | Bi-encoder | Cross-encoder |
|---|---|---|
| Input to the model | One text at a time | Query and passage together |
| Output | An embedding vector | A relevance score for the pair |
| Passage work done in advance | Yes, embeddings can be precomputed and indexed | No, the score depends on the query |
| Query-passage interaction | Only through vector distance | Token-level attention across both texts |
| Typical role | First-stage retrieval over millions of items | Reranking tens to hundreds of candidates |
The last row follows from the second to last. Because a cross-encoder score depends on both texts, nothing about a passage can be computed ahead of time. Each new query needs a fresh forward pass for every candidate.
What happens inside the model
Most cross-encoders for reranking are BERT-style encoders. The input is built like a sentence-pair task:
- The query and passage are tokenized separately.
- They are joined with special tokens:
[CLS] query tokens [SEP] passage tokens [SEP]. - The tokenizer also produces segment (token type) ids, so the model knows which tokens belong to the query and which to the passage. Some model families skip segment ids and rely on separator tokens alone.
- The transformer layers run self-attention over the full sequence. Each layer lets query tokens look at passage tokens directly.
- The final hidden state of the
[CLS]token is passed to a small classification head. This head is a linear layer that maps the hidden vector to one number, the relevance score.
The key step is number 4. In a bi-encoder, the model has already collapsed the passage into a single vector before it knows what the query is. A cross-encoder keeps all passage tokens available while it reads the query, so it can compare them one by one.
Why joint reading finds what vectors miss
Consider the query "How do I rotate an API key?" and these three passages:
- "API keys can be rotated from the Security page by creating a new key and deleting the old one."
- "Our API supports JSON and XML response formats."
- "To change your password, open Account Settings and choose Reset password."
All three share vocabulary or topic with the query. The second mentions "API". The third is about changing a credential. A single vector for each passage must blend all of its content, so the similarity scores can end up close together.
A cross-encoder can notice that the query asks for a procedure ("how do I"), that "rotate" matches "rotated" and the steps that follow, and that "API key" in the query lines up with "API keys" in the first passage and not with the password text. Negation, word order, and qualifiers like "not" or "before" are also visible to attention across the pair. A bi-encoder often blurs these distinctions because they get averaged into one vector.
Running a cross-encoder
The sentence-transformers library wraps this model type in the CrossEncoder class. Install it with pip install sentence-transformers. The first call downloads the model weights.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2", max_length=512)
query = "How do I rotate an API key?"
passages = [
"API keys can be rotated from the Security page by creating a new key and deleting the old one.",
"Our API supports JSON and XML response formats.",
"To change your password, open Account Settings and choose Reset password.",
]
scores = model.predict([(query, p) for p in passages])
ranked = sorted(zip(passages, scores), key=lambda x: x[1], reverse=True)
for passage, score in ranked:
print(f"{score:.2f} {passage}")Points to notice in this code:
predicttakes a list of(query, passage)tuples, not two separate lists of texts. Each tuple becomes one joined input sequence.- It returns one score per pair, in the same order as the input. Sorting by score gives the reranked order.
max_length=512caps the length of the joined sequence, covering query and passage together. Longer inputs are truncated. Chapter material on input length covers this in more detail, but remember now that the budget is shared.- The model name tells you something.
ms-marcois the training dataset,MiniLMis the small base model, andL-6means six transformer layers. Fewer layers means faster scoring and usually somewhat lower quality.
The passage about API keys should get the highest score. The exact numbers depend on the model version, so do not hard-code expectations about them.
The cost of reading together
Joint attention is the source of both the quality and the expense.
Self-attention cost grows with the square of the sequence length. A cross-encoder processes the query plus the passage as one sequence, so a long passage costs more than a short one. A bi-encoder pays this cost once per passage at indexing time. A cross-encoder pays it for every candidate at every query.
A rough comparison for a corpus of N passages and one query:
- Bi-encoder: embed the query once, then compare against N precomputed vectors. Vector search with an approximate index makes this sublinear in practice.
- Cross-encoder over the whole corpus: N forward passes through the transformer. For a corpus of a million passages, this is a million model calls per query. That is not workable for interactive search.
This is why a cross-encoder is almost never used alone. It scores a short list produced by a cheaper first stage. The next chapter builds that pipeline.
Common mistakes
- Scoring texts separately. Passing two flat lists of strings, or a single string, to
predictdoes not give you pair scores. Always build(query, passage)tuples. - Mixing up model types. A model named like
all-MiniLM-L6-v2is a bi-encoder and loads withSentenceTransformer. A model likecross-encoder/ms-marco-MiniLM-L-6-v2loads withCrossEncoder. Loading one with the other class either fails or produces meaningless output. - Comparing scores across different models. Each model has its own score scale. A score of 5 from one model has no relation to a 5 from another. Within one query and one model, the order is what matters.
- Ignoring truncation. If the answer sits past the token limit of a long passage, the model never sees it. The score then reflects only the beginning of the passage.
- Expecting reuse across queries. There is nothing to cache per passage. You can cache the final score for an exact repeated
(query, passage)pair, but not partial work shared among different queries.
Reading order matters less than you might think, but position does not vanish
The query comes first and the passage second in the joined sequence. Models are trained with this layout, so keep it. Swapping the order at inference time can lower quality, because the model learned position and segment cues from training data in the standard order. Always pass (query, passage), not (passage, query).
Exercise
A teammate says, "Cross-encoders are strictly better than bi-encoders, so we should drop the bi-encoder and score every passage in our 2 million passage corpus with the cross-encoder." Give two reasons this plan fails, and describe what the cross-encoder does that the bi-encoder cannot.
Show answer
First, a cross-encoder score depends on the query and the passage together, so no per-passage work can be precomputed. Every query would need 2 million transformer forward passes, which is too slow and too expensive for interactive search. Second, the cost of each pass grows with sequence length, so long passages make this worse, and the 512-token limit would still truncate them. What the cross-encoder does better: it concatenates query and passage into one sequence, so self-attention lets query tokens attend to passage tokens directly. It can use word order, qualifiers, and negation that a single passage vector blurs. The right design uses the bi-encoder to select a small candidate set and the cross-encoder to reorder only that set.
Exercise
You call model.predict(["How do I rotate an API key?", "Rotate keys from the Security page."]) on a cross-encoder and get unexpected results or an error. What is wrong, and how do you fix it?
Show answer
The input is a flat list of two strings instead of a list of (query, passage) pairs. The model expects each item to be a two-element pair so it can join them into one sequence. The fix is model.predict([("How do I rotate an API key?", "Rotate keys from the Security page.")]), which returns one score for that pair.