Skip to content

GPU indices

Present only when the extension was built with GPU support, which is the default. See GPU for the three things that differ from the CPU estimators.

gpu

GPU estimators, present only when the extension was built with them.

ann_search.gpu_available() is the check worth making: it says whether this machine has an adapter, which is the part that varies. The ordinary wheel has GPU support compiled in, so importing this module only fails on a build made with --no-default-features.

Three things differ from the CPU estimators, all of them consequences of the backend rather than choices:

  • float32 only. WGSL has no float64, so fit casts rather than letting a float64 array fail somewhere inside a kernel. That is a narrowing conversion, and the only one this package performs silently.
  • No persistence. These indices hold device buffers and sit outside the crate's serialise feature, so save, load and pickle raise. Rebuild.
  • Manhattan is unavailable on all of them.

ExhaustiveGpuIndex

ExhaustiveGpuIndex(
    n_neighbors: int = 15,
    metric: str = "euclidean",
    verbose: int = 0,
)

Bases: _BaseGpuIndex

Brute-force exact search on the device.

Recall is 1 by construction, and on a dataset too large to score on the CPU this is the cheapest way to get ground truth. No build-time knobs: the data goes up, the norms get recorded, and that is the index.

Do not expect an order of magnitude for it. On the benchmark M1 Max runs it comes out around 1.7x faster than ExhaustiveIndex; a discrete card with more bandwidth will do better.

Parameters:

Name Type Description Default
n_neighbors int

Neighbours per query, and the default k for kneighbors.

15
metric str

"euclidean"/"l2", "sqeuclidean" or "cosine".

'euclidean'
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout; in Jupyter that is the terminal running the kernel.

0

IvfGpuIndex

IvfGpuIndex(
    n_neighbors: int = 15,
    metric: str = "euclidean",
    nlist: int | None = None,
    nprobe: int | None = None,
    nquery: int | None = None,
    kmeans_algorithm: str = "emeans",
    kmeans_epochs: int | float | None = None,
    kmeans_iters: int | None = None,
    kmeans_balanced: bool = False,
    quantise_to_f16: bool = False,
    seed: int = 42,
    verbose: int = 0,
)

Bases: _BaseGpuIndex

Inverted file with k-means and the vectors both on the device.

Trains and queries without a readback, which is what makes it quick, and also what bounds it: the reordered vectors stay resident, so the dataset has to fit in device memory. nquery caps how many queries stage per batch if the upload is what does not fit.

Parameters:

Name Type Description Default
n_neighbors int

Neighbours per query, and the default k for kneighbors.

15
metric str

"euclidean"/"l2", "sqeuclidean" or "cosine".

'euclidean'
nlist int | None

Number of Voronoi cells to cut the space into. None defaults to sqrt(n).

None
nprobe int | None

Cells visited per query, the recall knob. None defaults to sqrt(nlist). Search-time: override it per call as index.kneighbors(nprobe=32).

None
nquery int | None

Queries staged on the device per batch. None sizes the batch from nprobe, the average cell size and the device's maximum binding, clamped into 100..=20_000. Lower it if a large nprobe overruns the candidate buffer. Search-time.

None
kmeans_algorithm str

"emeans" (default) or "lloyd". e-means is mini-batch k-means with an EMA update and fitted batch and step laws (Bessa et al., 2026).

'emeans'
kmeans_epochs int | float | None

Passes over the training sample under e-means, may be fractional. None defaults to 5. e-means only.

None
kmeans_iters int | None

Lloyd's only. Iterations when training the cells. None defaults to 30.

None
kmeans_balanced bool

Lloyd's only. Reseed starved centroids each iteration, RAFT-style. Evens out the posting lists, which matters more here than on the CPU because a straggler cell serialises its whole workgroup.

False
quantise_to_f16 bool

Hold the resident data buffer at fp16. Halves its memory and lifts effective bandwidth on the assignment kernels, at the cost of needing shader-f16 on the adapter.

False
seed int

Fixes k-means initialisation.

42
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout; in Jupyter that is the terminal running the kernel.

0

CagraGpuIndex

CagraGpuIndex(
    n_neighbors: int = 15,
    metric: str = "euclidean",
    graph_degree: int | None = None,
    build_k: int | None = None,
    max_iters: int | None = None,
    n_trees: int | None = None,
    delta: float | None = None,
    rho: float | None = None,
    refine_knn: int | None = None,
    retain_gpu: bool = True,
    beam_width: int | None = None,
    max_beam_iters: int | None = None,
    n_entry_points: int | None = None,
    expand_per_iter: int | None = None,
    half_vectors: bool | None = None,
    seed: int = 42,
    verbose: int = 0,
)

Bases: ExtractKnnMixin, _BaseGpuIndex

CAGRA graph: NN-Descent on the device, pruned, then beam-searched.

beam_width is the recall knob; leaving it None sizes the beam as 2 * max(k, 16), which is usually the right answer.

The build dominates until the dataset is large. On the benchmark runs the graph costs 1.3 to 3.2 seconds to build, so for a single query batch below roughly 500k points ExhaustiveGpuIndex finishes sooner overall, and at 250k in 128 dimensions it does so comfortably. Past that CAGRA pulls clear. It also holds 2 to 3x the memory of the raw vectors.

extract_knn hands back the kNN graph the descent converged on, taken before the CAGRA prune. No kernel runs, and it is capped by graph_degree rather than by the beam.

Unlike every other index in this package, a fitted handle is not safe to query from two threads at once: the beam search memoises its upload of the navigational graph behind a mutable borrow. Concurrent calls do not serialise, they raise, so give each thread its own handle. extract_knn takes a shared borrow and never causes the conflict, though it can still hit one raised by a concurrent query.

Parameters:

Name Type Description Default
n_neighbors int

Neighbours per query, and the default k for kneighbors. Not the graph degree, which is graph_degree.

15
metric str

"euclidean"/"l2", "sqeuclidean" or "cosine".

'euclidean'
graph_degree int | None

Neighbours stored per node in the final graph. None defaults to 30. The memory knob, and the ceiling on what extract_knn can return.

None
build_k int | None

Working degree the descent keeps before pruning. None defaults to 1.5 * graph_degree. Room to manoeuvre, so above graph_degree is the point.

None
max_iters int | None

Descent iteration cap. None defaults to 15.

None
n_trees int | None

Random projection trees used to seed the initial graph. None defaults to min(5 + round(n ** 0.25), 20).

None
delta float | None

Convergence threshold. Descent stops once the fraction of updated edges falls below it. None defaults to 0.001.

None
rho float | None

Local-join sampling rate. None defaults to 1.0, i.e. no sampling. Lower it to trade graph quality for build time.

None
refine_knn int | None

Two-hop refinement sweeps after the main loop. None defaults to 0, so refinement is off.

None
retain_gpu bool

Upload the navigational graph at build time rather than on the first query. On by default, because the first query would otherwise pay for it.

True
beam_width int | None

Beam width at query time, the recall knob. Search-time.

None
max_beam_iters int | None

Iteration cap on the beam search. Search-time.

None
n_entry_points int | None

Entry points into the graph per query. Search-time.

None
expand_per_iter int | None

Extra neighbours explored per beam iteration, usually 1 to 4. Search-time.

None
half_vectors bool | None

Walk the beam on an fp16 copy of the vectors and rescore its head in float32, so returned distances stay exact. True or False forces it; None makes the copy on the first query only if it keeps the device under 80% of its memory budget. The copy costs half the vector bytes again on the device. Search-time.

None
seed int

Fixes the seed graph and the sampling.

42
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout; in Jupyter that is the terminal running the kernel.

0
Note

The four beam parameters are all-or-nothing. Leave every one of them None and the beam is sized from k: beam_width = 2 * max(k, 16) and max_beam_iters = 3 * beam_width, with 8 entry points and 3 expansions per iteration. Set any one of them and that scaling is off for all four, and the ones still None fall back to flat constants: beam_width = 16, max_beam_iters = 48, n_entry_points = 8, expand_per_iter = 3. So asking for n_entry_points=16 alone on a k=50 query quietly narrows the beam from 100 to 16. If you touch one, set beam_width too. half_vectors sits outside that rule: set alone, it keeps the k-sized beam.

PipnnGpuIndex

PipnnGpuIndex(
    n_neighbors: int = 15,
    metric: str = "euclidean",
    r: int = 32,
    alpha: float = 1.2,
    leaf_k: int = 3,
    c_max: int = 512,
    c_min: int = 128,
    l_max: int = 64,
    fanout: Sequence[int] = (8, 2),
    replicas: int = 1,
    random_links: int = 4,
    beam_width: int | None = None,
    max_beam_iters: int | None = None,
    n_entry_points: int | None = None,
    expand_per_iter: int | None = None,
    half_vectors: bool | None = None,
    seed: int = 42,
    verbose: int = 0,
)

Bases: _BaseGpuIndex

PiPNN graph built on the CPU, beam-searched on the device.

The build is the CPU PipnnIndex build; the vectors and graph then go up to the device and stay there. Unlike CagraGpuIndex, a fitted handle is safe to query from several threads.

The graph and its build parameters are those of PipnnIndex; the search is the CAGRA beam, with the same four all-or-nothing knobs and half_vectors. No extract_knn: PiPNN keeps no kNN graph, only the pruned navigational one.

Parameters:

Name Type Description Default
n_neighbors int

Neighbours per query, and the default k for kneighbors.

15
metric str

"euclidean"/"l2", "sqeuclidean" or "cosine".

'euclidean'
r int

Maximum out-degree. The memory knob.

32
alpha float

RobustPrune slack on squared distances.

1.2
leaf_k int

Nearest in-leaf neighbours each point sends, both ways. The main build-quality knob.

3
c_max int

Largest leaf.

512
c_min int

Partition children smaller than this are merged.

128
l_max int

Candidate reservoir slots per node, at most 255.

64
fanout Sequence[int]

Leaders each point joins at each recursion depth.

(8, 2)
replicas int

Independent partitions streamed into the same reservoirs.

1
random_links int

Random candidates added to each node's final prune.

4
beam_width int | None

Beam width at query time, the recall knob. Search-time.

None
max_beam_iters int | None

Iteration cap on the beam search. Search-time.

None
n_entry_points int | None

Entry points per query. Search-time.

None
expand_per_iter int | None

Beam entries expanded per iteration. Search-time.

None
half_vectors bool | None

Walk the beam on an fp16 copy of the vectors and rescore its head in float32, so returned distances stay exact. True or False forces it; None makes the copy on the first query only if it keeps the device under 80% of its memory budget. Search-time.

None
seed int

Fixes the partition and so the graph.

42
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout.

0
Note

The beam knobs follow the CagraGpuIndex rule: leave all four None and the beam is sized from k; set any one and the rest fall back to flat constants. If you touch one, set beam_width too.

knn_graph_nndescent_gpu

knn_graph_nndescent_gpu(
    X: Any,
    n_neighbors: int = 15,
    *,
    metric: str = "euclidean",
    include_self: bool = True,
    return_distance: bool = True,
    build_k: int | None = None,
    max_iters: int | None = None,
    n_trees: int | None = None,
    delta: float | None = None,
    rho: float | None = None,
    refine_knn: int | None = None,
    n_clusters: int | None = None,
    sample_frac: float | None = None,
    n_assign: int | None = None,
    seed: int = 42,
    verbose: int = 0,
) -> tuple[ndarray, ndarray] | ndarray

Self-kNN graph by NN-Descent on the GPU, without building an index.

The graph-only counterpart of CagraGpuIndex: no CAGRA prune, no navigational graph, nothing left on the device afterwards. A dataset too large for one device binding is split into overlapping k-means clusters, each descended on its own and merged on the host; below that limit the build runs in one piece and the three cluster knobs do nothing.

Parameters:

Name Type Description Default
X Any

Samples by features. Cast to float32.

required
n_neighbors int

Row length, the self-edge included when include_self is set, matching kneighbors.

15
metric str

"euclidean"/"l2", "sqeuclidean" or "cosine".

'euclidean'
include_self bool

Whether row i starts with i at distance zero.

True
return_distance bool

Whether to return distances alongside indices.

True
build_k int | None

Working degree the descent keeps. None defaults to 1.5 * k.

None
max_iters int | None

Descent iteration cap. None defaults to 15.

None
n_trees int | None

Random projection trees seeding the graph. None sizes the forest from n.

None
delta float | None

Convergence threshold. None defaults to 0.001.

None
rho float | None

Local-join sampling rate. None defaults to 1.0, no sampling.

None
refine_knn int | None

Two-hop refinement sweeps. None defaults to 0.

None
n_clusters int | None

Clusters for the split build. None plans the count from the device limits.

None
sample_frac float | None

Fraction of the data the cluster centroids train on. None defaults to 0.1.

None
n_assign int | None

Clusters each point joins. None defaults to 2; 1 removes the overlap.

None
seed int

Fixes the seed graph and the sampling.

42
verbose int

0 quiet, 1 normal, 2 detailed. Prints to the process stdout, not sys.stdout.

0

Returns:

Type Description
tuple[ndarray, ndarray] | ndarray

(distances, indices) of shape (n, n_neighbors), or just

tuple[ndarray, ndarray] | ndarray

indices when return_distance is False.