Exact vector search and locality-sensitive hashing
Implement exact blocked nearest-neighbor search, reduce maximum inner product to nearest-neighbor search, and study locality-sensitive hashing, SimHash collision probability, band amplification, and approximate-neighbor guarantees.
After this lesson you can
- Implement blocked exact top-k with partial selection and measure its cost on CPU and local GPU.
- Reduce maximum inner-product search to nearest-neighbor search through a vector transformation.
- Prove SimHash collision probability is 1 − θ/π.
- Design band and table amplification for a similarity threshold and measure recall versus candidates examined.
- State the (c, r) approximate-neighbor problem and LSH sublinear guarantees.
Before you start
- 23Dense retrievalEmbedding pooling and normalizationRanking metrics
- 04Johnson-Lindenstrauss lemmaConcentration of the normNear-orthogonality in high dimensions
- 11k-nearest neighborsKD-trees and ball treesCurse of dimensionality
- 08Universal hashingQuickselectLas Vegas and Monte Carlo algorithms
- 02Dot productVector normCauchy-Schwarz inequality
- 09Memory hierarchyGPU memory hierarchyLoop tiling (blocking)
- 20LSH bandingMinHash
Searching among vectors
The dense retriever turns a query and many passages into vectors. We must locate the best without storing a score matrix for every query against every document. One million float32 vectors of dimension 768 occupy 3.072 billion bytes before metadata or index. Exact search fitting in memory does not imply it meets a response deadline: measure batching, transfers, and concurrency on the specific hardware and corpus.
Exact nearest-neighbor search computes every score and returns the top . With queries and documents of dimension , matrix multiplication costs on the order of . Instead of forming a full matrix, divide documents into blocks of : compute , retain the block’s top , and merge with previous best candidates. Peak score storage falls from to , in addition to vectors and results.
If a document is outside its own block’s top-k, at least documents in that block precede it, so it cannot enter the global top-k. This requires the same tie rule at both stages. Use partial selection, such as argpartition, and sort the selected; full argsort pays to sort candidates later discarded. A GPU executes multiplication and selection in parallel, but memory movement, batch size, and synchronization matter. An honest comparison includes warm-up and synchronization before reading the clock.
For unit vectors, normalization makes cosine, inner product, and Euclidean distance equivalent. Without it, maximizing inner product differs from maximizing cosine: a long vector can win even with a less similar direction.
Converting MIPS to distance
The maximum-inner-product to nearest-neighbor reduction adds a coordinate to each document whose norm satisfies . For query , define
Then all lifted documents have norm and
The first two terms do not depend on the document. Thus ascending distance order is exactly descending inner-product order, with the same ties. If a vector with norm greater than appears, the root is no longer real: update the bound and rebuild the transformation. Query and document are transformed differently, making the reduction asymmetric. This differs from normalizing every document, which would change MIPS. Shrivastava and Li study asymmetric families for approximate MIPS; this lift is a geometric identity for exact ordering.
The example has three explicit two-dimensional documents and . Lines are parallels of the hemisphere, not observations. The augmented query is at ; it is not lifted to the same sphere. Controls compute product and distance with the formula above.
Hyperplanes and collisions
KD trees and ball trees exploit regions to discard points, but in high dimensions many regions may intersect the search radius. The curse of dimensionality explains why pruning can lose effectiveness; it does not say all 768-dimensional datasets necessarily behave alike. Distribution and intrinsic dimension matter. High-dimensional concentration and near orthogonality help explain the difficulty.
An LSH family is -sensitive, for and , if points at distance at most collide with probability at least and points farther than collide with probability at most . This is a probabilistic property of the family relative to the chosen metric. It promises neither that every close pair collides nor that every collision is close.
SimHash chooses an isotropic Gaussian normal and assigns bit to each nonzero vector. For two vectors at angle ,
The proof is geometric. By isotropy, the direction of the normal’s projection onto the plane spanned by both vectors is uniform on the circle. The line perpendicular to that direction separates vectors on exactly two arcs of angular length out of . Separation probability is . Collinear vectors give the same formula at the endpoints. Exactly zero inner product has probability zero for nonzero vectors and a continuous normal. This angular similarity family appears in Charikar.
The lines are a deterministic seeded sequence with uniform directions: the finite fraction fluctuates and is not the exact probability. SimHash depends on angle, not norm. Applying it directly to unnormalized MIPS changes the question.
For distance there are other families. In the scheme of Datar and colleagues, project onto a Gaussian direction and use shifted intervals: , with shift uniform on . Shared-interval probability depends on projected distance and . The angular family and this family have different collision formulas.
Amplifying the difference
LSH amplification concatenates independent bits into a band and builds independent tables. If a pair collides on one bit with probability , it matches one band with probability ; it becomes a candidate if it matches any table:
This formula requires independent bits and tables. More bits reduce false collisions per table but can lose neighbors; more tables restore opportunities at the cost of storage and work. Approximate threshold corresponds approximately to probability , not exactly 0.5. The exact 0.5 threshold is . For SimHash use , not cosine directly.
Tables store signatures and document references, not just bits per signature. After collecting and deduplicating candidates, recompute exact scores. Recall against exact top-k and candidate count are both needed to assess the tradeoff; high recall that inspects nearly the full corpus may not save work.
Approximation guarantee and scope
In the approximate-neighbor problem, if a point exists at distance at most , the algorithm must return, with fixed success probability, one at distance at most . Outside that promise no answer is required. This guarantee differs from empirical recall@k or finding the exact neighbor.
In the classical analysis, with , points, and independent tables, choosing approximately functions per key makes each far point reach a table with probability on the order of . With on the order of tables, where
a near neighbor has constant probability of appearing and expected far collisions are on the order of . Typical reference space may grow as , excluding dimensional, construction, and logarithmic costs. The guarantee depends on the family, assumptions, and tables; it is not a promise of sublinear latency for every corpus. Randomized algorithm concepts distinguish success probability from cost.
Practice requires measuring hardware, precision, distribution, and updates. A graph index may be competitive, but there is no universal winner without fixing recall, memory, and load. The next lesson studies other structures.
Browser lab: exact search and LSH
Generate 100000 unit vectors of dimension 16 in synthetic clusters, four queries, and a fixed seed. This is a test model, not real embeddings or a production performance measurement. Exact search divides the collection into blocks and retains candidates by partial selection. The full score matrix appears only when checking this small example.
import numpy as np
rng = np.random.default_rng(18)
n, dim, k = 100_000, 16, 10
centers = rng.normal(size=(128, dim)).astype(np.float32)
centers /= np.linalg.norm(centers, axis=1, keepdims=True)
X = centers[rng.integers(0, len(centers), n)] + 0.25 * rng.normal(size=(n, dim)).astype(np.float32)
X /= np.linalg.norm(X, axis=1, keepdims=True)
Q = centers[:4] + 0.1 * rng.normal(size=(4, dim)).astype(np.float32)
Q /= np.linalg.norm(Q, axis=1, keepdims=True)
def topk_blocked(Q, X, k, block=10_000):
scores = np.empty((len(Q), 0), dtype=np.float32)
ids = np.empty((len(Q), 0), dtype=np.int64)
for start in range(0, len(X), block):
batch = Q @ X[start:start+block].T
indices = np.broadcast_to(np.arange(start, start+batch.shape[1]), batch.shape)
scores = np.concatenate((scores, batch), axis=1)
ids = np.concatenate((ids, indices), axis=1)
take = min(k, scores.shape[1])
part = np.argpartition(-scores, take-1, axis=1)[:, :take]
scores = np.take_along_axis(scores, part, axis=1)
ids = np.take_along_axis(ids, part, axis=1)
order = np.argsort(-scores, axis=1, kind="stable")
return np.take_along_axis(ids, order, axis=1), np.take_along_axis(scores, order, axis=1)
exact, exact_scores = topk_blocked(Q, X, k)
direct = Q @ X.T
truth = np.argsort(-direct, axis=1, kind="stable")[:, :k]
assert all(set(a)==set(b) for a,b in zip(exact,truth))
print("vectores bytes:", X.nbytes, "top-k exacto primera consulta:", exact[0])The code above does not guarantee identifier tie-breaking at the partial-selection boundary. This continuous corpus makes exact ties unlikely; if the protocol requires deterministic identifiers, resolve boundary ties explicitly as in the exercise. Saving top-k per block does not reduce the cost of every product: it reduces peak memory.
Each following table uses eight independent hyperplanes. Document keys are sorted once; the query binary-searches each key, gathers candidates, and reranks them by exact cosine. Two tables are built per cell to keep each browser step bounded.
bits, tables = 8, []
def add_tables(count):
for _ in range(count):
planes = rng.normal(size=(dim, bits)).astype(np.float32)
weights = (1 << np.arange(bits)).astype(np.uint16)
codes = ((X @ planes >= 0) * weights).sum(axis=1).astype(np.uint16)
order = np.argsort(codes, kind="stable")
tables.append((planes, codes[order], order))
add_tables(2)
print("tablas:", len(tables))add_tables(2)
print("tablas:", len(tables), "bytes de códigos e índices:",
sum(c.nbytes+i.nbytes for _,c,i in tables))def candidates(q, use_tables):
found = set()
weights = (1 << np.arange(bits)).astype(np.uint16)
for planes, codes, order in tables[:use_tables]:
key = int(((q @ planes >= 0) * weights).sum())
lo, hi = np.searchsorted(codes, [key, key+1])
found.update(order[lo:hi].tolist())
return np.array(sorted(found), dtype=np.int64)
for b in (1, 2, 4):
recalls, sizes = [], []
for qi, q in enumerate(Q):
cand = candidates(q, b)
ranks = cand[np.argsort(-(X[cand] @ q), kind="stable")[:k]]
recalls.append(len(set(ranks) & set(exact[qi])) / k)
sizes.append(len(cand))
print("tablas:", b, "recall@10:", np.mean(recalls), "candidatos medios:", np.mean(sizes))Printed memory sums sorted codes and table document indices, excluding hyperplanes, the original array, and temporary structures. Results depend on seed, cluster concentration, and queries. A vector missing from all buckets cannot reappear during reranking; a false positive can be discarded.
theta = np.pi / 3
u = np.array([1., 0.])
v = np.array([np.cos(theta), np.sin(theta)])
planes = rng.normal(size=(50_000, 2))
observed = np.mean((planes @ u >= 0) == (planes @ v >= 0))
print("colisión observada:", observed, "teoría:", 1-theta/np.pi)Local lab: real vectors at scale
The previous module’s corpus does not contain one million passages. This comparison therefore uses the public Cohere-1M Wikipedia dataset: one million real normalized 768-dimensional embeddings and separate queries. It is an external corpus, not E5 output or output from the previous lab. The cell downloads approximately 3.1 GB of vectors and requires local Python with NumPy, PyTorch, FAISS CPU, and huggingface_hub. It is excluded from automated testing because it downloads and indexes one million vectors; quick=True uses 10000 and four queries to check the flow.
Exact IndexFlatIP is built on CPU; torch computes blocked inner products on GPU and includes CPU-to-GPU copying in time. IndexLSH searches binary codes, returns 100 candidates, and reranks them by exact product. IndexLSH examines binary codes and does not implement the previous cell’s tables, so 100 is the number reranked, not the number of codes examined. Each search is warmed up and CUDA synchronized before stopping the clock. QPS values are observations from that run: batch size, memory, load, and transfers change the comparison.
import time
import numpy as np
import torch
import faiss
from huggingface_hub import hf_hub_download
quick = False # True: 10 000 documentos y 4 consultas
repo = 'YoKONCy/Cohere-1M-wikipedia-768d'
revision = '25ad59fd88a30aec3370cbc4c46dcbfc1e19591f'
base_path = hf_hub_download(repo, 'cohere_train.f32', repo_type='dataset', revision=revision)
query_path = hf_hub_download(repo, 'cohere_test.f32', repo_type='dataset', revision=revision)
base = np.memmap(base_path,dtype=np.float32,mode='r').reshape(-1,768)
queries = np.memmap(query_path,dtype=np.float32,mode='r').reshape(-1,768)
n = 10000 if quick else 1_000_000
X = np.ascontiguousarray(base[:n])
Q = np.array(queries[:4 if quick else 16], copy=True, order='C')
print('shape', X.shape, Q.shape, 'bytes', X.nbytes, flush=True)
k = 10
start = time.perf_counter()
exact = faiss.IndexFlatIP(X.shape[1]); exact.add(X)
print('Flat build seconds',time.perf_counter()-start, flush=True)
exact.search(Q[:1],k)
start=time.perf_counter(); scores, truth=exact.search(Q,k); tflat=time.perf_counter()-start
print('Flat QPS', len(Q)/tflat, flush=True)
if torch.cuda.is_available():
device=torch.device('cuda')
def gpu_blocked():
qt=torch.from_numpy(Q).to(device)
best=torch.empty((len(Q),0),device=device)
ids=torch.empty((len(Q),0),device=device,dtype=torch.long)
for start in range(0,len(X),16000):
chunk=torch.from_numpy(np.array(X[start:start+16000], copy=True)).to(device)
s=qt @ chunk.T
ix=torch.arange(start,start+len(chunk),device=device).expand(len(Q),-1)
vals=torch.cat((best,s),dim=1); js=torch.cat((ids,ix),dim=1)
best, which=torch.topk(vals,min(k,vals.shape[1]),dim=1)
ids=torch.gather(js,1,which)
return best.cpu().numpy(),ids.cpu().numpy()
gpu_blocked(); torch.cuda.synchronize()
start=time.perf_counter(); gs,gi=gpu_blocked(); torch.cuda.synchronize(); tgpu=time.perf_counter()-start
assert np.allclose(gs,scores,rtol=2e-4,atol=2e-4)
print('torch GPU with transfers QPS',len(Q)/tgpu,'mean overlap',np.mean([len(set(a)&set(b))/k for a,b in zip(gi,truth)]), flush=True)
else:
print('no CUDA, GPU measurement skipped', flush=True)
start=time.perf_counter()
approx=faiss.IndexLSH(X.shape[1],64); approx.train(X); approx.add(X)
print('IndexLSH build seconds',time.perf_counter()-start,flush=True)
approx.search(Q[:1],100)
start=time.perf_counter(); _, candidates=approx.search(Q,100)
reranked=[]
for q, candidates_i in zip(Q,candidates):
ids=candidates_i[candidates_i>=0]
order=np.argsort(-(X[ids] @ q),kind='stable')[:k]
reranked.append(ids[order])
elapsed=time.perf_counter()-start
recall=np.mean([len(set(a)&set(b))/k for a,b in zip(reranked,truth)])
print('IndexLSH + rerank QPS',len(Q)/elapsed,'recall@10',recall,'reranked per query',len(candidates[0]), flush=True)
print('IndexLSH scans binary codes; it is not the hash-table LSH from the browser lab.',flush=True)npm run lab and open the connection link.The indexes have different objectives: FlatIP is an exact reference, while IndexLSH approximates and must report recall. Do not interpret one result as a universal size threshold: test different sizes, batches, bit counts, memory, and recall targets. Synchronization and inclusion or exclusion of transfers should match the deployment conditions being studied.
To decide where exact search stops sufficing for your system, repeat with 10000, 100000, and 1000000 documents by changing n, then repeat batches and runs. If you need one query every 50 ms, 20 queries per second is a sustained-capacity condition but does not guarantee a latency percentile below 50 ms. Also measure individual latency under expected concurrency and set a recall target before choosing an approximate index. The first size violating any constraint under that load is your crossover point, not a technique constant.
In one verification run with the full million and 16 queries, FAISS CPU 1.16.0 and torch on GPU agreed on all ten neighbors per query. IndexLSH with 64 bits and exact reranking of 100 candidates achieved mean recall@10 of 0.03125 on those 16 queries. This is not a general LSH property or memory- or quality-matched comparison: it shows that in this configuration reranking cannot recover neighbors the first stage never proposes. Times vary with shared hardware and batch sizes; the cell measures them again in your environment.
Exercises
Step 1 of 3. Which part of the normal determines the signs?
Step 1 of 3. What norm does each lifted document have?
import numpy as np
def topk_blocked(Q, X, k, block):
pass