#272IVF (Inverted File) SearchMediumNeural NetworksML System DesignAsked atMeta · Google · Cohere
IVF (Inverted File) Search
Background
IVF (Inverted File Index) clusters the database into Voronoi cells around K-means centroids. At query time, you only search the top-nprobe cells — quadratic-to-linear speedup in exchange for some recall. The simple ANN baseline used by FAISS at billion-scale.
Problem statement
Implement ivf_search(query, db, centroids, assignments, k, nprobe=2). Steps:
- Compute the L2 distance from query to each centroid.
- Pick the
nprobenearest centroids. - Restrict candidates to db rows whose
assignmentslie in those cells. - Within the candidates, compute exact L2 distance to the query.
- Return the top- candidate indices.
Input
query— 1-Dnp.ndarrayof length .db— 2-Dnp.ndarrayshape .centroids— 2-Dnp.ndarrayshape .assignments— 1-Dnp.ndarrayofintlength , the centroid index for each db row.k—int, target result count.nprobe—int >= 1, number of cells to probe (default ).
Output
Returns list[int] of length — db indices in ascending-distance order.
Examples
Example 1 — query inside one cell
Input: query close to centroid 0; nprobe=1
Output: indices of the rows assigned to centroid 0, ordered by distance
Example 2 — nprobe spans multiple cells
nprobe=2 returns the union of candidates from the two nearest cells.
Constraints
- If no db row falls in any probed cell, return
[]. - Returns Python
ints, not numpyints. kmay exceed candidate count; in that case return all candidates.
Notes
- Recall vs latency.
nprobe = 1is fastest but lossy. Doublingnproberoughly halves the recall miss rate. - Train the centroids on a subsample. Production IVF clusters on 1M+ vectors with K-means; the
centroidshere are an input, not learned.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example: query nearest centroid 0, nprobe=1
- •Reference: two nearest cells union, nprobe=2
- •Sample: ascending L2 order within one cell