Module contents
Lesson 18 of 31Advanced 100 min

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

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 kk. With BB queries and NN documents of dimension dd, matrix multiplication costs on the order of BNdBNd. Instead of forming a full B×NB\times N matrix, divide documents into blocks of CC: compute QXbloque⊤QX_{\text{bloque}}\T, retain the block’s top kk, and merge with previous best candidates. Peak score storage falls from BNBN to BCBC, in addition to vectors and results.

If a document is outside its own block’s top-k, at least kk 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 kk 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 x\vb{x} whose norm satisfies ∥x∥2≤M\norm{\vb{x}}_2\le M. For query q\vb{q}, define

P(x)=(x,M2−∥x∥22),Q(q)=(q,0).P(\vb{x})=(\vb{x},\sqrt{M^2-\norm{\vb{x}}_2^2}),\qquad Q(\vb{q})=(\vb{q},0).

Then all lifted documents have norm MM and

∥P(x)−Q(q)∥22=M2+∥q∥22−2q⊤x.\norm{P(\vb{x})-Q(\vb{q})}_2^2 =M^2+\norm{\vb{q}}_2^2-2\vb{q}\T\vb{x}.

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 MM 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.

InteractiveAll documents reach the sphere
  • Lifted documents
  • Augmented query

Documents D1, D2 and D3 have coordinates (1, 0.5), (0.3, 1.4), and (−1, 0.3). All are lifted to norm 2.

30
Maximum productD1: 1.674
Minimum distanceD1: 1.704
Rotate the scene and change query direction. Compare the maximum-product document with the minimum-distance document after lifting.

The example has three explicit two-dimensional documents and M=2M=2. Lines are parallels of the hemisphere, not observations. The augmented query is at z=0z=0; 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 (r,cr,p1,p2)(r,cr,p_1,p_2)-sensitive, for c>1c>1 and p1>p2p_1>p_2, if points at distance at most rr collide with probability at least p1p_1 and points farther than crcr collide with probability at most p2p_2. 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 a\vb{a} and assigns bit ha(x)=1[a⊤x≥0]h_{\vb{a}}(\vb{x})=\ind[\vb{a}\T\vb{x}\ge0] to each nonzero vector. For two vectors at angle θ∈[0,π]\theta\in[0,\pi],

P[ha(u)=ha(v)]=1−θπ.\Pr[h_{\vb{a}}(\vb{u})=h_{\vb{a}}(\vb{v})]=1-\frac{\theta}{\pi}.

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 θ\theta out of 2π2\pi. Separation probability is 2θ/(2π)=θ/π2\theta/(2\pi)=\theta/\pi. 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.

InteractiveRandom hyperplane collisions
  • Same side
  • Separate
60
30
Collisions23 / 30
Observed frequency0.767
Theoretical probability0.667
Increase the number of lines and change the angle. Compare the observed equal-sign fraction with theoretical probability.

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 L2L_2 there are other families. In the scheme of Datar and colleagues, project onto a Gaussian direction and use shifted intervals: h(x)=⌊(a⊤x+b)/w⌋h(\vb{x})=\lfloor(\vb{a}\T\vb{x}+b)/w\rfloor, with shift bb uniform on [0,w)[0,w). Shared-interval probability depends on projected distance and ww. The angular family and this family have different collision formulas.

Amplifying the difference

LSH amplification concatenates rr independent bits into a band and builds bb independent tables. If a pair collides on one bit with probability ss, it matches one band with probability srs^r; it becomes a candidate if it matches any table:

P(candidato)=1−(1−sr)b.\Pr(\text{candidato})=1-(1-s^r)^b.

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 (1/b)1/r(1/b)^{1/r} corresponds approximately to probability 1−e−11-e^{-1}, not exactly 0.5. The exact 0.5 threshold is (1−2−1/b)1/r(1-2^{-1/b})^{1/r}. For SimHash use s=1−arccos⁡(coseno)/πs=1-\arccos(\text{coseno})/\pi, not cosine directly.

InteractiveThe candidate curve

Explicit probabilistic example: 10 pairs with s = 0.9 and 990 with s = 0.6; this is not a latency or corpus measurement.

10
20
Bits per vector, excluding overhead200
Approximate threshold0.741
Exact P = 0.50.713
Expected candidates in example123.1
Adjust r and b. The candidate readout uses a stated illustrative model, not a timing measurement.

Tables store signatures and document references, not just brbr 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 (c,r)(c,r) approximate-neighbor problem, if a point exists at distance at most rr, the algorithm must return, with fixed success probability, one at distance at most crcr. Outside that promise no answer is required. This guarantee differs from empirical recall@k or finding the exact neighbor.

In the classical analysis, with 0<p2<p1<10<p_2<p_1<1, nn points, and independent tables, choosing approximately k=log⁡n/log⁡(1/p2)k=\log n/\log(1/p_2) functions per key makes each far point reach a table with probability on the order of 1/n1/n. With LL on the order of nρn^\rho tables, where

ρ=log⁡(1/p1)log⁡(1/p2)<1,\rho=\frac{\log(1/p_1)}{\log(1/p_2)}<1,

a near neighbor has constant probability of appearing and expected far collisions are on the order of nρn^\rho. Typical reference space may grow as n1+ρn^{1+\rho}, 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.

[ ]Data and blocked searchBrowser
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.

[ ]First SimHash tablesBrowser
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))
[ ]Complete the tablesBrowser
add_tables(2)
print("tablas:", len(tables), "bytes de códigos e índices:",
      sum(c.nbytes+i.nbytes for _,c,i in tables))
[ ]Recall and candidatesBrowser
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.

[ ]Check angular probabilityBrowser
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.

[ ]FlatIP, torch, and IndexLSH with real vectorsLocal GPU
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)
This cell needs the local lab (PyTorch with your GPU). Start it with 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

ProofSeparation probability
Prove: A hyperplane with an isotropic Gaussian normal separates two nonzero vectors at angle θ with probability θ/π.
0
First suppose the vectors are not collinear.

Step 1 of 3. Which part of the normal determines the signs?

ProofThe additional coordinate
Prove: Under norm bound M, the lifted Euclidean neighbor maximizes the original inner product.
0
The document receives the positive square root and the query a zero coordinate.

Step 1 of 3. What norm does each lifted document have?

NumericBands for 30 degrees
With 10 bits per band and 20 independent SimHash tables, calculate candidate probability for vectors separated by 30 degrees.
NumericBands for 60 degrees
With the same 10 bits and 20 tables, calculate candidate probability for vectors separated by 60 degrees.
Quiz
Why can a KD tree lose effectiveness in 768 dimensions?
CodeTop-k with deterministic ties
Implement topk_blocked(Q, X, k, block): compute blocked inner products and return indices of shape (queries,k), ordered by descending score and smaller index first in ties. Assume 1 ≤ k ≤ len(X) and positive block. Avoid sorting the full collection.
import numpy as np
def topk_blocked(Q, X, k, block):
  pass
Shift+Enter to run
Key idea
Blocked search is exact and controls memory; LSH uses random collisions to propose candidates and requires measuring both recall and work, without confusing angular distance with unnormalized inner product.