Sub topic 5
Reading Cross-Encoder Scores
This chapter assumes you can run Python with sentence-transformers installed. It also assumes you know what a bi-encoder retriever does and what a first-stage candidate list is. Here you will learn what a cross-encoder score is, what it is not, and how to use it safely in a reranking pipeline.
What the model returns
A cross-encoder reads the query and the passage together in one forward pass. The final layer maps the combined representation to a number. For cross-encoder/ms-marco-MiniLM-L-6-v2, that number is a single logit, and predict returns it as-is by default.
A logit is the raw output of the last linear layer, before any squashing function. It can be negative, zero, or well above 1. The model was trained so that higher means "more relevant to this query", and that is the only guarantee you get.
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}")Typical output shows the key-rotation passage with a clearly positive score and the other two with negative scores. The exact numbers depend on the model version and library version, so do not hard-code them in tests.
Scores are ranking signals, not probabilities
Treat the score as an ordering key. Three properties follow from how the model is trained.
- The scale is arbitrary. A score of 4.0 does not mean "80% likely relevant". Training with a ranking or binary cross-entropy loss pushes relevant pairs above irrelevant ones, but it does not fit the output to real frequencies of relevance.
- Scores are comparable within one query, not across queries. For query A the best passage might score 9.1. For query B the best passage might score 2.3, and it could still be the right answer. A fixed threshold such as "keep anything above 5" can silently return nothing for hard or short queries.
- Scores are not comparable across models. Two rerankers have different ranges, different centers, and sometimes different output heads. Never compare or mix raw scores from different models.
Some models also differ in output shape. A model trained with a single label returns one value per pair. A model with several classes, such as natural language inference models, returns several values per pair. A reranker should have one output. If predict returns a two-dimensional array, check the model card before sorting.
Applying an activation
Many libraries let you apply a sigmoid to the logit, which maps it to the range 0 to 1. In sentence-transformers you can do this with the activation_fn argument.
import torch
from sentence_transformers import CrossEncoder
model = CrossEncoder(
"cross-encoder/ms-marco-MiniLM-L-6-v2",
activation_fn=torch.nn.Sigmoid(),
)
pairs = [
("How do I rotate an API key?", "Rotate API keys from the Security page."),
("How do I rotate an API key?", "Billing invoices are emailed monthly."),
]
print(model.predict(pairs))Sigmoid is a monotonic function, so it never changes the order of passages for one query. It only changes how the numbers look. Values near 0 or 1 are easier to read, but they are still not calibrated probabilities. A sigmoid output of 0.9 is not "90% correct" unless you measured it.
Sigmoid also saturates. Two strong passages with logits 8 and 11 become 0.9997 and 0.99998. The difference is real in logit space and nearly invisible after the sigmoid. If you need to tell strong candidates apart, or you plan to blend scores, keep the logits.
Using scores in a pipeline
The ranking can be used directly. Scores matter in three further cases.
- Cutting the list. You may want to drop weak passages before sending context to a language model.
- Detecting "no good answer". You may want to refuse or fall back when nothing is relevant.
- Combining with other signals. You may want to blend the reranker with the first-stage score or a recency feature.
Each case needs a different tool. The diagram shows how to choose.
Thresholds need calibration
If you need a cut-off, measure it. Collect queries with human relevance labels, score the labeled pairs, and pick the threshold that gives the precision and recall you want. Then check it on queries you did not use to choose it.
def best_threshold(scores, labels, min_precision=0.9):
"""Return the lowest score threshold that reaches min_precision.
scores: list of floats from the reranker
labels: list of 0/1 relevance judgments, same order
"""
pairs = sorted(zip(scores, labels), reverse=True)
tp = 0
best = None
for i, (score, label) in enumerate(pairs, start=1):
tp += label
if tp / i >= min_precision:
best = score
return best
scores = [8.2, 6.9, 5.1, 2.0, 0.4, -1.5, -3.0]
labels = [1, 1, 1, 0, 1, 0, 0]
print(best_threshold(scores, labels, min_precision=0.75))This function walks down the ranked list and remembers the last score at which precision was still at least the target. It returns 0.4 for the sample data. The threshold is only valid for the same model, the same kind of queries, and the same kind of passages. If you change any of them, fit it again.
For a smoother probability estimate, fit a one-feature logistic regression (Platt scaling) or isotonic regression on labeled scores. This gives you a calibrated probability for the model and domain you fitted it on.
Blending with other signals
Raw cross-encoder logits and cosine similarities live on different scales, so a weighted sum such as 0.5 * cosine + 0.5 * logit mostly reflects whichever has the wider range. You have two safer options.
- Fuse by rank. Use reciprocal rank fusion, which ignores score scale entirely. This is the approach from the hybrid retrieval chapter.
- Normalize per query. Rescale each list to a common range, such as min-max within the candidate set, before weighting. This is sensitive to outliers and to the candidate set size, so check it against a labeled set.
In most systems the cross-encoder should have the final say. A common design is to let it decide the order and use the other signals only to build the candidate pool.
Pitfalls when reading scores
- Ties and near-ties. Scores within a small margin are effectively a tie. Reordering on a difference of 0.01 is noise, and different batch sizes or hardware can shift floating point results slightly. Do not write tests that depend on exact order of near-equal scores.
- Score gaps carry information. A large drop between rank 1 and rank 2 suggests one clear answer. A flat profile suggests several similar passages or no good answer. You can use the gap as a rough confidence hint, but verify it on labeled data.
- Top score can be high for the wrong reason. A passage that repeats the query words can score well without answering. Inspect high-scoring errors, not just the metric.
- Truncation changes the score. If a passage is longer than
max_length, the model scores only the part that fit. A relevant sentence beyond the limit is invisible. The input length chapter covers this in detail. - Short candidate lists skew per-query normalization. With three candidates, min-max scaling stretches tiny differences to fill 0 to 1.
A quick sanity check
Before trusting a reranker in production, run a small test: score one clearly relevant pair, one clearly irrelevant pair, and one pair that shares words with the query but does not answer it. The relevant pair should score highest and the word-overlap pair should score below it. If that fails on your own data, the model may be a poor fit for your domain.
from sentence_transformers import CrossEncoder
model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
query = "How do I rotate an API key?"
cases = {
"relevant": "Rotate API keys from the Security page by creating a new key.",
"overlap_only": "The API key field is shown on the Security page header.",
"irrelevant": "Invoices are emailed on the first of each month.",
}
scores = model.predict([(query, text) for text in cases.values()])
for name, score in zip(cases, scores):
print(f"{name:13s} {score:.2f}")
assert scores[0] > scores[2], "relevant should beat irrelevant"The assert checks only the clear-cut ordering, which a working model should pass. The overlap-only case is one to read by eye, since small models sometimes rank it close to the relevant one.
Summary of rules
| Task | Safe approach | Unsafe approach |
|---|---|---|
| Order passages for one query | Sort by logit | Compare to a fixed cut-off first |
| Compare passages across queries | Avoid, or calibrate first | Compare raw scores directly |
| Compare two models | Compare metrics on labeled data | Compare raw score values |
| Drop weak passages | Threshold fit on labeled data | Threshold copied from elsewhere |
| Blend with dense score | Rank fusion or per-query normalization | Weighted sum of raw values |
Exercise
A teammate sets if score > 0.5: keep after applying a sigmoid to logits from ms-marco-MiniLM-L-6-v2, and says it keeps only passages that are "more than 50% likely to be relevant". Give two reasons this claim is wrong, and say what you would do instead.
Show answer
First, the sigmoid output is a monotonic rescaling of an arbitrary logit, not a calibrated probability. The model was trained to order passages, so 0.5 has no guaranteed link to a 50% chance of relevance. Second, score levels vary by query and by domain, so one fixed cut-off may keep too much for easy queries and drop correct answers for hard ones. Instead, collect labeled queries from your own domain, score them, and choose a threshold (or fit Platt scaling or isotonic regression) that meets your target precision and recall. Validate it on held-out queries and refit it whenever the model or data changes.
Exercise
You blend scores as final = 0.5 * cosine + 0.5 * logit and find that the cross-encoder dominates the ranking. Why does this happen, and name two ways to fix it.
Show answer
Cosine similarity usually falls in a narrow range such as 0 to 1, while cross-encoder logits can span a range of ten or more units, so the logit term contributes far more variance to the sum. Fixes: use reciprocal rank fusion, which uses only ranks, or normalize each score list per query (for example min-max) before weighting and tune the weights on labeled data. You can also let the cross-encoder alone decide the final order and use the dense score only for candidate retrieval.