Proximity graphs: NSW, HNSW and production vector search
Study greedy proximity-graph search, HNSW hierarchy and diversity pruning, DiskANN, filters, deletions and updates. Implement HNSW, compare with exact search and libraries, and apply ANN benchmarking with recall, memory and latency tradeoffs.
After this lesson you can
- Implement greedy search with an ef-sized candidate list and HNSW insertion with geometric level sampling.
- Prove greedy search on a Delaunay graph reaches the exact neighbor and explain practical diversity pruning.
- Tune M, efConstruction and efSearch and measure recall, latency, memory and build time.
- Compare prefiltering, postfiltering and traversal-time filtering by selectivity.
- Design and run an index benchmark with exact ground truth, configurations and Pareto frontiers.
Before you start
- 23Exact nearest-neighbor searchApproximate nearest-neighbor guaranteesInverted file indexIVF-PQ with residual encoding and re-rankingProduct quantization
- 08Priority queue ADTBinary heapVoronoi diagrams and Delaunay triangulation
- 10Greedy best-first search
- 01Graph basicsPaths and connectivity
- 04Bernoulli-trial distributionsMemoryless property
Traversing a neighbor graph
A proximity index represents each vector as a node and stores links to other vectors. A query starts at an entry node, calculates distances to neighbors and advances toward promising candidates. Proximity-graph search avoids necessarily examining the entire collection, but graph structure determines which regions it can reach.
In strictly greedy search, traversal stops when no neighbor is closer to the query. That local minimum need not be the global neighbor. A candidate priority queue allows alternatives to be explored: ef limits how many promising results are retained, while the visited set avoids repeated calculations. It is not an exact limit on distances computed.
In the Euclidean Delaunay graph of distinct points in general position, with ties treated consistently, strictly greedy search does reach an exact neighbor. If the current node is not nearest, the query is outside its Voronoi cell. The segment from node to query exits through a boundary shared with another cell; that cell’s site is closer to the query. Each step strictly decreases distance and there are finitely many nodes. Degeneracies and ties require specifying cell representation and tie-breaking. Practical pruned, degree-limited graphs do not automatically inherit this guarantee.
A hierarchy of small worlds
NSW inserts points into a navigable graph; some long edges enable jumps, but distribution and insertion order matter. HNSW separates scales through nested levels: every point appears in the base layer and reaches higher levels with decreasing probability. A common choice satisfies . Enter at the top layer, search with small breadth and descend to the base, where efSearch is used.
The example incrementally builds an index on 90 explicit seed-generated points. Changing M rebuilds the graph; changing ef modifies only search. Stored edges can be directed after pruning. Sublinear or approximately logarithmic cost observed on some datasets is empirical and depends on data and parameters, not a general guarantee for every dimension or distribution. See the original HNSW paper.
M approximately controls degree and link memory; efConstruction provides more candidates during construction and usually increases time and graph quality. efSearch can be adjusted without rebuilding. To request results, use at least ; libraries may adjust or reject smaller values differently. Storing full vectors plus links, levels, identifiers and metadata costs more than vectors alone.
Preserving diversity
Diversity-based neighbor pruning traverses candidates by distance to the node and discards one when a previously chosen neighbor covers it: for example, if the candidate is closer to that neighbor than to the source node. This avoids dedicating all links to one direction. It does not guarantee always retaining a long edge or that the resulting graph is navigable.
The figure uses the same points and compares six nearest edges with selection from 30 candidates; traversal always starts at the same node. In the Vamana-inspired rule, candidate is discarded by an already chosen if , with . Increasing alpha makes a candidate harder to discard; a degree limit still restricts the result. This local demonstration does not reproduce every Vamana construction phase. The DiskANN paper describes its construction.
Disk, filters and changes
DiskANN combines a bounded-degree graph on SSD with compressed RAM representations to guide traversal. Latency depends on reads, page size, concurrency and cache as well as the number of distances. The original work reports measurements for a particular configuration and dataset; its performance should not be transferred without repeating the experiment.
In filtered search, exact ground truth is defined among allowed documents, not the entire collection. Exact prefiltering can be efficient for a small subset. Postfiltering searches first and discards afterward; if few candidates are examined it can return fewer than . Traversal-time filtering can pass through excluded nodes to preserve connectivity but accepts only allowed results. A geometry-correlated filter can behave differently from a scattered label.
Tombstone deletions retain links to traverse obsolete nodes, but increase work and memory until compaction or rebuilding. Removing edges immediately can break connectivity; if vectors change, links can become stale. Concurrency guarantees for inserts, searches and deletions depend on the library and must be checked for the version used. Monitor recall, latency and live population against an exact-ground-truth sample before deciding when to rebuild.
Comparable measurement
An ANN benchmark must fix distance, query set, exact ground truth, , item exclusions and software version. Sweep parameters, warm up paths, measure building and search separately, and report threads, batch and hardware. Compare speed at similar recall and do not interpret one shared-load run as a latency distribution. The ANN-Benchmarks methodology systematizes these comparisons.
For small collections, measuring exact CPU or GPU search can avoid index cost and complexity; no universal size threshold exists. A GPU can favor batches, and transfer cost matters. Choice depends on dimension, concurrency, memory, filters and latency target.
Browser laboratory: HNSW from scratch
The following educational model uses squared Euclidean distance, an incremental hierarchy, two heaps and diversity selection. It does not reproduce all optimizations or guarantees of a production library. The browser generates 10000 synthetic 16-dimensional vectors and 20 queries; ground truth is calculated by brute force. Run cells in order: each block adds 500 vectors to the same index. For the kNN graph, 200 rows are calculated at a time within one cell. Partitioning preserves the same state and insertion order; each cell keeps the browser interface responsive.
import heapq, math, time
import numpy as np
def distance(a,b):
diff=a-b
return float(diff@diff)
def search_layer(q, entries, ef, graph, vectors, allowed=None):
"""El filtro afecta a los resultados, no a los nodos que se pueden atravesar."""
visited=set(entries)
candidates=[]
best=[]
for i in entries:
d=distance(q,vectors[i])
heapq.heappush(candidates,(d,i))
if allowed is None or allowed[i]: heapq.heappush(best,(-d,-i))
while len(best)>ef: heapq.heappop(best)
while candidates:
d,i=heapq.heappop(candidates)
if len(best)>=ef and d > -best[0][0]:
break
for j in graph[i]:
if j in visited: continue
visited.add(j)
dj=distance(q,vectors[j])
if len(best)<ef or (dj,j)<(-best[0][0],-best[0][1]):
heapq.heappush(candidates,(dj,j))
if allowed is None or allowed[j]:
heapq.heappush(best,(-dj,-j))
if len(best)>ef: heapq.heappop(best)
ranked=sorted((-d,-i) for d,i in best)
return [i for _,i in ranked], len(visited)
def diversify(q, candidates, vectors, limit):
chosen=[]
for i in sorted(set(candidates),key=lambda i:(distance(q,vectors[i]),i)):
if all(distance(vectors[i],vectors[j]) >= distance(q,vectors[i]) for j in chosen):
chosen.append(i)
if len(chosen)==limit: break
return chosen
class HNSW:
def __init__(self,M=8,ef_construction=32,seed=20):
self.M=M; self.ef_construction=ef_construction
self.rng=np.random.default_rng(seed)
self.vectors=[]; self.layers=[]; self.entry=None; self.maxlevel=-1
def add(self,v):
idx=len(self.vectors); self.vectors.append(v)
level=int(-math.log(max(float(self.rng.random()),1e-15))/math.log(self.M))
while len(self.layers)<=level: self.layers.append({})
for layer in range(level+1): self.layers[layer][idx]=[]
if self.entry is None:
self.entry=idx; self.maxlevel=level; return
ep=self.entry
for layer in range(self.maxlevel,level,-1):
ep=search_layer(v,[ep],1,self.layers[layer],self.vectors)[0][0]
for layer in range(min(level,self.maxlevel),-1,-1):
ids,_=search_layer(v,[ep],self.ef_construction,self.layers[layer],self.vectors)
limit=2*self.M if layer==0 else self.M
selected=diversify(v,ids,self.vectors,limit)
self.layers[layer][idx]=selected
for neighbor in selected:
graph=self.layers[layer]
graph[neighbor].append(idx)
if len(graph[neighbor])>limit:
graph[neighbor]=diversify(self.vectors[neighbor],graph[neighbor],self.vectors,limit)
if ids: ep=ids[0]
if level>self.maxlevel: self.entry=idx; self.maxlevel=level
def search(self,q,k,ef=40,allowed=None):
if ef<k: raise ValueError('ef debe ser al menos k')
ep=self.entry; count=0
for layer in range(self.maxlevel,0,-1):
ids,n=search_layer(q,[ep],1,self.layers[layer],self.vectors)
ep=ids[0];count+=n
ids,n=search_layer(q,[ep],ef,self.layers[0],self.vectors,allowed)
return ids[:k],count+nrng=np.random.default_rng(20)
X=rng.normal(size=(10000,16)).astype(np.float32)
Q=rng.normal(size=(20,16)).astype(np.float32)
truth=np.argsort(((Q[:,None,:]-X[None,:,:])**2).sum(2),axis=1)[:,:10]
index=HNSW(M=8,ef_construction=32,seed=20)assert len(index.vectors)==0, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 0"
for x in X[0:500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 500"
for x in X[500:1000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==1000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 1000"
for x in X[1000:1500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==1500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 1500"
for x in X[1500:2000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==2000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 2000"
for x in X[2000:2500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==2500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 2500"
for x in X[2500:3000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==3000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 3000"
for x in X[3000:3500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==3500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 3500"
for x in X[3500:4000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==4000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 4000"
for x in X[4000:4500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==4500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 4500"
for x in X[4500:5000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==5000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 5000"
for x in X[5000:5500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==5500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 5500"
for x in X[5500:6000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==6000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 6000"
for x in X[6000:6500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==6500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 6500"
for x in X[6500:7000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==7000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 7000"
for x in X[7000:7500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==7500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 7500"
for x in X[7500:8000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==8000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 8000"
for x in X[8000:8500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==8500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 8500"
for x in X[8500:9000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==9000, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 9000"
for x in X[9000:9500]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==9500, f"Ejecuta los bloques en orden: hay {len(index.vectors)} vectores, se esperan 9500"
for x in X[9500:10000]: index.add(x)
print('insertados',len(index.vectors))assert len(index.vectors)==10000
print('niveles',index.maxlevel+1)
for ef in (10,40,100):
result=[index.search(q,10,ef) for q in Q]
recall=np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(result,truth)])
print('ef',ef,'recall@10',recall,'distancias medias por capa',np.mean([n for _,n in result]))Distance count sums visits per layer, so a node evaluated at two levels is counted twice. To compare with a directed graph of eight exact neighbors without pruning, its rows are calculated in blocks. The quadratic comparison is educational, not a large-scale indexing strategy. The cell processes groups of 200 rows to avoid materializing the entire distance matrix at once.
graph=[]
norm=(X*X).sum(1)
def add_knn_block(start, stop):
block=X[start:stop]
ds=np.maximum(0,(block*block).sum(1)[:,None]+norm[None,:]-2*[email protected])
for row in range(len(block)):
ds[row,start+row]=np.inf
graph.append(np.argpartition(ds[row],8)[:8].tolist())assert len(graph)==0, "Prepara el grafo antes de construirlo"
for start in range(0,len(X),200):
add_knn_block(start,min(start+200,len(X)))
print('filas',len(graph))assert len(graph)==10000
out=[search_layer(q,[0],40,graph,X) for q in Q]
print('kNN dirigido recall@10',np.mean([len(set(ids[:10])&set(t))/10 for (ids,_),t in zip(out,truth)]),
'distancias medias',np.mean([count for _,count in out]))Full local experiment: 10000 vectors
This version reproduces construction and comparison with a kNN graph on the 10000 synthetic vectors in the design. Browser cells use the same scale and partition graph inserts and rows to keep each execution responsive. In the 10000-vector run, custom HNSW achieved recall@10 0.635, 0.915 and 0.985 for ef 10, 40 and 100; the directed kNN graph at ef 40 achieved 0.69. These are results from 20 queries, not a general guarantee. The local cell is omitted from automatic tests due to cost, but was run to verify those values.
import heapq, math, time
import numpy as np
def distance(a,b):
diff=a-b
return float(diff@diff)
def search_layer(q, entries, ef, graph, vectors, allowed=None):
"""El filtro afecta a los resultados, no a los nodos que se pueden atravesar."""
visited=set(entries)
candidates=[]
best=[]
for i in entries:
d=distance(q,vectors[i])
heapq.heappush(candidates,(d,i))
if allowed is None or allowed[i]: heapq.heappush(best,(-d,-i))
while len(best)>ef: heapq.heappop(best)
while candidates:
d,i=heapq.heappop(candidates)
if len(best)>=ef and d > -best[0][0]:
break
for j in graph[i]:
if j in visited: continue
visited.add(j)
dj=distance(q,vectors[j])
if len(best)<ef or (dj,j)<(-best[0][0],-best[0][1]):
heapq.heappush(candidates,(dj,j))
if allowed is None or allowed[j]:
heapq.heappush(best,(-dj,-j))
if len(best)>ef: heapq.heappop(best)
ranked=sorted((-d,-i) for d,i in best)
return [i for _,i in ranked], len(visited)
def diversify(q, candidates, vectors, limit):
chosen=[]
for i in sorted(set(candidates),key=lambda i:(distance(q,vectors[i]),i)):
if all(distance(vectors[i],vectors[j]) >= distance(q,vectors[i]) for j in chosen):
chosen.append(i)
if len(chosen)==limit: break
return chosen
class HNSW:
def __init__(self,M=8,ef_construction=32,seed=20):
self.M=M; self.ef_construction=ef_construction
self.rng=np.random.default_rng(seed)
self.vectors=[]; self.layers=[]; self.entry=None; self.maxlevel=-1
def add(self,v):
idx=len(self.vectors); self.vectors.append(v)
level=int(-math.log(max(float(self.rng.random()),1e-15))/math.log(self.M))
while len(self.layers)<=level: self.layers.append({})
for layer in range(level+1): self.layers[layer][idx]=[]
if self.entry is None:
self.entry=idx; self.maxlevel=level; return
ep=self.entry
for layer in range(self.maxlevel,level,-1):
ep=search_layer(v,[ep],1,self.layers[layer],self.vectors)[0][0]
for layer in range(min(level,self.maxlevel),-1,-1):
ids,_=search_layer(v,[ep],self.ef_construction,self.layers[layer],self.vectors)
limit=2*self.M if layer==0 else self.M
selected=diversify(v,ids,self.vectors,limit)
self.layers[layer][idx]=selected
for neighbor in selected:
graph=self.layers[layer]
graph[neighbor].append(idx)
if len(graph[neighbor])>limit:
graph[neighbor]=diversify(self.vectors[neighbor],graph[neighbor],self.vectors,limit)
if ids: ep=ids[0]
if level>self.maxlevel: self.entry=idx; self.maxlevel=level
def search(self,q,k,ef=40,allowed=None):
if ef<k: raise ValueError('ef debe ser al menos k')
ep=self.entry; count=0
for layer in range(self.maxlevel,0,-1):
ids,n=search_layer(q,[ep],1,self.layers[layer],self.vectors)
ep=ids[0];count+=n
ids,n=search_layer(q,[ep],ef,self.layers[0],self.vectors,allowed)
return ids[:k],count+n
rng=np.random.default_rng(20)
X=rng.normal(size=(10000,16)).astype(np.float32)
Q=rng.normal(size=(20,16)).astype(np.float32)
truth=np.argsort(((Q[:,None,:]-X[None,:,:])**2).sum(2),axis=1)[:,:10]
index=HNSW()
start=time.perf_counter()
for x in X: index.add(x)
print('construcción',time.perf_counter()-start,'niveles',index.maxlevel+1,flush=True)
for ef in (10,40,100):
result=[index.search(q,10,ef) for q in Q]
recall=np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(result,truth)])
print('ef',ef,'recall',recall,'distancias',np.mean([n for _,n in result]),flush=True)
graph=[]
norm=(X*X).sum(1)
for start in range(0,len(X),100):
block=X[start:start+100]
ds=np.maximum(0,(block*block).sum(1)[:,None]+norm[None,:]-2*[email protected])
for row in range(len(block)):
ds[row,start+row]=np.inf
candidates=np.argpartition(ds[row],8)[:8]
graph.append(candidates.tolist())
out=[search_layer(q,[0],40,graph,X) for q in Q]
print('kNN dirigido recall@10',np.mean([len(set(ids[:10])&set(t))/10 for (ids,_),t in zip(out,truth)]),
'distancias medias',np.mean([count for _,count in out]))npm run lab and open the connection link.Local laboratories: benchmark and deletions
You need NumPy, PyTorch, FAISS CPU, hnswlib and huggingface_hub; a CUDA GPU is optional. The Cohere-1M Wikipedia dataset contains external precomputed vectors, not the E5-encoded texts from the previous lesson. The experiment uses the first 10000 vectors and 16 queries, L2 distance and the same exact ground truth. The code downloads files with their revision pinned. The full corpus occupies several gigabytes.
The figure sweep used FAISS 1.16.0 and hnswlib 0.8.0, Intel Core i7-12700K CPU and NVIDIA GeForce RTX 3060 GPU. It used 1 and 20 logical CPU threads; 20 corresponds to this machine, not the 24 in the proposed design. One warmup and one timed pass were used; shared load and the batch of 16 queries mean these speeds do not establish a stable comparison. Libraries were measured in separate runs using the same data and protocol. GPU search includes copying the result to CPU, not initial transfer of the entire collection. Serialized size estimates storage, not resident memory or construction peak. Flat build time was not measured. The code is complete but omitted from automatic tests due to download and cost.
import heapq, math, time
import numpy as np
def distance(a,b):
diff=a-b
return float(diff@diff)
def search_layer(q, entries, ef, graph, vectors, allowed=None):
"""El filtro afecta a los resultados, no a los nodos que se pueden atravesar."""
visited=set(entries)
candidates=[]
best=[]
for i in entries:
d=distance(q,vectors[i])
heapq.heappush(candidates,(d,i))
if allowed is None or allowed[i]: heapq.heappush(best,(-d,-i))
while len(best)>ef: heapq.heappop(best)
while candidates:
d,i=heapq.heappop(candidates)
if len(best)>=ef and d > -best[0][0]:
break
for j in graph[i]:
if j in visited: continue
visited.add(j)
dj=distance(q,vectors[j])
if len(best)<ef or (dj,j)<(-best[0][0],-best[0][1]):
heapq.heappush(candidates,(dj,j))
if allowed is None or allowed[j]:
heapq.heappush(best,(-dj,-j))
if len(best)>ef: heapq.heappop(best)
ranked=sorted((-d,-i) for d,i in best)
return [i for _,i in ranked], len(visited)
def diversify(q, candidates, vectors, limit):
chosen=[]
for i in sorted(set(candidates),key=lambda i:(distance(q,vectors[i]),i)):
if all(distance(vectors[i],vectors[j]) >= distance(q,vectors[i]) for j in chosen):
chosen.append(i)
if len(chosen)==limit: break
return chosen
class HNSW:
def __init__(self,M=8,ef_construction=32,seed=20):
self.M=M; self.ef_construction=ef_construction
self.rng=np.random.default_rng(seed)
self.vectors=[]; self.layers=[]; self.entry=None; self.maxlevel=-1
def add(self,v):
idx=len(self.vectors); self.vectors.append(v)
level=int(-math.log(max(float(self.rng.random()),1e-15))/math.log(self.M))
while len(self.layers)<=level: self.layers.append({})
for layer in range(level+1): self.layers[layer][idx]=[]
if self.entry is None:
self.entry=idx; self.maxlevel=level; return
ep=self.entry
for layer in range(self.maxlevel,level,-1):
ep=search_layer(v,[ep],1,self.layers[layer],self.vectors)[0][0]
for layer in range(min(level,self.maxlevel),-1,-1):
ids,_=search_layer(v,[ep],self.ef_construction,self.layers[layer],self.vectors)
limit=2*self.M if layer==0 else self.M
selected=diversify(v,ids,self.vectors,limit)
self.layers[layer][idx]=selected
for neighbor in selected:
graph=self.layers[layer]
graph[neighbor].append(idx)
if len(graph[neighbor])>limit:
graph[neighbor]=diversify(self.vectors[neighbor],graph[neighbor],self.vectors,limit)
if ids: ep=ids[0]
if level>self.maxlevel: self.entry=idx; self.maxlevel=level
def search(self,q,k,ef=40,allowed=None):
if ef<k: raise ValueError('ef debe ser al menos k')
ep=self.entry; count=0
for layer in range(self.maxlevel,0,-1):
ids,n=search_layer(q,[ep],1,self.layers[layer],self.vectors)
ep=ids[0];count+=n
ids,n=search_layer(q,[ep],ef,self.layers[0],self.vectors,allowed)
return ids[:k],count+n
import json, time, tempfile, os, pickle, sys
import numpy as np, faiss, torch
from huggingface_hub import hf_hub_download
import hnswlib
repo='YoKONCy/Cohere-1M-wikipedia-768d';rev='25ad59fd88a30aec3370cbc4c46dcbfc1e19591f'
get=lambda f:hf_hub_download(repo,f,repo_type='dataset',revision=rev)
X=np.array(np.memmap(get('cohere_train.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:10000],copy=True)
Q=np.array(np.memmap(get('cohere_test.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:16],copy=True)
flat=faiss.IndexFlatL2(768);flat.add(X)
_,truth=flat.search(Q,10)
recall=lambda I:float(np.mean([len(set(a)&set(b))/10 for a,b in zip(I,truth)]))
results=[]
def run(name,fn,size,build,threads):
fn(); start=time.perf_counter(); I=fn(); elapsed=time.perf_counter()-start
item={'name':name,'recall':recall(I),'qps':len(Q)/elapsed,'bytes':size,'build':build,'threads':threads}
results.append(item);print(item,flush=True)
def faiss_size(index):
with tempfile.NamedTemporaryFile(suffix='.faiss',delete=False) as f: path=f.name
try: faiss.write_index(index,path);return os.path.getsize(path)
finally: os.unlink(path)
for threads in (1,20):
faiss.omp_set_num_threads(threads)
run('Flat CPU',lambda:flat.search(Q,10)[1],faiss_size(flat),0,threads)
for M in (8,16):
start=time.perf_counter(); idx=faiss.IndexHNSWFlat(768,M);idx.hnsw.efConstruction=80;idx.add(X);build=time.perf_counter()-start
for ef in (20,80):
idx.hnsw.efSearch=ef
run(f'FAISS HNSW M{M} ef{ef}',lambda:idx.search(Q,10)[1],faiss_size(idx),build,threads)
start=time.perf_counter();idx=faiss.index_factory(768,'IVF32,PQ16x4',faiss.METRIC_L2);idx.train(X);idx.add(X);build=time.perf_counter()-start
for nprobe in (1,8,32):
idx.nprobe=nprobe
run(f'IVF32 PQ16x4 nprobe{nprobe}',lambda:idx.search(Q,10)[1],faiss_size(idx),build,threads)
if hnswlib:
for M in (8,16):
start=time.perf_counter();idx=hnswlib.Index(space='l2',dim=768);idx.init_index(max_elements=len(X),ef_construction=80,M=M,random_seed=20);idx.add_items(X,np.arange(len(X)),num_threads=threads);build=time.perf_counter()-start
with tempfile.NamedTemporaryFile(suffix='.hnsw',delete=False) as f: path=f.name
try: idx.save_index(path);size=os.path.getsize(path)
finally: os.unlink(path)
for ef in (20,80):
idx.set_ef(ef)
run(f'hnswlib M{M} ef{ef}',lambda:idx.knn_query(Q,k=10,num_threads=threads)[0],size,build,threads)
if torch.cuda.is_available():
xt=torch.from_numpy(X).cuda();qt=torch.from_numpy(Q).cuda()
def gpu():
distances=torch.cdist(qt,xt).square();ids=distances.topk(10,largest=False).indices
torch.cuda.synchronize()
return ids.cpu().numpy()
run('Flat GPU',gpu,X.nbytes,0,0)
start=time.perf_counter();own=HNSW(M=8,ef_construction=32,seed=20)
for x in X: own.add(x)
build=time.perf_counter()-start
size=len(pickle.dumps(own,protocol=pickle.HIGHEST_PROTOCOL))
for ef in (20,80):
run(f'Propio M8 ef{ef}',lambda:np.array([own.search(q,10,ef)[0] for q in Q]),size,build,1)
print(json.dumps(results,indent=2))npm run lab and open the connection link.The second part rebuilds the custom index with 2000 synthetic vectors and 50 queries. It marks 30% deleted, allows traversal through them and measures recall against live ground truth with several filters; then it builds another graph with only live vectors. It also updates 100 vectors by marking the old version and inserting the new one. The verified run left 1389 live vectors. Without an additional filter, recall@10 was 1.000 before deletion, 0.998 after and 0.998 after rebuilding; mean per-layer distances were 705.56, 895.62 and 632.86. After updating, recall was 0.998 with 924.8 distances and, after rebuilding, 0.996 with 634.78. These are results of this example, not a universal rebuild threshold.
import heapq, math, time
import numpy as np
def distance(a,b):
diff=a-b
return float(diff@diff)
def search_layer(q, entries, ef, graph, vectors, allowed=None):
"""El filtro afecta a los resultados, no a los nodos que se pueden atravesar."""
visited=set(entries)
candidates=[]
best=[]
for i in entries:
d=distance(q,vectors[i])
heapq.heappush(candidates,(d,i))
if allowed is None or allowed[i]: heapq.heappush(best,(-d,-i))
while len(best)>ef: heapq.heappop(best)
while candidates:
d,i=heapq.heappop(candidates)
if len(best)>=ef and d > -best[0][0]:
break
for j in graph[i]:
if j in visited: continue
visited.add(j)
dj=distance(q,vectors[j])
if len(best)<ef or (dj,j)<(-best[0][0],-best[0][1]):
heapq.heappush(candidates,(dj,j))
if allowed is None or allowed[j]:
heapq.heappush(best,(-dj,-j))
if len(best)>ef: heapq.heappop(best)
ranked=sorted((-d,-i) for d,i in best)
return [i for _,i in ranked], len(visited)
def diversify(q, candidates, vectors, limit):
chosen=[]
for i in sorted(set(candidates),key=lambda i:(distance(q,vectors[i]),i)):
if all(distance(vectors[i],vectors[j]) >= distance(q,vectors[i]) for j in chosen):
chosen.append(i)
if len(chosen)==limit: break
return chosen
class HNSW:
def __init__(self,M=8,ef_construction=32,seed=20):
self.M=M; self.ef_construction=ef_construction
self.rng=np.random.default_rng(seed)
self.vectors=[]; self.layers=[]; self.entry=None; self.maxlevel=-1
def add(self,v):
idx=len(self.vectors); self.vectors.append(v)
level=int(-math.log(max(float(self.rng.random()),1e-15))/math.log(self.M))
while len(self.layers)<=level: self.layers.append({})
for layer in range(level+1): self.layers[layer][idx]=[]
if self.entry is None:
self.entry=idx; self.maxlevel=level; return
ep=self.entry
for layer in range(self.maxlevel,level,-1):
ep=search_layer(v,[ep],1,self.layers[layer],self.vectors)[0][0]
for layer in range(min(level,self.maxlevel),-1,-1):
ids,_=search_layer(v,[ep],self.ef_construction,self.layers[layer],self.vectors)
limit=2*self.M if layer==0 else self.M
selected=diversify(v,ids,self.vectors,limit)
self.layers[layer][idx]=selected
for neighbor in selected:
graph=self.layers[layer]
graph[neighbor].append(idx)
if len(graph[neighbor])>limit:
graph[neighbor]=diversify(self.vectors[neighbor],graph[neighbor],self.vectors,limit)
if ids: ep=ids[0]
if level>self.maxlevel: self.entry=idx; self.maxlevel=level
def search(self,q,k,ef=40,allowed=None):
if ef<k: raise ValueError('ef debe ser al menos k')
ep=self.entry; count=0
for layer in range(self.maxlevel,0,-1):
ids,n=search_layer(q,[ep],1,self.layers[layer],self.vectors)
ep=ids[0];count+=n
ids,n=search_layer(q,[ep],ef,self.layers[0],self.vectors,allowed)
return ids[:k],count+n
import numpy as np,time
rng=np.random.default_rng(20)
X=rng.normal(size=(2000,16)).astype(np.float32)
Q=rng.normal(size=(50,16)).astype(np.float32)
idx=HNSW(M=8,ef_construction=32,seed=20)
for x in X: idx.add(x)
marks=rng.random(len(X))>=.3
print('vivos',marks.sum(),flush=True)
def evaluate(index,active,mapping=None,selectivity=1.0):
allowed=active.copy()
if selectivity<1:
allowed &= np.arange(len(active))%int(round(1/selectivity))==0
positions=np.flatnonzero(allowed)
truth=np.argsort(((Q[:,None,:]-np.array(index.vectors)[positions][None,:,:])**2).sum(2),axis=1)[:,:10]
truth=positions[truth]
outcomes=[index.search(q,10,100,allowed) for q in Q]
return (np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(outcomes,truth)]),
np.mean([n for _,n in outcomes]))
for frac in (1,.5,.1):
print('selectividad',frac,'sin borrados',evaluate(idx,np.ones(len(X),dtype=bool),selectivity=frac),
'tras borrar 30%',evaluate(idx,marks,selectivity=frac),flush=True)
new=HNSW(M=8,ef_construction=32,seed=20)
for x in X[marks]:new.add(x)
print('reconstruido',evaluate(new,np.ones(marks.sum(),dtype=bool)),flush=True)
# Actualizar = marcar la versión antigua y agregar la nueva.
updated=np.flatnonzero(marks)[:100]
active=marks.copy()
for i in updated:
active[i]=False
idx.add(X[i]+rng.normal(scale=.2,size=16).astype(np.float32))
active=np.concatenate([active,np.ones(len(updated),dtype=bool)])
print('tras 100 actualizaciones',evaluate(idx,active),flush=True)
renewed=HNSW(M=8,ef_construction=32,seed=20)
for x in np.array(idx.vectors)[active]: renewed.add(x)
print('reconstruido tras actualizar',evaluate(renewed,np.ones(active.sum(),dtype=bool)),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 3. If the current node is not the nearest neighbor, where is the query?
import heapq
import numpy as np
def search_layer(q, entries, ef, graph, vectors):
pass