07. HNSW: Hierarchical Navigable Small World
Chapter 7 of 18 · 20 min
HNSW is a graph-based ANN method that builds a multi-layer structure where upper layers enable fast skipping to the right region, and lower layers refine the search.
EXERCISE
Build a 2D visualization of an HNSW graph. Plot nodes, color by layer, draw edges. Observe how upper layers have sparser connectivity and longer edges.
import matplotlib.pyplot as plt
import numpy as np
def visualize_hnsw(hnsw):
"""Visualize HNSW structure in 2D."""
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for ax, layer in zip(axes, [0, 1, 2]):
positions = []
for node in hnsw.nodes.values():
if layer in node.neighbors:
pos = node.vector[:2] # First 2 dimensions
positions.append(pos)
for neighbor_id in node.neighbors[layer]:
neighbor = hnsw.nodes[neighbor_id]
ax.plot([pos[0], neighbor.vector[0]],
[pos[1], neighbor.vector[1]],
alpha=0.1, color='gray')
positions = np.array(positions)
ax.scatter(positions[:, 0], positions[:, 1], s=10)
ax.set_title(f'Layer {layer}')
plt.show()
# Generate test data
vectors = np.random.randn(500, 128).astype('float32')
hnsw = HNSW(m=8)
hnsw.add(vectors)
visualize_hnsw(hnsw)