QuiddityML

By · 8 November 2026 · 7 min read

Retrieval and text ranking explained

How a system scores every candidate text against a query with cosine similarity, sorts them into a ranked list, and how precision at k and mean reciprocal rank measure whether the useful results landed near the top, with runnable PyTorch.

Retrieval is the task of finding the items in a collection that best match a query, and ranking is putting those items in order from most to least useful. The items can be documents, images, products or songs. This post uses text, where the task is called text ranking, and a search box over help articles or a support bot looking up the right policy page are examples. The output is not one answer but an ordered list, and the order decides how useful that list is.

Score candidates, then sort them

Retrieval starts with one query, such as "how do I reset my password". It also has many candidates, the texts it could return. A first version needs no new kind of model:

  1. Turn the query into a vector, a fixed-length list of numbers, with an encoder.
  2. Turn every candidate into a vector with the same encoder.
  3. Compute one score for each query and candidate pair.
  4. Sort the candidates from highest score to lowest.

The sorted list is the output. A useful candidate at rank 50 is almost as bad as a missing one, because a person or the next step of a system usually reads only the top few results.

The query Who wrote Pride and Prejudice? is compared against a collection of documents, and the output is a ranked list of results 1 to 4. The output is an ordering, and the order is the point.

The encoder is a model trained so that texts with similar meanings get vectors pointing in similar directions. How that works is the subject of sentence embeddings and semantic similarity. This post starts from the vectors.

One score for each candidate

The usual score is cosine similarity, which compares the directions of two vectors. For a query vector $\mathbf{q}$ and the vector $\mathbf{c}_i$ of candidate $i$, the score $s_i$ is:

$$s_i = \cos(\mathbf{q}, \mathbf{c}_i) = \frac{\mathbf{q} \cdot \mathbf{c}_i}{\|\mathbf{q}\| \|\mathbf{c}_i\|}$$

The top is the dot product, the sum of the products of matching entries, and the bottom multiplies the two vector lengths. The score is 1 when the vectors point the same way, 0 when they are at a right angle and -1 when they point in opposite directions. For example, $\mathbf{q} = [1, 0]$ and $\mathbf{c} = [1, 1]$ give $1/(1 \cdot \sqrt{2}) \approx 0.71$.

With 1,000 candidate passages, retrieval computes 1,000 scores. A query like "how do I reset my password" should score high against "steps to change your account password" and low against "shipping times by region".

A query vector q and three candidate vectors. c1 has cosine 0.87 with q, c2 has 0.50 and c3 has 0.00, so the ranked result is c1, c2, c3.

The retrieval step does not write an answer. It finds the best pieces of text to read next.

Scoring and sorting in Python

With every candidate already turned into a vector, ranking is arithmetic plus a sort. The vectors below have 3 numbers each and stand in for real encoder outputs, which usually have hundreds:

1import torch
2 
3 
4def cosine_similarity(u, v):
5    return ((u * v).sum() / (u.norm() * v.norm())).item()
6 
7 
8def rank_candidates(query_vec, candidates):
9    scored = [(text, cosine_similarity(query_vec, vec)) for text, vec in candidates]
10    return sorted(scored, key=lambda pair: pair[1], reverse=True)
11 
12 
13# toy 3-number vectors standing in for encoder outputs
14query_vec = torch.tensor([0.9, 0.1, 0.2])   # "how do I reset my password"
15candidates = [
16    ("shipping times by region", torch.tensor([0.1, 0.9, 0.1])),
17    ("steps to change your account password", torch.tensor([0.8, 0.2, 0.3])),
18    ("recovering a locked account", torch.tensor([0.6, 0.1, 0.7])),
19]
20for text, score in rank_candidates(query_vec, candidates):
21    print(f"{score:.2f}  {text}")
10.98  steps to change your account password
20.80  recovering a locked account
30.24  shipping times by region

candidates is a list of (text, vector) pairs. Each candidate vector has to come from the same encoder and the same pooling step as the query vector, or the scores compare vectors from different spaces. sorted(..., reverse=True) puts the highest score first.

The rank_candidates code above three candidates, each a text and a vector, and the output sorted by score with candidate 2 first, then candidate 1, then candidate 3.

The same ranking as tensor operations

A Python loop gets slow over thousands of candidates. When the candidate vectors are stacked into one matrix with $n$ rows of $d$ numbers, the whole ranking runs as one matrix product:

1import torch
2 
3 
4def rank_candidates(query_vec, candidate_vecs):
5    query_vec = query_vec / query_vec.norm()
6    candidate_vecs = candidate_vecs / candidate_vecs.norm(dim=1, keepdim=True)
7    scores = candidate_vecs @ query_vec          # (n,) one cosine score per candidate
8    return torch.argsort(scores, descending=True), scores
9 
10 
11query_vec = torch.tensor([0.9, 0.1, 0.2])
12candidate_vecs = torch.tensor([[0.1, 0.9, 0.1],
13                               [0.8, 0.2, 0.3],
14                               [0.6, 0.1, 0.7]])
15order, scores = rank_candidates(query_vec, candidate_vecs)
16print(order, scores.round(decimals=2))
1tensor([1, 2, 0]) tensor([0.2400, 0.9800, 0.8000])

Dividing each vector by its length gives it length 1, and for vectors of length 1 the dot product is the cosine. candidate_vecs @ query_vec multiplies the $(n, d)$ matrix by the $d$ query numbers and returns $n$ scores, the same 0.24, 0.98 and 0.80 as the loop. torch.argsort(scores, descending=True) returns the candidate indices from highest score to lowest, here 1 then 2 then 0.

Storing the candidate vectors already divided by their lengths saves that step at query time.

Ranking metrics: precision at k and MRR

Accuracy is the share of correct predictions, and it does not fit a ranked list because there is no single correct answer to match. The question is where the useful results landed.

Take the query "how do I reset my password" and five ranked results, each marked relevant or not by a person:

1rank 1  steps to change your account password   relevant
2rank 2  shipping times by region                not relevant
3rank 3  recovering a locked account             relevant
4rank 4  our returns policy                      not relevant
5rank 5  contact the support team                not relevant

Precision at k, written $P@k$, is the share of the top $k$ results that are relevant:

$$P@k = \frac{\text{relevant results in the top } k}{k}$$

Here $P@3 = 2/3 \approx 0.67$ and $P@5 = 2/5 = 0.40$. The number falls as $k$ grows because the lower ranks hold fewer relevant results, which is what a ranker doing its job looks like.

Reciprocal rank looks only at the first relevant result. If it sits at rank $r$, the score is $1/r$. In this list the first relevant result is at rank 1, so the reciprocal rank is 1.0. Mean reciprocal rank (MRR) averages that over $Q$ queries, where $r_q$ is the rank of the first relevant result for query $q$:

$$MRR = \frac{1}{Q}\sum_{q=1}^{Q} \frac{1}{r_q}$$

For three queries whose first relevant results sit at ranks 1, 3 and 2, that is $(1 + 0.33 + 0.50) / 3 \approx 0.61$:

1def precision_at_k(relevant, k):
2    return sum(relevant[:k]) / k
3 
4 
5def reciprocal_rank(relevant):
6    for rank, rel in enumerate(relevant, start=1):
7        if rel:
8            return 1 / rank
9    return 0.0
10 
11 
12ranked = [1, 0, 1, 0, 0]   # 1 = a person marked the result relevant, rank 1 first
13print(round(precision_at_k(ranked, 3), 2), round(precision_at_k(ranked, 5), 2), reciprocal_rank(ranked))
14 
15first_relevant_ranks = [1, 3, 2]   # three queries
16mrr = sum(1 / r for r in first_relevant_ranks) / len(first_relevant_ranks)
17print(round(mrr, 2))
10.67 0.4 1.0
20.61

Precision at k for five results marked relevant, not relevant, relevant, not relevant, not relevant: P@3 = 2/3 = 0.67 and P@5 = 2/5 = 0.40. Mean reciprocal rank for three queries with first relevant results at ranks 1, 3 and 2: MRR = 0.61.

Precision at k counts every relevant result in the top $k$ the same. MRR cares only about the first one, which fits cases where one good result is enough, such as finding the one help article that answers a question. When relevance comes in degrees instead of yes or no, normalized discounted cumulative gain (nDCG) is the usual choice. It adds up each result's relevance divided by $\log_2(\text{rank} + 1)$, so lower ranks count for less, then divides by the score of the best possible ordering so a perfect ranking gets 1.

When to use embedding retrieval, and common mistakes

Ranking candidates by cosine similarity fits when queries and texts can match in meaning without sharing words, as "how do I reset my password" and "recovering a locked account" do. It is a common first stage for search over documents and for question-answering systems that need passages to read. This post covers only that first version. Sparse retrieval, dense retrieval and reranking each go much further than this overview.

Mistakes that come up often:

Sentence similarity compares two texts with the same cosine score. Retrieval repeats that comparison between one query and many candidates, and sentence embeddings and semantic similarity explains where the vectors come from. Extractive question answering, explained in question answering in NLP, reads one passage and copies the answer out of it. A retrieval step that passes its top passages to a QA model is how many document question-answering systems are put together.

QuiddityML teaches retrieval and text ranking as a concept in the Intro to NLP track, and the exercises on it include filling in rank_candidates and picking the parameters that belong in its signature.