HNSW:建出捷径,再按预算搜索
Hierarchical navigable small worlds
构建真实分层图,比较贪心下行与更宽候选搜索。
hnsw先经过少数路标,再走近处街区
精确最近邻扫描访问每个存储向量。近邻图则把相近向量连起来,沿连接搜索。但起点不合适时,可能绕很远或困在局部死角。HNSW 增加稀疏上层作为远距离路由结构,再到更密的底层,用较宽候选预算搜索。
HNSW 指分层可导航小世界。它的图逐点构建,不是事先给定的地图:每次插入要搜索已有层、选择邻居,还可能裁剪旧连接。所引 v4 把插入、层内搜索、两种邻居选择规则与查询搜索分别列成算法。本实现按照该版本,并声明教学限制。HNSW 算法1—5
首稿出现于2016年,所引 v4 是2018年修订。读过早期伪代码和后期库 README,不代表实现细节完全相同。本文使用 hnswlib 官方 README 区分建库与查询控制,不声称本例就是这个库。hnswlib API方法
层级抽一次,预算每次搜索选
对每个插入向量,从(0,1]均匀抽 U,再得到非负最高层 ℓ。论文使用层级乘数,本例根据 M 选择它:
最高层为 ℓ 的点出现在0至ℓ的每一层。暂不考虑本例层数上限,到达第 j 层的概率为:
所以上层逐渐变小。对这些离散尾概率求和,得到平均层成员数:
推导针对无上限离散规则。本例最高12层,使无穷和改为 j=0至12的有限和。随机抽层不能保证每种插入顺序、每份数据都得到理想图。
插入点 q 时,从当前入口的最高层开始。高于 q 分配层级的部分,以预算一逐层下行;到了双方共有的下层,用 efConstruction 做更宽搜索,选最多 M 个邻居,再添加双向连接。已有邻接表超过本层容量时裁剪;若 q 成为最高层节点,就更新入口。HNSW 算法1
邻居启发式先考虑离 q 近的候选。只有候选 c 离 q 比离每个已选邻居 r 都近时,才接受它:
目的是保留不同方向的路线,不把全部连接花在一个紧密小簇中。论文还给出简单的最近 M 个规则。本例启发式关闭候选扩展,允许用此前被拒候选补足空位,明确采用算法4中的这两个选项。这里所有比较改用平方欧氏距离,大小关系不变。
层内搜索维护访问集合、最近优先的候选堆,以及最远优先的保留结果堆 W,后者最多放 ef 个点。弹出候选 c,检查未访问的出邻居,并保留有希望的结果。W 已满时,停止条件为:
这是图搜索停止规则,不是“所有未访问点都更远”的证明。有用邻居可能藏在一个更差的中间点之后。候选堆和累计访问集合都可能超过 ef,所以 ef 不是距离计算次数。查询在上层用预算一,在底层使用所选 ef,再返回 k 项,要求 ef 至少为 k。HNSW 算法2及5
存储向量至少 k 个时,设精确前 k 项为 E,返回集合为 A,质量指标为:
精确和图搜索都用平方欧氏距离,同分按编号升序;这是邻居一致性,不是相关性判断。
先把图建出来,再搜索
使用 Python 3.12 与 NumPy 1.26。种子31生成120个四维数据库向量、另外20个查询,种子29控制插入层级。M=4、efConstruction=20,底层最大出度8、上层4,最高层限制为12。教学类最多存500个向量,并限制为有界有限坐标。
"""Original bounded HNSW teaching implementation, following v4 algorithms1–5."""
import heapq
import json
import math
import numpy as np
class HNSW:
def __init__(self,dimension,m=4,ef_construction=20,seed=29,heuristic=True):
if type(dimension) is not int or not 1<=dimension<=32 or type(m) is not int or not 2<=m<=32:
raise ValueError('dimension1..32 and M2..32 required')
if type(ef_construction) is not int or not m<=ef_construction<=1000:raise ValueError('efConstruction must be M..1000')
self.dimension=dimension;self.m=m;self.efc=ef_construction;self.heuristic=heuristic
self.rng=np.random.default_rng(seed);self.vectors=[];self.levels=[];self.graph=[]
self.entry=None;self.top=-1;self.distance_calls=0
def vector(self,x):
x=np.asarray(x,dtype=float)
if x.shape!=(self.dimension,) or not np.isfinite(x).all() or np.max(np.abs(x))>1e6:raise ValueError('bounded vector of matching dimension required')
return x.copy()
def distance(self,a,b):
self.distance_calls+=1
return float(np.sum((a-b)**2))
def layer_search(self,q,entries,ef,level):
visited=set(entries);candidates=[];best=[]
for i in sorted(visited):
d=self.distance(q,self.vectors[i]);heapq.heappush(candidates,(d,i));heapq.heappush(best,(-d,-i))
while len(best)>ef:heapq.heappop(best)
while candidates:
dist,i=heapq.heappop(candidates)
if len(best)>=ef and dist>-best[0][0]:break
for j in sorted(self.graph[level][i]):
if j in visited:continue
visited.add(j);d=self.distance(q,self.vectors[j]);worst=(-best[0][0],-best[0][1])
if len(best)<ef or (d,j)<worst:
heapq.heappush(candidates,(d,j));heapq.heappush(best,(-d,-j))
if len(best)>ef:heapq.heappop(best)
return [i for _,i in sorted((-d,-i) for d,i in best)]
def select(self,q,candidates,capacity):
ordered=sorted(set(candidates),key=lambda i:(self.distance(q,self.vectors[i]),i))
if not self.heuristic:return ordered[:capacity]
selected=[];rejected=[]
for i in ordered:
if len(selected)>=capacity:break
dq=self.distance(q,self.vectors[i])
if all(dq<self.distance(self.vectors[i],self.vectors[j]) for j in selected):selected.append(i)
else:rejected.append(i)
# extendCandidates=False; keepPrunedConnections=True.
selected.extend(rejected[:capacity-len(selected)])
return selected
def add(self,x,level=None):
q=self.vector(x)
if len(self.vectors)>=500:raise ValueError('teaching capacity500 exceeded')
if level is None:level=min(12,int(-math.log(1-self.rng.random())/math.log(self.m)))
if type(level) is not int or not 0<=level<=12:raise ValueError('level must be0..12')
index=len(self.vectors);self.vectors.append(q);self.levels.append(level)
while len(self.graph)<=level:self.graph.append({})
for layer in range(level+1):self.graph[layer][index]=set()
if self.entry is None:self.entry=index;self.top=level;return index
entries=[self.entry]
for layer in range(self.top,level,-1):entries=self.layer_search(q,entries,1,layer)
for layer in range(min(self.top,level),-1,-1):
found=self.layer_search(q,entries,self.efc,layer);neighbors=self.select(q,found,self.m)
self.graph[layer][index].update(neighbors)
for j in neighbors:
self.graph[layer][j].add(index)
capacity=2*self.m if layer==0 else self.m
if len(self.graph[layer][j])>capacity:
self.graph[layer][j]=set(self.select(self.vectors[j],self.graph[layer][j],capacity))
entries=found
if level>self.top:self.entry=index;self.top=level
return index
def search(self,x,k=5,ef=10):
q=self.vector(x)
if type(k) is not int or type(ef) is not int or not 1<=k<=ef<=1000:raise ValueError('1<=k<=ef<=1000 required')
self.distance_calls=0
if self.entry is None:return dict(ids=[],distance_calls=0)
entries=[self.entry]
for layer in range(self.top,0,-1):entries=self.layer_search(q,entries,1,layer)
result=self.layer_search(q,entries,ef,0)[:k]
return dict(ids=result,distance_calls=self.distance_calls)
def fixture():
rng=np.random.default_rng(31);return rng.normal(size=(120,4)),rng.normal(size=(20,4))
def demo():
x,queries=fixture();index=HNSW(4);index.distance_calls=0
for row in x:index.add(row)
build_calls=index.distance_calls
exact=[sorted(range(len(x)),key=lambda i:(float(np.sum((q-x[i])**2)),i))[:5] for q in queries]
rows=[]
for ef in [5,10,30,120]:
runs=[index.search(q,5,ef) for q in queries]
rows.append(dict(ef=ef,recall_at5=float(np.mean([len(set(r['ids'])&set(e))/5 for r,e in zip(runs,exact)])),
mean_distance_calls=float(np.mean([r['distance_calls'] for r in runs]))))
return dict(rows=rows,levels=[len(layer) for layer in index.graph],
directed_edges=[sum(len(v) for v in layer.values()) for layer in index.graph],
build_distance_calls=build_calls,
scope='120 synthetic vectors,20 separate queries; sequential insertion, M4, efConstruction20, level cap12, no deletion/filtering/concurrency.')
if __name__=='__main__':print(json.dumps(demo(),sort_keys=True,allow_nan=False))
建出的各层有[120,29,13,2]个节点,出邻接项数为[765,116,52,2]。新选连接会双向加入,但后续剪枝只替换被裁剪节点的出邻接表,因此原本互为邻居的关系未必一直互为邻居。这是本实现的局部邻接更新行为;把全部存储边说成永久无向边,会描述错误。
ef=5、10、30、120时,平均前五召回为0.94、0.99、1、1;平均距离调用为38.1、49.3、83.1、134.7。最后一个数大于120,因为还计算上层访问与跨层重复评分。建图总计21,083次距离调用,包含邻居选择和剪枝。它们是本程序测得的调用次数,不是墙钟速度,也不是 hnswlib 性能声称。
测试把小型完整底层图与穷举对照,检查每层成员和出度,验证重复点、确定性插入,并用三候选例子检查多样化是否选择不同方向。本例召回达到1,不证明任意图都能精确搜索;即使 ef 很大,也找不回从入口沿出边无法到达的点。
建图质量与查询努力,是不同旋钮
M 影响连通结构与内存,efConstruction 影响插入探索,查询 ef 影响底层搜索努力。hnswlib 通过 init_index 暴露建库控制,通过 set_ef 控制查询努力。它的过滤、删除、更新和线程行为都是额外工程,本教学实现没有覆盖。hnswlib init_index及set_ef
D 维向量每次距离计算 O(D),堆操作与邻居选择比较另有开销。原向量存储 O(ND),邻接存储取决于出度限制和层成员数。论文讨论对数增长时使用几何假设与实验证据,明确区分理想 Delaunay 论证和实际近似图。它不是对任意高维数据无条件成立的最坏 O(log N) 保证,搜索可能访问线性数量的存储点。HNSW 第4.2节
在开发查询上选择建库与查询参数,再测留出的召回、延迟、内存和更新成本。检查聚簇数据、重复点、插入顺序和分布漂移。提高 ef 是在已有图中投入更多努力,不会重建缺失的有用连接。保留建索引时使用的向量版本与距离约定。
跟着队列,也跟着边
- M=4且不封顶时,预期多少比例的节点到达第2层?
答案:4⁻²=1/16。120个节点的预期数量为7.5,但一次随机构造不必等于期望;本种子得到13个。
- 120向量索引中,ef=120为什么可能计算超过120次距离?
答案:ef限制某一层保留的结果集合。上层路由也算距离,同一点到下层还可能重算。本例跨全部查询层的平均数为134.7。
- 查询[0,0],候选[1,0]、[1.1,0]、[0,2],容量二。启发式与直接选最近两个有何不同?
答案:先保留[1,0]。[1.1,0]离已选邻居比离查询更近,暂时推迟;[0,2]提供不同方向,被接受。直接最近两个则都落在水平正轴上。
- ef很大就保证精确吗?设计能暴露问题的测试。
答案:不能。不可达连通部分无法访问,提前停止也不是全局下界。应在刻意构造的簇和插入顺序上对照穷举、检查可达性,把建图参数与查询 ef 分开改变。
伪代码版本和选项都要写清
v4 算法暴露了“图加贪心搜索”这种简述掩盖的选择:入口替换、建图搜索宽度、结果堆边界、邻居多样化与剪枝。本例层数上限、确定性同分规则、有限输入限制和未做的更新功能均已声明。程序展示真实增量构图和查询,没有复现论文性能基准,也不是完整向量数据库。
先判断,再看解释
ef=30就意味着恰好计算30次距离吗?
学习目标
- 跟踪插入、邻居多样化、分层搜索以及不同建库/查询预算。
- 运行原创示例,定位近似误差。
先修与延伸
查看知识关联图 →参考文献
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs — arXiv v4
Yu. A. Malkov; D. A. Yashunin · 2018 - hnswlib README — commit d9b3608c83d83b46c96e25088cb1d729b29dcfe9
nmslib/hnswlib contributors
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. Viewed physical PDF4/5/7: algorithms1–5, level sampling, neighbor heuristic, construction/search parameters and conditional complexity discussion. v1 PDF5 separately compared; implementation follows v4 with declared limits. Read opening25 lines and init_index/set_ef/knn_query excerpts; build versus query controls and filtering behavior. License first8 lines identify Apache2.0; no upstream code copied or run. 6 paired equations and four explained exercises. Checked real incremental hierarchy, layer membership and degrees, diversified neighbor selection, complete small graph against exhaustive search, duplicate ties and query distance calls.
- 核真实增量层级、成员及出度、多样邻居、完整小图对照穷举、重复同分及查询距离调用。
- 每题四张计算SVG,9数值/几何与24响应式组合通过;实看8张最终图,完整页面验收另记。
核对的来源位置:
- Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs — arXiv v4 · Viewed physical PDF4/5/7: algorithms1–5, level sampling, neighbor heuristic, construction/search parameters and conditional complexity discussion. v1 PDF5 separately compared; implementation follows v4 with declared limits.
- hnswlib README — commit d9b3608c83d83b46c96e25088cb1d729b29dcfe9 · Read opening25 lines and init_index/set_ef/knn_query excerpts; build versus query controls and filtering behavior. License first8 lines identify Apache2.0; no upstream code copied or run.
相关主题