How to Measure Vector Search Recall@K When Distances Tie

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

How to Measure Vector Search Recall@K When Distances Tie

Two vector indexes return the three closest matches to the same query. They agree on just one document. Your recall test reports 33%, so you start tuning the new index. Before you change a setting, check the distances. Both indexes may have returned an exact answer. There’s a second trap. Suppose you fix the test by accepting every document within the third neighbor’s distance. Now the new index can leave out the closest document and still score 100%. You can reproduce both outcomes with six bytes and a few lines of Python. The question that resolves them is simple. How many IDs in this response could appear together in one valid top-three answer? That question gives you a test you can use when rebuilding a vector index, switching search libraries, or adding a binary candidate stage to a retrieval pipeline.

两个向量索引对同一个查询返回了三个最接近的匹配项,但它们仅在一个文档上达成一致。你的召回率测试显示为 33%,因此你开始调整新索引。在更改设置之前,请先检查距离。两个索引可能都返回了精确的答案。这里还有第二个陷阱:假设你通过接受第三个邻居距离内的所有文档来修复测试,那么新索引现在可以遗漏最接近的文档,却依然能获得 100% 的分数。你可以用六个字节和几行 Python 代码重现这两种结果。解决问题的关键很简单:在这个响应中,有多少个 ID 可以同时出现在一个有效的“前三名”答案中?这个问题为你提供了一种测试方法,可用于重建向量索引、切换搜索库或在检索管道中添加二进制候选阶段时使用。

Build a query with two different correct answers

Imagine a help-center search box that returns three article IDs. Internally, a search stage represents each article with a binary code. For this example, each code is just eight bits. The query is eight zero bits. Hamming distance counts the positions where two codes differ, so you can read each distance by counting the ones.

构建一个具有两个不同正确答案的查询

想象一个返回三个文章 ID 的帮助中心搜索框。在内部,搜索阶段用二进制代码表示每篇文章。在此示例中,每个代码仅为八位。查询是八个零位。汉明距离计算两个代码不同的位置,因此你可以通过计算“1”的个数来读取每个距离。

Article IDBinary codeDistance to query
A000000000
B000000011
C000000101
D000001001
E000010001
F000000112

A belongs in every exact top three. Four articles compete for the remaining two places. An exhaustive search that breaks ties by ascending ID gives A, B, C. A second exhaustive search could give A, D, E. The codes for B and D are different. They tie because they sit the same distance from this query. Removing identical vectors would change nothing here. Try the reverse case with B, C, D. Every item is within one bit of the query. Yet this response omits the only exact match. In a search box for known items, that missing first result could be the one document a user came to find. You can detect the omission even if you have no human labels for the other four articles.

A 属于每一个精确的前三名。四篇文章竞争剩余的两个名额。通过按 ID 升序打破平局的穷举搜索会得出 A、B、C。第二次穷举搜索可能会得出 A、D、E。B 和 D 的代码不同,但它们因为距离查询的距离相同而打平。删除相同的向量在这里不会改变任何结果。尝试 B、C、D 的反向情况:每一项都在查询的一位距离内,但这个响应却遗漏了唯一的精确匹配。在针对已知项目的搜索框中,那个缺失的第一条结果可能正是用户想要寻找的文档。即使你没有其他四篇文章的人工标签,你也可以检测到这种遗漏。

Decide what a hit means in your benchmark

One common test saves a list of exact IDs, intersects it with the returned IDs, and divides by the requested count. The Sentence Transformers Faiss example uses this approach. It answers a useful question when you need to reproduce a particular set of IDs. With an arbitrary tie-break, a low score can also tell you about insertion order or ID order.

确定基准测试中“命中”的含义

一种常见的测试方法是保存一份精确 ID 列表,将其与返回的 ID 取交集,然后除以请求的数量。Sentence Transformers 的 Faiss 示例就使用了这种方法。当你需要重现特定的一组 ID 时,它能回答一个有用的问题。在任意平局决胜的情况下,低分还可以反映出插入顺序或 ID 顺序的问题。

Another test counts returned IDs within the distance of the exact kth neighbor. The ANN-Benchmarks paper describes this definition. It answers “How many of our hits are at least this close?” That fits a distance threshold. A move from A, D, E to B, C, D goes undetected because all six positions across the two responses meet the cutoff.

另一种测试是计算在精确第 k 个邻居距离内的返回 ID 数量。ANN-Benchmarks 论文描述了这种定义。它回答的是“我们的命中项中有多少至少达到这个接近程度?”这符合距离阈值。从 A、D、E 变为 B、C、D 的变化不会被检测到,因为两个响应中的所有六个位置都满足截止条件。

For a top-k membership test, split the eligible records into two groups. Every ID strictly closer than the cutoff owns a place. IDs at the cutoff share the places left over. Give a point for each closer ID returned. Then give a point for each distinct tied ID returned, up to the number of shared places. Divide by the number of places the query can fill. This computes the best overlap with any valid exact top-k set. Loh and Lee give this interpretation of recall for ties in their work on per-query recall guarantees.

对于 Top-k 成员资格测试,将符合条件的记录分为两组。所有严格比截止距离更近的 ID 占据一个名额。处于截止距离的 ID 共享剩余的名额。每返回一个更近的 ID 得一分,然后每返回一个不同的平局 ID 得一分(上限为共享名额的数量)。最后除以查询可填充的名额总数。这计算了与任何有效精确 Top-k 集合的最佳重叠度。Loh 和 Lee 在他们关于单次查询召回保证的工作中给出了这种针对平局的召回率解释。

Write a tie-aware recall test in Python

This example runs on Python 3.10 or later with the standard library. Supply a mapping from every eligible ID to its exact distance. The returned list is in the same order the application received it. Slicing that list before removing duplicate IDs makes each wasted position count.

用 Python 编写支持平局感知的召回测试

此示例在 Python 3.10 或更高版本上运行,仅使用标准库。提供从每个符合条件的 ID 到其精确距离的映射。返回的列表与应用程序接收到的顺序相同。在删除重复 ID 之前对列表进行切片,可以使每个浪费的位置都被计算在内。

def top_k_overlap(exact_distance, returned_ids, k):
    if k < 1:
        raise ValueError("k must be positive")
    target = min(k, len(exact_distance))
    if target == 0:
        return None
    cutoff = sorted(exact_distance.values())[target - 1]
    closer = {i for i, d in exact_distance.items() if d < cutoff}
    tied = {i for i, d in exact_distance.items() if d == cutoff}
    hits = set(returned_ids[:k])
    fixed_hits = len(hits & closer)
    shared_slots = target - len(closer)
    shared_hits = min(shared_slots, len(hits & tied))
    return (fixed_hits + shared_hits) / target

The fourth assertion catches an easy mistake in evaluation code. An adapter might remove the second A, pull E into view, and award full credit. A reader who saw the first three positions got A twice. Score the response at the same point where your application promises three results. If the application itself deduplicates and refills before display, capture the list after that operation. The last two assertions cover small collections. If a tenant has only one eligible document, returning it fills every possible place. If there are none, report an empty-collection case separately. A stream of empty queries can make a broken index look healthy if you assign each one a perfect score. Also count unknown or out-of-scope IDs as contract failures, even if a query has too few eligible records to expose the error through recall alone.

第四个断言捕捉了评估代码中一个容易犯的错误。适配器可能会删除第二个 A,将 E 拉入视野,并给予满分。但观察前三个位置的读者会发现 A 出现了两次。请在应用程序承诺提供三个结果的同一位置对响应进行评分。如果应用程序在显示前自行去重并填充,请在执行该操作后捕获列表。最后两个断言涵盖了小型集合。如果租户只有一个符合条件的文档,返回它就填满了所有可能的位置。如果没有文档,请单独报告空集合的情况。如果你为每个空查询分配满分,那么一连串的空查询可能会让一个损坏的索引看起来很健康。此外,即使查询中符合条件的记录太少而无法仅通过召回率暴露错误,也要将未知或超出范围的 ID 计为契约失败。