After reranking util.semantic_search hits with CrossEncoder.rank, your search returns the wrong passages; what mapping did you miss?
answer
- two different index spaces
- rank sees only the candidates
- position in the shortlist
- hits[r['corpus_id']]['corpus_id']
- or return_documents=True for text
basics
~10 sCrossEncoder.rank numbers its results by position in the candidate list you passed, while util.semantic_search's corpus_id indexes the full corpus. Map each reranked result back through the hit list: hits[r['corpus_id']]['corpus_id'].
solid answer
~40 s`util.semantic_search` returns, per query, a list of `{"corpus_id", "score"}` dicts where `corpus_id` is a row in the corpus embeddings. To rerank, you pull those passages out into a candidate list and call `reranker.rank(query, candidates, top_k=10)`. Its results also carry a key named `corpus_id`, but that one is the position in `candidates`, from 0 to 99 for a top 100. Using it directly as a corpus index returns whatever happens to sit at rows 0 to 99 of the corpus. The fix is to go through the hit list: `doc_id = hits[r["corpus_id"]]["corpus_id"]`. If you only need text, `return_documents=True` puts it on each result.
code
python · 17 linesfrom sentence_transformers import CrossEncoder, SentenceTransformer, util
bi = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
corpus_emb = bi.encode(corpus, convert_to_tensor=True) # once, not per query
def search(query: str, k: int = 100, n: int = 10):
query_emb = bi.encode(query, convert_to_tensor=True)
hits = util.semantic_search(query_emb, corpus_emb, top_k=k)[0]
candidates = [corpus[h["corpus_id"]] for h in hits]
ranked = reranker.rank(query, candidates, top_k=n)
results = []
for r in ranked:
doc_id = hits[r["corpus_id"]]["corpus_id"] # shortlist slot -> corpus row
results.append((doc_id, r["score"], corpus[doc_id]))
return resultsgo deeper
Recall that rank numbers results by their position in the list you passed it, so its corpus_id is a shortlist slot, not a corpus row.
Explain the two index spaces and write the mapping hits[r['corpus_id']]['corpus_id'], or the predict-and-zip alternative that keeps alignment.
Show you diagnose the silent symptom, results always drawn from the first corpus rows, and guard it with a test whose answer sits deep in the corpus.
Argue for carrying stable document ids through every stage of a retrieval pipeline so no stage hands back a positional index another stage misreads.
## The retrieve-then-rerank wiring A self-hosted reranking setup in Sentence Transformers usually has two steps in code: 1. **Retrieve** with a bi-encoder: encode the corpus once, encode the query, and call `util.semantic_search(query_emb, corpus_emb, top_k=100)`. 2. **Rerank** those candidates with a **CrossEncoder**, which reads the query and each candidate together and scores the pair. Both functions return lists of dicts with a key called **`corpus_id`**. That shared name is the trap: the two keys index **different lists**. ## Two index spaces with one name | Returned by | `corpus_id` means | Range for a top-100 retrieval | |---|---|---| | `util.semantic_search` | row in the corpus embeddings you searched | 0 to corpus size minus 1 | | `CrossEncoder.rank` | position in the `documents` list you passed to `rank` | 0 to 99 | `rank` has no idea where its `documents` came from. It numbers them 0, 1, 2, ... in the order you supplied, scores each `(query, document)` pair, sorts, and reports the positions. So a reranked result with `corpus_id: 3` means "the fourth candidate you gave me", not "corpus row 3". ## The symptom The code runs, scores look plausible, and results are wrong in a way that is hard to spot: - the top results are always drawn from the **first rows of the corpus** (rows 0 to 99), whatever the query; - reranking appears to **make quality worse** than plain retrieval; - nothing raises an error, because every index is in range. ## The fix Keep the hit list and map through it: ```python candidates = [corpus[h["corpus_id"]] for h in hits] ranked = reranker.rank(query, candidates, top_k=10) for r in ranked: doc_id = hits[r["corpus_id"]]["corpus_id"] # shortlist position -> corpus row ``` Alternatives that avoid the double lookup: - **`return_documents=True`** on `rank` adds a `text` key, which is enough if you only display passages. - **Pass richer objects through your own code**: build `candidates` and a parallel list of your own document ids, and index the parallel list with the reranked position. - **Call `predict` instead** and keep alignment yourself: `scores = reranker.predict([(query, c) for c in candidates])` returns scores in candidate order, which you can zip with `hits` before sorting. ## Other wiring details that matter - **Encode the corpus once.** `semantic_search` should run against cached corpus embeddings; re-encoding per query is a bi-encoder mistake that has nothing to do with the reranker but dominates latency in prototypes. - **The two scores are not comparable.** The retrieval score is a cosine similarity by default; the rerank score is the CrossEncoder's output (raw logits for the MS MARCO checkpoints). Do not blend or threshold them as one number without deliberate normalisation. - **`rank` returns everything by default.** `top_k=None` returns all candidates sorted; set `top_k` to the number you will show. - **Batching and device.** `rank` accepts `batch_size` (default 32) and `device`, the same as `predict`, because it calls `predict` internally. ## Reranking several queries at once `util.semantic_search` accepts a batch of query embeddings and returns **one hit list per query**. `rank`, by contrast, takes **one query**. Two ways to handle a batch: - **Loop over queries** and call `rank` per query, mapping each result through that query's own hit list. Simple, and `rank` still batches the pairs internally. - **Flatten into one `predict` call**: build every `(query_i, candidate)` pair across all queries, call `predict` once, then split the scores back by query using the lengths of each hit list. This keeps the GPU busier when each query has few candidates. Either way, the index you use to look up a corpus row must come from **semantic_search's hits**, never from a reranker's positional output. ## Testing for the bug A cheap regression check: pick a query whose correct passage sits deep in the corpus (well beyond row 100), run the pipeline, and assert that the returned `doc_id` is that passage's row. A unit test with a corpus of a few hundred shuffled strings catches the mapping error immediately, because the top answers will otherwise come from the first rows.
- How would you write the same reranking step with predict instead of rank?Score the pairs in candidate order with `scores = reranker.predict([(query, c) for c in candidates])`, zip them with `hits`, and sort by the CrossEncoder score. Because `predict` returns scores aligned with its input, each score stays attached to its original hit and its corpus row, so no second index is needed.
- Can you add the semantic_search score and the CrossEncoder score to get a combined relevance?Not directly. The retrieval score is a cosine similarity by default, while an MS MARCO CrossEncoder returns raw logits on a different, unbounded scale. Adding them lets one dominate arbitrarily; if you need fusion you normalise or rank-combine deliberately, which is a design decision outside the API.
A shortlist of 100 candidates is renumbered 1 to 100 for the interview panel; the panel's top pick, number 4, is a seat on the shortlist, not employee number 4 in the company directory.
- Both corpus_id keys refer to the same corpus rows
- rank remembers which corpus rows the candidates came from
- A wrong mapping would raise an IndexError
- Reranking made results worse, so the cross-encoder is broken
- Re-encode the corpus on every query before reranking