Evaluate CLIP-style image-text retrieval with recall at k

Why it matters Recall at 1, 5 and 10 on image-text retrieval is the headline metric for CLIP-style models.

CLIP-style models are judged by retrieval: for each image, is its caption among the top k texts, and the other way round.

Write retrieval_recall(img_emb, txt_emb, ks). Both are (n, d) and pair i is image i with text i. L2-normalise each row and compute S = img @ txt.T (cosine similarity). For image to text, the rank of image i is the number of texts j with S[i, j] > S[i, i] (strictly greater, so ties favour the correct pair). For text to image, the rank of text i is the number of images j with S[j, i] > S[i, i]. Recall at k is the fraction of queries with rank < k. Return {"i2t": [...], "t2i": [...]} as lists of floats, one per k in ks.

Signaturedef retrieval_recall(img_emb, txt_emb, ks)

Example

img = [[1, 0], [0, 1], [1, 1]], txt = [[1, 0.1], [1, 1], [0, 1]], ks = [1, 2] gives i2t [0.3333, 0.6667] and t2i [0.3333, 1.0] (rounded).

Understand the idea

A good image-text model puts each picture close to its own caption. To measure that, use each image as a search query over all captions and check where its true caption lands in the ranking; then do the same in reverse. Recall at k is the share of searches where the right answer appears in the top k, like checking how often the book you want is on the first page of library search results.

Tiny example: image 1 is [1, 0]; its caption [1, 0.1] has cosine 0.995, the best, so rank 0. Image 2 is [0, 1]; its caption [1, 1] scores 0.707 while [0, 1] scores 1, so rank 1. Image 3 is [1, 1]; its caption [0, 1] scores 0.707, beaten by [1, 1] and [1, 0.1], so rank 2. Image-to-text R@1 is 1/3 and R@2 is 2/3.

Rule: rank_i = number of j with S[i, j] > S[i, i]; R@k = mean(rank < k).

CLIP, ALIGN and SigLIP papers all report these numbers on Flickr30k and COCO.

Shapes and data flow

img, txt (n,d) -> S (n,n) -> ranks (n,) per direction
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleretrieval_recall([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], [[1.0, 0.1], [1.0, 1.0], [0.0, 1.0]], [1, 2])
  • Sample 2: perfectretrieval_recall(np.eye(3), np.eye(3) * 2.0, [1])