近似最近邻:决定省去哪些搜索工作
Approximate nearest-neighbor search
训练粗分区索引,测量召回、探查成本与过滤顺序。
ann-search少搜一些向量,也要知道漏掉了什么
数据库用向量表示文档、图像或其他对象。每次查询,精确扫描可以比较所有合格向量。这是有用的非 AI 基线:没有学习式路由,也没有索引近似。语料规模或请求量让扫描太贵时,近似最近邻搜索 ANN 用一部分准确性换取更少计算、更少存储,或者两者兼得。
近似可以发生在不同位置:粗索引跳过区域,图搜索跳过路径,量化改变评分使用的向量。这些选择可以组合。Faiss GPU 论文区分了精确距离计算、压缩表示上的穷举,以及进一步限制候选列表的 IVFADC。Faiss 第2节
工程问题不是孤立地“找最快索引”,而是满足特定工作负载下明确的召回、延迟、内存、更新与过滤预算。本篇构建粗索引,但在已访问列表中使用精确距离,因此遗漏来自候选选择,不来自压缩。
测近似之前,先固定参照
查询 q 与存储向量 x 的平方欧氏距离为:
越小越好。平方不改变欧氏最近邻的次序,但平方距离本身不满足普通三角不等式。内积搜索则选大分数,余弦消去长度。对非零、单位归一化的向量,余弦与平方欧氏距离的关系是:
因此归一化内积与归一化欧氏距离的排序相同,原始内积与原始欧氏距离却未必。Faiss 明确把比较规则列为搜索问题的一部分。Faiss 第2节
本例粗索引用 k-means 学 L 个中心,把每个数据库向量分到最近的中心。查询访问最近的 p 个中心并收集对应列表。记 a(x) 为向量所属分区,P_p(q) 为选中分区:
靠近分区边界的向量,可能与查询很近,却被分到未访问区域。乘积量化论文的倒排文件搜索通过访问多个粗分区处理这个问题。本例借用粗筛思路,不做残差量化或压缩评分。PQ 第IV.C节
E_k 是相同合格向量中,按相同距离与确定性同分规则取得的精确前 k 项。合格向量至少有 k 个时,Q 条查询的平均召回为:
它衡量是否找回精确邻居,不衡量邻居能否满足人的信息需求。理论近似邻居保证也可能规定返回距离不超过最优距离的1+ε倍,并注明概率。那与实测召回是不同契约,本索引没有这类最坏情况近似保证。
列表内精确评分时,每条查询工作量大致为:
三项分别是中心评分、候选评分和本实现的候选全排序,不含建库及过滤开销。列表均衡时可估计约 Np/L 个候选,但实际列表大小可能不均,应该实数而不是假定均衡。
从160个向量学出索引
使用 Python 3.12 与 NumPy 1.26。种子23生成160个四维数据库向量,以及另外24个查询向量。在数据库上做最多30次 Lloyd 更新,训练八个中心。初始化反复选取离当前最近中心最远的点,空簇保留原中心。这是确定性最远点初始化,不是 k-means++ 概率抽样。
每个数据库向量只分配一次。分别探查1、2、4、8个分区,把前五项对照完整扫描。同距离按向量编号升序。演示接受有界有限坐标,并明确处理空的允许集合。
"""Original inverted-file nearest-neighbor experiment using trained coarse centroids."""
import json
import numpy as np
def matrix(x):
x=np.asarray(x,dtype=float)
if x.ndim!=2 or not 1<=len(x)<=1000 or not 1<=x.shape[1]<=32 or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:
raise ValueError('bounded finite matrix required')
return x
def distances(x,y):return np.sum((x[:,None,:]-y[None,:,:])**2,axis=2)
def fit_centroids(x,count=8,steps=30):
x=matrix(x)
if type(count) is not int or not 1<=count<=len(x) or type(steps) is not int or not 1<=steps<=100:
raise ValueError('valid cluster count and1..100 steps required')
# Deterministic farthest-point initialization; ties choose smallest input ID.
centers=[x[0].copy()]
while len(centers)<count:
nearest=distances(x,np.array(centers)).min(axis=1);centers.append(x[int(np.argmax(nearest))].copy())
centers=np.array(centers)
for _ in range(steps):
labels=distances(x,centers).argmin(axis=1)
updated=np.array([x[labels==i].mean(axis=0) if np.any(labels==i) else centers[i] for i in range(count)])
if np.array_equal(updated,centers):break
centers=updated
return centers,distances(x,centers).argmin(axis=1)
def rank(query,x,ids,k):
q=matrix(np.asarray(query,dtype=float).reshape(1,-1));x=matrix(x)
if q.shape[1]!=x.shape[1] or type(k) is not int or not 1<=k<=len(x):raise ValueError('matching dimensions and valid k required')
candidates=sorted(set(ids))
if any(type(i) is not int or i<0 or i>=len(x) for i in candidates):raise ValueError('candidate ID out of range')
if not candidates:return []
values=distances(q,x[candidates])[0]
return [candidates[j] for j in sorted(range(len(candidates)),key=lambda j:(float(values[j]),candidates[j]))[:k]]
def search(query,x,centers,labels,probes,k=5,allowed=None):
x=matrix(x);centers=matrix(centers);q=matrix(np.asarray(query,dtype=float).reshape(1,-1))
if type(probes) is not int or not 1<=probes<=len(centers):raise ValueError('probe count out of range')
if centers.shape[1]!=x.shape[1] or q.shape[1]!=x.shape[1] or np.shape(labels)!=(len(x),):raise ValueError('incompatible index')
ds=distances(q,centers)[0];cells=sorted(range(len(centers)),key=lambda i:(float(ds[i]),i))[:probes]
permitted=set(range(len(x))) if allowed is None else set(allowed)
ids=[i for i in range(len(x)) if labels[i] in cells and i in permitted]
return dict(ids=rank(query,x,ids,k),vector_distances=len(ids),centroid_distances=len(centers))
def fixture():
rng=np.random.default_rng(23)
x=rng.normal(size=(160,4));queries=rng.normal(size=(24,4))
return x,queries
def demo():
x,queries=fixture();centers,labels=fit_centroids(x);exact=[rank(q,x,range(len(x)),5) for q in queries];rows=[]
for probes in [1,2,4,8]:
runs=[search(q,x,centers,labels,probes) for q in queries]
rows.append(dict(probes=probes,recall_at5=float(np.mean([len(set(r['ids'])&set(e))/5 for r,e in zip(runs,exact)])),
mean_vector_distances=float(np.mean([r['vector_distances'] for r in runs])),centroid_distances=8))
q=queries[0];global_top=exact[0];allowed=set(range(len(x)))-set(global_top)
post=[i for i in global_top if i in allowed]
pre=search(q,x,centers,labels,8,5,allowed)['ids']
v=np.array([[100.,0.],[1.,1.]]);query=np.array([1.,1.]);cos=v@query/(np.linalg.norm(v,axis=1)*np.linalg.norm(query))
return dict(rows=rows,exact_vector_distances=len(x),filtered_post=post,filtered_pre=pre,
metric_example=dict(dot_winner=int(np.argmax(v@query)),cosine_winner=int(np.argmax(cos)),l2_winner=int(np.argmin(distances(query[None,:],v)[0]))),
scope='160 seeded synthetic vectors,24 separate queries; trained coarse IVF, exact distances within selected lists; no compression or timing claim.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
平均前五召回依次为0.825、0.95、1、1;平均评分数据库向量数约22.08、44.92、87.21、160,每条查询还要比较八个中心。四个分区恰好找回这份小数据的全部精确邻居,只是这些查询上的观察,不能保证未来查询。八个分区覆盖所有列表,在相同距离和同分规则下必须吻合精确参照。
距离约定反例使用查询[1,1]和向量[100,0]、[1,1]。原始内积选前者,余弦与欧氏距离选后者。若拿内积索引对照未归一化的欧氏参照,就是把任务不匹配误判成索引错误。
过滤例子刻意排除未过滤前五项。先截取这些结果再过滤,会返回空列表,但在合格总体中仍能找到五个邻居。此实验访问全部分区,以便把过滤问题与 ANN 遗漏分开。这是构造的合格规则,不是真实访问控制系统模型。
基准需要覆盖完整工作负载
测建库时间、查询延迟分布、峰值内存、保留索引大小和更新行为。本程序统计实际候选与中心距离计算次数,却没有对生产引擎做墙钟加速测试;Python 容器、排序、分配和矩阵运算都会影响延迟。粗索引仍存原始向量,没有获得乘积量化的存储压缩收益。
在开发查询上选参数,再用留出查询集评测一次。覆盖分区边界、聚簇数据、重复点与向量分布变化。用数据库向量重建索引属于无监督建库,但在最终评测查询上调探查数,仍会泄漏评测信息。记录准确快照、距离、编码器版本和允许访问的总体。
短列表后过滤可能让结果不足。预过滤、带过滤遍历、过量取候选和精确回退,是不同成本的设计。精确回退也必须遵守相同合格规则。比较图搜索时,应分别检查 HNSW 的建图质量与查询预算;不能假定一个查询参数能修好所有劣质索引。
核对目标,也核对预算
- 为什么本实现探查所有粗分区,就能恢复精确邻居?
答案:每个数据库向量都属于其中一个分区,候选评分使用原始向量,距离及同分规则又与参照一致。如果候选评分是压缩近似,就不能自动得出这个结论。
- 查询[1,1]下,反例中两个原始内积是多少?
答案:分别为100和2。大向量虽然偏离查询方向,仍赢得内积;它的平方欧氏距离为99²+1=9802,第二个向量距离为零。
- 未过滤前五项经过过滤后为空,能证明没有合格邻居吗?
答案:不能;合格向量可能排在这个前缀之外。应搜索合格总体、扩大候选预算或使用明确回退,并以合格总体中的精确结果为参照。
- 怎样公平比较一个与四个探查分区?
答案:固定相同索引、向量快照、距离、合格集合与查询集,报告相对精确前五的召回、候选和中心距离次数,以及实测延迟分布。另记建库与存储成本,不在最终测试查询上选参数。
候选近似与评分近似分开看
对照阅读 Faiss 的精确搜索、ADC、IVFADC 定义,再读 PQ 论文怎样通过多倒排列表修复边界遗漏,同时把量化误差作为另一项问题。本程序隔离前一个机制,没有复现 GPU 内核或论文的十亿规模实验。
先判断,再看解释
先取未过滤的前k项再过滤,一定得到最近的k个合格向量吗?
学习目标
- 在相同距离和合格集合下,对照近似结果与精确邻居。
- 运行原创示例,定位近似误差。
先修与延伸
查看知识关联图 →参考文献
- Billion-scale similarity search with GPUs — arXiv v1
Jeff Johnson; Matthijs Douze; Hervé Jégou · 2017 - Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2
Hervé Jégou; Matthijs Douze; Cordelia Schmid · 2011
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced. Read HAL cover: journal2011, archive deposit2013-05-22. Viewed physical PDF3/4/5/6/8: Lloyd conditions, product codebook, ADC/SDC, Euclidean error bound and inverted lists. No benchmark reproduction. 5 paired equations and four explained exercises. Checked trained coarse centroids, all-cell exactness, nested-pool recall, filtering order, metric mismatch and empty/duplicate cases; no compression or latency claim.
- 核训练粗中心、全分区精确性、嵌套候选召回、过滤顺序、度量错配、空与重复情况;无压缩或延迟声称。
- 每题四张计算SVG,9数值/几何与24响应式组合通过;实看8张最终图,完整页面验收另记。
核对的来源位置:
- Billion-scale similarity search with GPUs — arXiv v1 · Viewed physical PDF2/6: exact squared-L2, IVFADC coarse/fine quantizers, candidate lists and PQ lookup tables; no GPU kernels or speed claims reproduced.
- Product Quantization for Nearest Neighbor Search — HAL inria-00514462v2 · Read HAL cover: journal2011, archive deposit2013-05-22. Viewed physical PDF3/4/5/6/8: Lloyd conditions, product codebook, ADC/SDC, Euclidean error bound and inverted lists. No benchmark reproduction.
相关主题