Compressed vector search: IVF and product quantization
Build compressed vector search with an IVF coarse quantizer, product quantization and asymmetric distance tables, then combine residual IVF-PQ with exact reranking. Study score-aware anisotropic quantization and measure configurations against exact FAISS search.
After this lesson you can
- Implement IVF with k-means and measure the nprobe, recall@k and latency tradeoff.
- Implement product quantization and asymmetric distance tables and calculate memory per vector.
- Prove that asymmetric distance error is bounded by database-vector quantization error and compare symmetric distance.
- Build residual IVF-PQ with exact reranking and locate it on the recall, memory and speed frontier.
- Explain score-aware anisotropic quantization and when it improves inner-product search.
Before you start
- 23Exact nearest-neighbor searchMIPS-to-NN reductionApproximate nearest-neighbor guaranteesDense retrievalRanking metrics
- 12Lloyd's algorithmk-means objective (inertia)Vector quantization
- 09SIMD vectorizationMemory traffic of array expressionsMemory hierarchy
- 21Non-uniform codebook quantization
- 02Orthogonal projectionOrthogonal complement
Pruning and compression are different decisions
One billion vectors of 768 float32 components occupy 3.072 trillion bytes, about 3.072 decimal TB, for the vectors alone. Exact search remains the reference for measuring errors, but reading the entire collection can be costly. IVF reduces how many candidates are examined; PQ reduces bytes needed to represent each candidate. Either can be used alone and their errors differ.
IVF: choosing cells
An IVF index learns coarse centroids, for example with Lloyd’s algorithm, and assigns each vector to its nearest centroid. Each centroid has an inverted list of its identifiers. A query ranks centroids, probes the first nprobe lists and examines only their documents.
The figure uses four explicit centroids and seed-generated points assigned to the nearest centroid. Near a boundary, the centroid nearest the query may not be the exact neighbor’s centroid. Probing all centroids removes this coverage loss, though quantization error may remain afterward. Increasing nprobe adds lists and candidates, normally with more work; for exact neighbors within the union, recall cannot decrease if list selection is nested and ties are fixed.
The k-means objective minimizes training squared distortion; it does not directly maximize recall for the query distribution. A poorly trained codebook or changing distribution can produce imbalanced lists. Measure each list’s population; do not assume each contains exactly vectors.
A product of codebooks
Vector quantization replaces a vector with a centroid identifier. A single codebook with centroids is impractical. Product quantization (PQ) divides into subvectors and learns a codebook of centroids per subspace. Each subvector is encoded by an index; reconstruction concatenates the chosen centroids.
With and , there are possible combinations, although only small codebooks are stored. Each code needs bits if is a power of two. With equally sized subvectors, codebooks occupy numbers, not .
Each panel quantizes two coordinates; together they represent four. Changing from 4 to 16 centroids increases bits and refines a nested grid, so error does not increase in this example. With learned codebooks and finite samples, more centroids do not guarantee improvement for a specific procedure or shifted test.
Asymmetric distance and error
Asymmetric distance computation (ADC) keeps the full query and compares it with the document reconstruction. In each subspace it calculates a table . If the document code is ,
The table is prepared once per query and scanning codes sums entries per document. Tables, codes, identifiers, cache and random access determine actual cost. This approximation can change ranking even when reconstructed distance is close.
By the reverse triangle inequality, with the reconstruction,
The bound is for distances, not their squares. If the query is also quantized, symmetric distance has error at most . This does not imply ADC always has lower observed error: a larger bound does not order all errors. A small neighbor margin can reverse even with small errors.
Residuals, probing and reranking
In IVF-PQ with residuals and reranking, first assign to coarse centroid and quantize residual . For a query and each probed cell, the ADC table compares with residual centroids. Then select a shortlist with ADC and, if original vectors are retained, calculate exact distance.
There are two distinct losses. If the neighbor’s cell is not probed, increasing PQ precision does not recover it; increase nprobe or improve the coarse quantizer. If the cell is probed but compression leaves it outside the candidate set, more bits or a larger reranking set can help. Reranking cannot recover a vector that never reached that list. There is also a memory cost: retaining originals for reranking adds storage even when codes are small.
OPQ learns a rotation to distribute variation better across subspaces before PQ; an orthogonal rotation preserves exact distances but changes which combinations the product of codebooks can represent. Additive quantization sums several codes in the full space instead of concatenating subspaces; it increases flexibility and can also complicate encoding.
The score determines the relevant error
Score-aware quantization observes that for inner product, score error is , not residual norm alone. Two reconstructions with equal Euclidean error can affect queries differently. Guo and colleagues derive, under their query and relevance assumptions, an anisotropic loss penalizing residuals parallel and orthogonal to the database vector differently. This does not imply that weighting is optimal for every distribution or metric.
If representations are not normalized and the objective is MIPS, replacing it with Euclidean distance changes the problem. Asymmetric lifting is a geometric option, but compression and scoring objective still require evaluation. Evaluate index recall against exact neighbors and separately task nDCG with relevance judgments: preserving neighbors is not identical to preserving utility.
Measuring the frontier
The figure uses a FAISS CPU 1.16.0 run on 500000 precomputed Cohere-1M Wikipedia vectors, 16 separate queries and 20 threads. Codebooks were trained on the first 12000 vectors. Exact L2 search is the reference. The data are real, but the corpus was not encoded in this run and provides no relevance judgments; recall is index recall, not task nDCG.
Estimated bytes include codes, amortized codebooks and, for IVF, identifiers and coarse centroids. Reranking adds a float32 copy of each original vector; other structures and construction peak are omitted. Speeds are a point observation and horizontal axes show decimal logarithms rounded to hundredths: they do not prove a stable relationship or equal hardware conditions with GPU search. The selector finds lowest cost among these configurations, not a universally optimal frontier. Low recall can persist even with more lists when quantization error dominates.
Browser laboratory: IVF-PQ from scratch
The following data are synthetic: 20000 64-dimensional vectors around seed-generated centers. The run teaches the pipeline and checks results against exact search; it does not estimate quality on a real corpus. Codes use 16 centroids per subspace, stored as bytes for readability, although two four-bit codes could be packed per byte.
import numpy as np
rng=np.random.default_rng(19)
n,d,m,K,nlist=20_000,64,8,16,32
centers=rng.normal(size=(64,d)).astype(np.float32)
X=(centers[rng.integers(0,64,n)]+0.5*rng.normal(size=(n,d))).astype(np.float32)
Q=(centers[:4]+0.5*rng.normal(size=(4,d))).astype(np.float32)
def dist2(a,b):
return np.maximum(0, (a*a).sum(1)[:,None]+(b*b).sum(1)[None,:]-2*[email protected])
def lloyd(a,k,iters=5):
c=a[rng.choice(len(a),k,replace=False)].copy()
for _ in range(iters):
labels=np.argmin(dist2(a,c),axis=1)
for j in range(k):
mask=labels==j
if mask.any(): c[j]=a[mask].mean(axis=0)
return c
train=X[:2000]
coarse=lloyd(train,nlist)
labels=np.argmin(dist2(X,coarse),axis=1)
residual=X-coarse[labels]
truth=np.argsort(dist2(Q,X),axis=1,kind="stable")[:,:10]
books=[]
print("datos:",X.shape,"listas no vacías:",len(np.unique(labels)))for j in range(m):
books.append(lloyd(residual[:2000,j*8:(j+1)*8],K))
print("diccionarios:",len(books),"forma:",books[0].shape)codes=np.empty((n,m),dtype=np.uint8)
for j in range(m):
codes[:,j]=np.argmin(dist2(residual[:,j*8:(j+1)*8],books[j]),axis=1)
reconstructed=coarse[labels]+np.concatenate([books[j][codes[:,j]] for j in range(m)],axis=1)
error=np.linalg.norm(X-reconstructed,axis=1)
actual=np.linalg.norm(X-Q[0],axis=1)
approx=np.linalg.norm(reconstructed-Q[0],axis=1)
assert np.all(np.abs(actual-approx)<=error+1e-4)
print("bytes de códigos:",codes.nbytes,"máximo exceso sobre la cota:",float(np.max(np.abs(actual-approx)-error)))def search(q,nprobe,rerank=0):
cellorder=np.argsort(dist2(q[None,:],coarse)[0],kind="stable")[:nprobe]
candidates=np.flatnonzero(np.isin(labels,cellorder))
scores=np.empty(len(candidates),dtype=np.float32)
for cell in cellorder:
loc=np.flatnonzero(labels[candidates]==cell)
qres=q-coarse[cell]
tables=[dist2(qres[None,j*8:(j+1)*8],books[j])[0] for j in range(m)]
scores[loc]=sum(tables[j][codes[candidates[loc],j]] for j in range(m))
take=min(max(10,rerank),len(candidates))
part=np.argpartition(scores,take-1)[:take]
ids=candidates[part]
if rerank:
exact=dist2(q[None,:],X[ids])[0]
ids=ids[np.argsort(exact,kind="stable")[:10]]
else:
ids=ids[np.argsort(scores[part],kind="stable")[:10]]
return ids,len(candidates)
for p in (1,4,16,32):
for rerank in (0,100):
results=[search(q,p,rerank) for q in Q]
recall=np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(results,truth)])
print("nprobe",p,"rerank",rerank,"recall@10",recall,
"candidatos medios",np.mean([count for _,count in results]))Results are from four queries of this synthetic model. Maximum numerical excess over the bound can be negative: that means no difference violates it. An ADC table is built per query and cell because the query residual changes with the coarse centroid.
To isolate partition error, now search exactly within each union of lists. Recall of this IVF without PQ shows whether the problem lies in probing or later compression.
def ivf_exact(q,nprobe):
cells=np.argsort(dist2(q[None,:],coarse)[0],kind="stable")[:nprobe]
candidates=np.flatnonzero(np.isin(labels,cells))
values=dist2(q[None,:],X[candidates])[0]
ids=candidates[np.argsort(values,kind="stable")[:10]]
return ids,len(candidates)
for p in (1,4,16,32):
results=[ivf_exact(q,p) for q in Q]
recall=np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(results,truth)])
print("nprobe",p,"recall@10",recall,"candidatos medios",np.mean([n for _,n in results]))Local laboratories: texts, indices and task
You need a connection, storage space and an environment with PyTorch, sentence-transformers, datasets, FAISS CPU and huggingface_hub. The first cell takes one passage per article from Wikimedia Wikipedia 20231101.en, encodes up to 500000 with E5 and saves normalized vectors, identifiers and 16 queries based on held-out article titles. The encoder uses BF16 on CUDA and promotes results to float32 for storage and search; this does not make inference float32. Writing uses space in the specified directory. This long cell is omitted from automatic tests.
from pathlib import Path
from itertools import islice
import json, numpy as np, torch
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
limit = 500_000 # usa 16 para una prueba corta
target_dir = Path('wiki-e5-lab')
target_dir.mkdir(parents=True,exist_ok=True)
dataset = load_dataset('wikimedia/wikipedia','20231101.en',split='train',streaming=True,
revision='b04c8d1ceb2f5cd4588862100d08de323dccfbaa')
iterator = iter(dataset)
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
raise RuntimeError('Esta configuración necesita una GPU CUDA compatible con BF16')
torch.set_float32_matmul_precision('highest')
model = SentenceTransformer('intfloat/multilingual-e5-small', revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cuda')
model.bfloat16()
vectors = np.lib.format.open_memmap(target_dir/'passages.npy',mode='w+',dtype=np.float32,shape=(limit,384))
with (target_dir/'ids.jsonl').open('w',encoding='utf-8') as ids:
for start in range(0,limit,1024):
batch = list(islice(iterator,min(1024,limit-start)))
if len(batch)!=min(1024,limit-start): raise RuntimeError('El corpus terminó antes de lo previsto')
texts=['passage: '+x['title']+' '+x['text'][:2000] for x in batch]
vectors[start:start+len(batch)] = model.encode(texts,batch_size=16,normalize_embeddings=True,convert_to_tensor=True).float().cpu().numpy()
for x in batch: ids.write(json.dumps({'id':x['id'],'title':x['title']},ensure_ascii=False)+'\n')
vectors.flush()
held = list(islice(iterator,16))
if len(held)!=16: raise RuntimeError('Faltan consultas retenidas')
if hasattr(iterator,'close'): iterator.close()
Q=model.encode(['query: '+x['title'] for x in held],batch_size=16,normalize_embeddings=True,convert_to_tensor=True).float().cpu().numpy()
np.save(target_dir/'queries.npy',Q)
print('pasajes y consultas:',vectors.shape,Q.shape,'directorio:',target_dir)npm run lab and open the connection link.Precision changes the representation. As a prior control, the same 1024 passages and 16 held-out title queries were encoded in float32 and BF16. Mean overlap between their exact top-10s was 0.91875 and maximum absolute score difference was 0.00548. These are neighbors in this sample without relevance judgments and do not establish universal quality loss. The full campaign encoded 500000 passages and 16 queries on an RTX 3060. BF16 normalization does not leave exactly unit norms: stored passage norms ranged from 0.99625 to 1.00397. Therefore the experiment uses L2 distance in both index and exact ground truth; it does not assume exact cosine equivalence. Do not mix results of the two precisions.
The next cell implements Lloyd, coarse assignment, residual PQ, ADC and reranking with PyTorch and NumPy. By default it uses Wikipedia vectors from the previous cell; change source to cohere for precomputed vectors and their queries. For a 16-vector wiki sample it automatically reduces centroids. The Cohere run obtained, at nprobe 4, recall@10 of 0.175 without reranking and 0.4375 reranking 100, on 16 queries. Printed memory counts unpacked codes, labels and codebooks without originals or temporaries.
import time, numpy as np, torch
from huggingface_hub import hf_hub_download
repo='YoKONCy/Cohere-1M-wikipedia-768d';rev='25ad59fd88a30aec3370cbc4c46dcbfc1e19591f'
get=lambda f:hf_hub_download(repo,f,repo_type='dataset',revision=rev)
source='wiki' # 'cohere' usa los vectores externos precomputados
if source=='wiki':
X=np.load('wiki-e5-lab/passages.npy',mmap_mode='r')
Q=np.load('wiki-e5-lab/queries.npy')
else:
X=np.memmap(get('cohere_train.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:500000]
Q=np.array(np.memmap(get('cohere_test.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:16],copy=True)
device='cuda' if torch.cuda.is_available() else 'cpu'
torch.manual_seed(19)
def d2(a,b):
return (a.square().sum(1)[:,None]+b.square().sum(1)[None,:]-2*[email protected]).clamp_min_(0)
def lloyd(a,k,steps=5):
c=a[torch.randperm(len(a),device=a.device)[:k]].clone()
for _ in range(steps):
label=d2(a,c).argmin(1)
sums=torch.zeros_like(c); sums.index_add_(0,label,a)
counts=torch.bincount(label,minlength=k)
nonempty=counts>0
c[nonempty]=sums[nonempty]/counts[nonempty,None]
return c
start=time.perf_counter()
train=torch.from_numpy(np.array(X[:12000],copy=True)).to(device)
coarse=lloyd(train,min(64,max(2,len(train)//2)))
trainlab=d2(train,coarse).argmin(1)
res=train-coarse[trainlab]
m=16; K=min(16,max(2,len(train)//2)); sub=X.shape[1]//m
books=torch.stack([lloyd(res[:,j*sub:(j+1)*sub],K) for j in range(m)])
labels=np.empty(len(X),dtype=np.int32)
codes=np.empty((len(X),m),dtype=np.uint8)
for begin in range(0,len(X),8192):
chunk=torch.from_numpy(np.array(X[begin:begin+8192],copy=True)).to(device)
cl=d2(chunk,coarse).argmin(1); residual=chunk-coarse[cl]
labels[begin:begin+len(chunk)]=cl.cpu().numpy()
for j in range(m):
codes[begin:begin+len(chunk),j]=d2(residual[:,j*sub:(j+1)*sub],books[j]).argmin(1).cpu().numpy()
if device=='cuda': torch.cuda.synchronize()
print('own build seconds',time.perf_counter()-start,'bytes codes, labels, books, centroids',codes.nbytes,labels.nbytes,books.numel()*4,coarse.numel()*4,flush=True)
def exact(q):
qt=torch.from_numpy(q[None,:]).to(device)
best=torch.empty((1,0),device=device); ids=torch.empty((1,0),device=device,dtype=torch.long)
for begin in range(0,len(X),8192):
chunk=torch.from_numpy(np.array(X[begin:begin+8192],copy=True)).to(device)
val=-d2(qt,chunk); ix=torch.arange(begin,begin+len(chunk),device=device).reshape(1,-1)
val=torch.cat([best,val],1);ix=torch.cat([ids,ix],1)
best,positions=torch.topk(val,min(10,val.shape[1]),dim=1);ids=torch.gather(ix,1,positions)
return ids[0].cpu().numpy()
truth=[exact(q) for q in Q]
def search(q,probe,rerank):
qt=torch.from_numpy(q[None,:]).to(device)
chosen=torch.argsort(d2(qt,coarse)[0])[:probe].cpu().numpy()
candidates=np.flatnonzero(np.isin(labels,chosen))
scores=np.empty(len(candidates),dtype=np.float32)
for cell in chosen:
loc=np.flatnonzero(labels[candidates]==cell)
qr=qt-coarse[cell]
table=torch.stack([d2(qr[:,j*sub:(j+1)*sub],books[j])[0] for j in range(m)]).cpu().numpy()
scores[loc]=sum(table[j,codes[candidates[loc],j]] for j in range(m))
take=min(max(10,rerank),len(candidates)); pos=np.argpartition(scores,take-1)[:take]; ids=candidates[pos]
if rerank:
vals=np.sum((X[ids]-q)**2,axis=1);ids=ids[np.argsort(vals,kind='stable')[:10]]
else:
ids=ids[np.argsort(scores[pos],kind='stable')[:10]]
return ids,len(candidates)
for p in (4,16):
for r in (0,100):
start=time.perf_counter(); result=[search(q,p,r) for q in Q]
rec=np.mean([len(set(ids)&set(t))/10 for (ids,_),t in zip(result,truth)])
print('nprobe',p,'rerank',r,'recall',rec,'candidates',np.mean([n for _,n in result]),'qps',len(Q)/(time.perf_counter()-start),flush=True)npm run lab and open the connection link.On 500000 Wikipedia vectors and 16 held-out queries, custom IVF-PQ obtained recall@10 0.09375 without reranking and 0.30000 reranking 100 candidates at nprobe 4; at nprobe 16 it obtained 0.09375 and 0.31875. Unpacked codes, labels, codebooks and centroids totaled 10122880 bytes; retaining originals adds 768000000 bytes. PyTorch and FAISS exact L2 ground truth agreed on all ten neighbors of all 16 queries. Queries are titles without relevance judgments: this recall measures the index, not task nDCG. Results depend on codebook training and this small sample.
The FAISS factory reads configurations such as IVF64,PQ16x4: 64 lists and 16 four-bit subquantizers. Train before adding data; set nprobe on the IVF index. The next block compares FAISS with the custom index on Wikipedia by default; change source to cohere to reconstruct figure points. That configuration needs at least 12000 vectors, not the 16-vector sample. Add original-vector cost when reranking. Times depend on hardware and load; 20 threads were used here because that was machine availability, not 24 physical cores. It is omitted from automatic tests due to download and cost.
import json, time
import numpy as np
import faiss
from huggingface_hub import hf_hub_download
repo='YoKONCy/Cohere-1M-wikipedia-768d'
rev='25ad59fd88a30aec3370cbc4c46dcbfc1e19591f'
get=lambda f:hf_hub_download(repo,f,repo_type='dataset',revision=rev)
source='wiki' # 'cohere' reconstruye la configuración de la figura
if source=='wiki':
X=np.load('wiki-e5-lab/passages.npy',mmap_mode='r')
Q=np.load('wiki-e5-lab/queries.npy')
else:
X=np.memmap(get('cohere_train.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:500000]
Q=np.array(np.memmap(get('cohere_test.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:16],copy=True)
dim=X.shape[1]
if len(X)<12000: raise ValueError('Esta configuración necesita al menos 12000 vectores')
train=np.array(X[:12000],copy=True)
faiss.omp_set_num_threads(20)
def recall(I,truth):
return float(np.mean([len(set(a)&set(b))/10 for a,b in zip(I,truth)]))
def timed(index,k=10):
index.search(Q[:1],k)
start=time.perf_counter(); D,I=index.search(Q,k); elapsed=time.perf_counter()-start
return D,I,len(Q)/elapsed
flat=faiss.IndexFlatL2(dim); flat.add(X)
_,truth,qps=timed(flat)
out=[{'name':'Exacta','bytes':dim*4,'recall':1.0,'qps':qps}]
for m in (8,16,32):
name=f'IVF64,PQ{m}x4'
index=faiss.index_factory(dim,name,faiss.METRIC_L2)
start=time.perf_counter(); index.train(train); index.add(X)
print(name,'build seconds',time.perf_counter()-start,flush=True)
for nprobe in (4,16):
index.nprobe=nprobe
_,I,qps=timed(index)
amort=(64*dim*4 + m*16*(dim//m)*4)/len(X)
out.append({'name':f'{name}, nprobe={nprobe}','bytes':m/2+8+amort,'recall':recall(I,truth),'qps':qps})
_,cand,_=timed(index,100)
start=time.perf_counter(); _,cand=index.search(Q,100)
reranked=[]
for q,c in zip(Q,cand):
ids=c[c>=0]; scores=np.sum((X[ids]-q)**2,axis=1)
reranked.append(ids[np.argsort(scores,kind='stable')[:10]])
qps_r=len(Q)/(time.perf_counter()-start)
out.append({'name':f'{name}, nprobe={nprobe}, rerank 100','bytes':dim*4+m/2+8+amort,'recall':recall(reranked,truth),'qps':qps_r})
print(out[-4:],flush=True)
print(json.dumps(out,indent=2))npm run lab and open the connection link.On the same Wikipedia collection, FAISS IVF64,PQ16x4 achieved recall@10 0.10625 and 0.26875 reranking 100 at nprobe 4; at nprobe 16 it achieved 0.11250 and 0.29375. Centroid training is not identical to the custom implementation, and packed codes occupy less than the bytes used to explain the earlier code. Speeds and build time are printed for each run; one pass under shared load with different hardware per stage does not establish a general latency comparison.
The next block measures PQ without IVF on the same dataset; it helps identify savings from compression versus list probing.
import json,time
import numpy as np
import faiss
from huggingface_hub import hf_hub_download
repo='YoKONCy/Cohere-1M-wikipedia-768d';rev='25ad59fd88a30aec3370cbc4c46dcbfc1e19591f'
get=lambda f:hf_hub_download(repo,f,repo_type='dataset',revision=rev)
X=np.memmap(get('cohere_train.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:500000]
Q=np.array(np.memmap(get('cohere_test.f32'),dtype=np.float32,mode='r').reshape(-1,768)[:16],copy=True)
train=np.array(X[:12000],copy=True)
faiss.omp_set_num_threads(20)
flat=faiss.IndexFlatL2(768);flat.add(X);_,truth=flat.search(Q,10)
out=[]
for m in (8,16,32):
index=faiss.index_factory(768,f'PQ{m}x4',faiss.METRIC_L2)
start=time.perf_counter(); index.train(train); index.add(X)
print('build',m,time.perf_counter()-start,flush=True)
index.search(Q[:1],10)
start=time.perf_counter(); _,I=index.search(Q,10); elapsed=time.perf_counter()-start
rec=float(np.mean([len(set(a)&set(b))/10 for a,b in zip(I,truth)]))
out.append({'name':f'PQ{m}x4','bytes':m/2+16*768*4/len(X),'recall':rec,'qps':len(Q)/elapsed})
print(out[-1],flush=True)
print(json.dumps(out,indent=2))npm run lab and open the connection link.The string OPQ8,IVF32,PQ8x4 adds a rotation before IVF and PQ. Since it is a composite index, extract the IVF component to change nprobe; assigning an attribute to the wrapper does not guarantee changing the inner index. This test uses only 10000 vectors and one OPQ iteration to check the pipeline. A larger run can use, for example, OPQ48,IVF1024,PQ48 with sufficient samples and training: that configuration was not measured here.
import numpy as np, faiss
from huggingface_hub import hf_hub_download
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)
faiss.omp_set_num_threads(20)
flat=faiss.IndexFlatL2(768);flat.add(X);_,truth=flat.search(Q,10)
index=faiss.index_factory(768,'OPQ8,IVF32,PQ8x4',faiss.METRIC_L2)
opq=faiss.downcast_VectorTransform(index.chain.at(0));opq.niter=1;opq.niter_pq=1;opq.niter_pq_0=1
ivf=faiss.extract_index_ivf(index);ivf.cp.niter=3
index.train(X);index.add(X)
for nprobe in (1,8,32):
ivf.nprobe=nprobe;_,ids=index.search(Q,10)
recall=np.mean([len(set(a)&set(b))/10 for a,b in zip(ids,truth)])
print('OPQ smoke nprobe',nprobe,'recall',recall,flush=True)npm run lab and open the connection link.Finally, SciFact does contain relevance judgments. Its 5183 documents and 300 test queries are encoded with E5, and index recall and task nDCG are compared against the same exact reference. In the verified run, exact search yielded nDCG@10 0.6770; IVF32 with PQ16x4 and nprobe 32 yielded recall@10 0.2193 and nDCG@10 0.2627. These are results of this protocol, not the Cohere corpus or a general guarantee. Parameter choice should be made outside the test set.
import json,zipfile,csv,io,time,requests
import numpy as np
import torch,faiss
from sentence_transformers import SentenceTransformer
response=requests.get('https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/scifact.zip',timeout=90)
response.raise_for_status()
with zipfile.ZipFile(io.BytesIO(response.content)) as z:
corpus=[json.loads(x) for x in z.read('scifact/corpus.jsonl').decode('utf-8').splitlines()]
queries={x['_id']:x['text'] for x in map(json.loads,z.read('scifact/queries.jsonl').decode('utf-8').splitlines())}
rows=list(csv.DictReader(io.StringIO(z.read('scifact/qrels/test.tsv').decode('utf-8')),delimiter='\t'))
qrels={}
for row in rows:
if int(row['score'])>0: qrels.setdefault(row['query-id'],set()).add(row['corpus-id'])
qids=sorted(qrels)
ids=[x['_id'] for x in corpus]
texts=[x.get('title','')+' '+x['text'] for x in corpus]
model=SentenceTransformer('intfloat/multilingual-e5-small',device='cuda' if torch.cuda.is_available() else 'cpu')
X=model.encode(['passage: '+x for x in texts],batch_size=16,normalize_embeddings=True,convert_to_numpy=True,show_progress_bar=True)
Q=model.encode(['query: '+queries[q] for q in qids],batch_size=16,normalize_embeddings=True,convert_to_numpy=True,show_progress_bar=True)
faiss.omp_set_num_threads(20)
flat=faiss.IndexFlatL2(X.shape[1]);flat.add(X);_,truth=flat.search(Q,10)
def metric(I):
ndcg=[]
for qid,ix in zip(qids,I):
relevant=qrels[qid]
dcg=sum((ids[j] in relevant)/np.log2(i+2) for i,j in enumerate(ix) if j>=0)
ideal=sum(1/np.log2(i+2) for i in range(min(10,len(relevant))))
ndcg.append(dcg/ideal)
return float(np.mean(ndcg))
print('N',len(X),'Q',len(Q),'exact ndcg@10',metric(truth),flush=True)
for m in (8,16):
index=faiss.index_factory(X.shape[1],f'IVF32,PQ{m}x4',faiss.METRIC_L2)
index.train(X);index.add(X)
for probes in (1,8,32):
index.nprobe=probes;_,I=index.search(Q,10)
rec=float(np.mean([len(set(a)&set(b))/10 for a,b in zip(I,truth)]))
print('m',m,'nprobe',probes,'index recall@10',rec,'task ndcg@10',metric(I),flush=True)npm run lab and open the connection link.Exercises
Step 1 of 2. Which inequality connects two distances to the same query?
import numpy as np
def adc_search(query, codes, codebooks, k):
pass