Repository navigation
Description
Describe the bug
On datasets made of well-separated clusters, CAGRA graphs built with build_algo=IVF_PQ split into many disconnected
components. When the same CAGRA graph is converted to HNSW using faiss (IndexHNSWCagra, base_level_only=True), recall
drops from ~99% for a CPU-built HNSW index on the same data to ~14–17%:
| Index on the same 300k × 1024 dataset | Level-0 components (largest) | recall@600, 8 real queries | recall@600, 200 corpus queries |
|---|---|---|---|
CPU HNSW (faiss IndexHNSWFlat, M=16, efConstruction 256) |
1–4 (100%) | 98.8% | 99.95% |
CAGRA (IVF_PQ) → faiss IndexHNSWCagra |
217 (1.5%) | 13.7% (0–38% per pass) | 17.3% (15–22% per pass) |
Search uses ef_search 600 on the CPU. CAGRA recall is the mean over 10 repeats; it varies from request to request because the
base-level search starts from random entry points. Reproduced by repro_faiss_cagra_hnsw.py (below). CAGRA build parameters are in the table under More details below.
More details
We see this with OpenSearch k-NN's GPU index build
remote-vector-index-builder (RVIB), which:
- builds a CAGRA graph through faiss
GpuIndexCagra(cuVS backend); - converts it to a CPU
faiss.IndexHNSWCagrawithbase_level_only=TrueviaGpuIndexCagra::copyTo; - returns the file to OpenSearch, which searches it on CPU with faiss.
IndexHNSWCagra base-level-only search starts from the best of 32 random entry points, so on a fragmented graph identical
queries return different results across requests.
Default CAGRA parameters RVIB sends for float / fp16 vectors (from
remote_vector_index_builder/core/index_builder/faiss/faiss_index_build_service.py and the builder dataclasses).
m = the index's HNSW m (default 16).
| Parameter | RVIB main (1.3.0) |
RVIB 1.2.0 release |
|---|---|---|
build_algo |
IVF_PQ (NN_DESCENT is used only for binary vectors) | IVF_PQ |
graph_degree |
4·m = 64 | 2·m = 32 |
intermediate_graph_degree |
4·m = 64 (m lowered for very small segments) | 4·m = 64 |
IVF-PQ n_lists |
int(√N) | int(√N) |
IVF-PQ pq_dim / pq_bits |
d / 4 / 8 | d / 4 / 8 |
IVF-PQ kmeans_n_iters / kmeans_trainset_fraction |
20 / 0.1 | 20 / 0.1 |
IVF-PQ codebook_kind |
PER_SUBSPACE (faiss default) | PER_SUBSPACE |
IVF-PQ force_random_rotation / conservative_memory_allocation |
true / true | true / true |
IVF-PQ search n_probes |
5 | 20 |
| IVF-PQ search LUT / internal distance dtype | fp32 (faiss defaults) | fp32 |
refinement_rate |
1.0 (faiss default is 2.0) | 1.0 |
store_dataset |
false | false |
guarantee_connectivity |
not set (false) | not set (false) |
Vector dtype passed to add_with_ids |
fp32, or fp16 for fp16 indexes | same |
| CPU conversion | IndexHNSWCagra, base_level_only=True, efConstruction from the mapping (e.g. 512), efSearch 100 |
same |
| faiss / cuVS | faiss v1.14.3 + 3 small patches / cuVS 26.08.01 | faiss pre-1.12 dev (f9ccd582) / cuVS 25.08 |
Both RVIB configurations fragment on our data. Every faiss-based number below uses the main configuration unless stated.
Steps/Code to reproduce bug
- Build faiss v1.14.3 with cuVS 26.08.01, the way RVIB builds it:
setup_faiss_from_source.sh(appendix). - Download the dataset: q8
or q200.
Both are 300k × 1024, angular, with exact top-600 neighbours. - Run
repro_faiss_cagra_hnsw.py(appendix). It builds the CAGRA graph with RVIB's parameters through
faissGpuIndexCagra, converts it withcopyTotoIndexHNSWCagra(base_level_only=True), builds a CPU
IndexHNSWFlatfor comparison, and reports level-0 components and recall@600 at ef_search 600:
python repro_faiss_cagra_hnsw.py cohere-v4-1024-angular-q8.hdf5
python repro_faiss_cagra_hnsw.py cohere-v4-1024-angular-q200.hdf5Output (NVIDIA L4):
$ python repro_faiss_cagra_hnsw.py cohere-v4-1024-angular-q8.hdf5
faiss 1.14.3, GPUs 1, train (300000, 1024), queries (8, 1024), k=600, ef_search=600
index build s L0 SCCs largest recall@600 min..max over repeats
CAGRA (IVF_PQ) -> IndexHNSWCagra 6.6 217 1.5% 0.1370 0.0000 .. 0.3808
CPU IndexHNSWFlat (M=16, efC=256) 29.6 1 100.0% 0.9883 0.9883 .. 0.9883
$ python repro_faiss_cagra_hnsw.py cohere-v4-1024-angular-q200.hdf5
faiss 1.14.3, GPUs 1, train (300000, 1024), queries (200, 1024), k=600, ef_search=600
index build s L0 SCCs largest recall@600 min..max over repeats
CAGRA (IVF_PQ) -> IndexHNSWCagra 6.5 217 1.5% 0.1726 0.1454 .. 0.2190
CPU IndexHNSWFlat (M=16, efC=256) 28.0 4 100.0% 0.9995 0.9995 .. 0.9995
Results across datasets (faiss GpuIndexCagra → IndexHNSWCagra, base level only)
Graphs built through faiss 1.14.3 GpuIndexCagra with cuVS 26.08.01, converted to IndexHNSWCagra (base level only) and
searched on CPU (ef 600). The CPU search starts from the best of 32 random entry points.
| Dataset (n × d, cosine) | IVF_PQ n_probes 5, 64/64: SCCs / recall@100 | IVF_PQ n_probes 20, 64/128 |
|---|---|---|
| GMM, 200 clusters, sigma 0.3 (300k × 256) | 200 / 0.16 | 200 / 0.15 |
| GMM, 200 clusters, sigma 1.0 (300k × 256) | 200 / 0.135 | 200 / 0.125 |
| GMM, 1000 clusters, sigma 0.3 (300k × 256) | 1000 / 0.01 | 1000 / 0.02 |
| GMM, 200 clusters, sigma 2.0 (control) | 1 / 0.967 | 1 / 0.991 |
| Product-catalogue embeddings (300k × 1024, dataset), recall@600 | 215 / 0.17 | 177 / 0.21 |
Product-catalogue dataset
The dataset is 300,000 × 1024 fp32 text embeddings of a synthetic product catalogue, about 45 product categories, cosine
similarity. It comes as an ann-benchmarks-style HDF5 (train, test, neighbors, distances, distance="angular",
exact top-600). Download: q8 · q200 (≈ 1.2 GB each; md5 def125d53c1d04ba50e59bb842bed4c4 / 2f30494587afea3b204a8516f46ca101).
| File | test (queries) |
Notes |
|---|---|---|
cohere-v4-1024-angular-q8.hdf5 |
8 real search-phrase embeddings | exact top-600 by cosine |
cohere-v4-1024-angular-q200.hdf5 |
200 corpus vectors (np.random.default_rng(42).choice(300000, 200, replace=False), also stored as sample_ids) |
each query is in train; its own id is at rank 0 |
On this dataset:
-
The exact k-NN graph itself is disconnected:
k 16 64 128 1024 2047 weakly connected components 367 209 167 72 44 For every vector, all of its exact 64 nearest neighbours fall in its own category.
-
Making IVF-PQ more accurate converges to the data's own split:
refinement_rate2.0 / 4.0 andpq_dim = 1024both
give exactly 167 SCCs. -
The candidate search isn't what loses the cross-cluster edges. With n_probes 5, the probed lists contain all of a
vector's exact 128 nearest neighbours for 99.8% of vectors; with n_probes 20 it's 100%. -
IVF-PQ +
guarantee_connectivity: 1 SCC, recall@600 ≈ 0.51–0.65 on real queries and ≈ 0.76–0.81 on corpus queries.
Results also vary strongly with the entry points: 2–3 distinct result sets per query over 10 repeats.
Expected behavior
-
A CAGRA graph should stay navigable on clustered data: reachable from typical entry points, with recall comparable to an
HNSW graph on the same data. Or it should at least warn when it isn't. -
For reference, CPU HNSW on the same data (faiss, M=16, efConstruction 256, single thread, 5 repeats) is a single
connected component with stable results:Data HNSW variant Build (32 threads) Level-0 SCCs (largest share) Recall mean (min) Unstable queries Product catalogue, q8, k=600, ef 600 IndexHNSWFlatfp3231.0 s 3 (100%) 0.988 (0.965) 0 / 8 Product catalogue, q200, k=600, ef 600 IndexHNSWFlatfp32(same index) 0.9995 (0.992) 0 / 200 Product catalogue, q8 / q200, k=600, ef 600 IndexHNSWSQfp1658.3 s 2 (100%) 0.988 / 0.999 0 / 0 The 2–3 tiny level-0 components in HNSW hold almost no nodes, and the upper levels route queries to the right region.
The equivalent CAGRA (IVF-PQ, RVIB
maindefaults) builds in ≈ 6.5 s but has 217 SCCs and recall@600 ≈ 0.14–0.17. -
guarantee_connectivitybridges should be useful for search: for example, connect each component through its nearest
cross-component pair(s), not an arbitrary node.
Questions / suggestions
- Is this a known limitation of CAGRA's construction (pruning a k-NN graph cannot create adjacencies that the k-NN graph
lacks)? Are there plans for a long-range / diversity edge budget, like Vamana's α-pruning or HNSW's incremental insertion? - Could
guarantee_connectivity's MST step choose bridge endpoints by distance (nearest cross-component pairs, possibly
several per component) rather than arbitrary nodes? - Would a cheap post-build connectivity check be welcome, e.g. an API returning the component count, or a warning when the
largest SCC is below a threshold?
Environment details
-
cuVS: 26.08.01 (conda
libcuvs=26.08.01) -
CUDA: 12.9 toolkit (conda
cuda-nvcc=12.9,cuda-version=12.9); driver 595.91.07 (CUDA 13.2) -
GPU: NVIDIA L4 24 GB (also seen on A10G)
-
OS: Ubuntu 22.04, x86_64
-
faiss: v1.14.3 built from source with
-DFAISS_ENABLE_CUVS=ON, plus RVIB's patches from
base_image/patches/:0001: skip storage oncopyTo;0002: don't auto-widenintermediate_graph_degreewhen it equalsgraph_degree;0003: the cuVS 26.08 compatibility diff shipped by cuVS.
None of them changes how cuVS constructs the graph.
Environment setup scripts
-
faiss path, as RVIB builds it:
setup_faiss_from_source.shreproduces RVIB's
base_imageDockerfile without Docker:- Miniconda
py311_26.1.1-1; python 3.11, cmake 4.0.3, swig 4.0, gxx 14.2. libcuvs=26.08.01,cuda-nvcc=12.9.- The faiss submodule at RVIB's pin, plus patches 0001–0003.
cmake -DFAISS_ENABLE_GPU=ON -DFAISS_ENABLE_CUVS=ON -DFAISS_OPT_LEVEL=generic -DBUILD_SHARED_LIBS=OFF ..., then
make faiss swigfaissand the python install.
The build takes about 20 minutes with
-j16. - Miniconda
Additional context: source notes (cuVS v26.08.01)
- IVF-PQ candidate graph: with
refinement_rate == 1.0,gpu_top_k == top_k
(cagra_build.cuh#L1688), sodo_refine = false
(#L1596). The PQ-ranked topintermediate_degreebecome the k-NN graph as-is
(write_to_graph, #L1557). optimize():- Detour-count pruning (
kern_fused_prune, graph_core.cuh#L206) selects a subset of
each k-NN row. kern_merge_graph(#L375) merges reverse edges of the pruned graph into the second
half of each row.- Neither step adds an adjacency that isn't in the k-NN graph, so the number of weakly connected components can't
decrease.
- Detour-count pruning (
guarantee_connectivity(mst_optimization, #L1186):- The MST candidates are the rank-k edges of the input k-NN graph (#L1319). On data
whose k-NN graph has no edges between clusters, these can't join the clusters. - The fallback for the remaining components (#L1294-L1316): every node outside
the main cluster gets an edge to the first main-cluster node found by steppingj = (j + 97) % graph_size. That is
effectively an arbitrary node, which matches the ≈ 0.3 median cosine we measured on these bridge edges.
- The MST candidates are the rank-k edges of the input k-NN graph (#L1319). On data
Appendix: scripts
repro_faiss_cagra_hnsw.py
#!/usr/bin/env python3
"""
Repro: a CAGRA graph built with IVF-PQ on clustered data splits into many disconnected components, and after conversion
to HNSW with faiss (IndexHNSWCagra, base_level_only=True) recall@600 is far below a CPU-built HNSW on the same data.
CAGRA build parameters are the defaults of the OpenSearch remote-vector-index-builder (main):
IVF_PQ graph build, graph_degree = intermediate_graph_degree = 4*m = 64, n_lists = int(sqrt(N)), pq_dim = d/4, pq_bits 8,
kmeans_trainset_fraction 0.1, force_random_rotation, n_probes 5, refine_rate 1.0, store_dataset False,
then GpuIndexCagra.copyTo(IndexHNSWCagra) with base_level_only=True, efConstruction 512, efSearch 100.
Data: ann-benchmarks style HDF5 (train / test / neighbors, angular), e.g. cohere-v4-1024-angular-q8.hdf5.
Requires faiss built with GPU + cuVS (FAISS_ENABLE_CUVS=ON), numpy, scipy, h5py.
python repro_faiss_cagra_hnsw.py cohere-v4-1024-angular-q8.hdf5 [--repeats 10] [--guarantee-connectivity]
"""
import argparse
import math
import time
import faiss
import h5py
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
def level0_components(hnsw_index):
"""Strongly connected components of the level-0 graph (search follows out-edges)."""
h, n = hnsw_index.hnsw, hnsw_index.ntotal
nbrs = faiss.vector_to_array(h.neighbors)
offsets = faiss.vector_to_array(h.offsets).astype(np.int64)
nb0 = int(h.nb_neighbors(0))
cols = nbrs[offsets[:n, None] + np.arange(nb0)[None, :]].reshape(-1).astype(np.int64)
rows = np.repeat(np.arange(n, dtype=np.int64), nb0)
keep = cols >= 0
g = csr_matrix((np.ones(int(keep.sum()), dtype=np.int8), (rows[keep], cols[keep])), shape=(n, n))
count, labels = connected_components(g, directed=True, connection="strong")
return count, np.bincount(labels).max() / n
def recall(index, queries, gt, k, ef, repeats):
"""recall@k averaged over `repeats` passes; one query per call, single thread (like a search engine does)."""
params = faiss.SearchParametersHNSW(efSearch=ef)
threads = faiss.omp_get_max_threads()
faiss.omp_set_num_threads(1)
per_pass = []
for _ in range(repeats):
hits = 0
for i in range(len(queries)):
_, ids = index.search(queries[i:i + 1], k, params=params)
hits += len(set(ids[0][ids[0] >= 0]) & set(gt[i, :k]))
per_pass.append(hits / (len(queries) * k))
faiss.omp_set_num_threads(threads)
return float(np.mean(per_pass)), float(np.min(per_pass)), float(np.max(per_pass))
def build_cagra_hnsw(x, m, guarantee_connectivity):
n, d = x.shape
cfg = faiss.GpuIndexCagraConfig()
cfg.graph_degree = 4 * m
cfg.intermediate_graph_degree = 4 * m
cfg.build_algo = faiss.graph_build_algo_IVF_PQ
cfg.store_dataset = False
cfg.refine_rate = 1.0
cfg.guarantee_connectivity = guarantee_connectivity
build = faiss.IVFPQBuildCagraConfig()
build.n_lists = int(math.sqrt(n))
build.pq_dim = d // 4
build.pq_bits = 8
build.kmeans_n_iters = 20
build.kmeans_trainset_fraction = 0.1
build.force_random_rotation = True
build.conservative_memory_allocation = True
cfg.ivf_pq_params = build
search = faiss.IVFPQSearchCagraConfig()
search.n_probes = 5
cfg.ivf_pq_search_params = search
res = faiss.StandardGpuResources()
t0 = time.time()
gpu = faiss.GpuIndexCagra(res, d, faiss.METRIC_INNER_PRODUCT, cfg)
gpu.train(x) # builds the CAGRA graph on the GPU
cpu = faiss.IndexHNSWCagra()
cpu.base_level_only = True
cpu.hnsw.efConstruction = 512
cpu.hnsw.efSearch = 100
gpu.copyTo(cpu)
return cpu, time.time() - t0
def build_cpu_hnsw(x, m, ef_construction):
idx = faiss.IndexHNSWFlat(x.shape[1], m, faiss.METRIC_INNER_PRODUCT)
idx.hnsw.efConstruction = ef_construction
t0 = time.time()
idx.add(x)
return idx, time.time() - t0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("hdf5")
ap.add_argument("--k", type=int, default=600)
ap.add_argument("--ef-search", type=int, default=600)
ap.add_argument("--m", type=int, default=16)
ap.add_argument("--cpu-ef-construction", type=int, default=256)
ap.add_argument("--repeats", type=int, default=10)
ap.add_argument("--guarantee-connectivity", action="store_true")
args = ap.parse_args()
with h5py.File(args.hdf5, "r") as f:
x = np.ascontiguousarray(f["train"][:], dtype=np.float32)
q = np.ascontiguousarray(f["test"][:], dtype=np.float32)
gt = np.asarray(f["neighbors"][:, :args.k])
faiss.normalize_L2(x) # angular: cosine = inner product on normalised vectors
faiss.normalize_L2(q)
print(f"faiss {faiss.__version__}, GPUs {faiss.get_num_gpus()}, train {x.shape}, queries {q.shape}, k={args.k}, "
f"ef_search={args.ef_search}", flush=True)
rows = []
cagra, t = build_cagra_hnsw(x, args.m, args.guarantee_connectivity)
label = "CAGRA (IVF_PQ) -> IndexHNSWCagra" + (" + guarantee_connectivity" if args.guarantee_connectivity else "")
rows.append((label, t, *level0_components(cagra), *recall(cagra, q, gt, args.k, args.ef_search, args.repeats)))
del cagra
hnsw, t = build_cpu_hnsw(x, args.m, args.cpu_ef_construction)
rows.append((f"CPU IndexHNSWFlat (M={args.m}, efC={args.cpu_ef_construction})", t, *level0_components(hnsw),
*recall(hnsw, q, gt, args.k, args.ef_search, args.repeats)))
print(f"\n{'index':<58} {'build s':>8} {'L0 SCCs':>8} {'largest':>8} {'recall@' + str(args.k):>11} {'min..max over repeats':>22}")
for name, t, comps, largest, mean, lo, hi in rows:
print(f"{name:<58} {t:8.1f} {comps:8d} {largest:8.1%} {mean:11.4f} {lo:10.4f} .. {hi:.4f}")
if __name__ == "__main__":
main()setup_faiss_from_source.sh (faiss v1.14.3 + cuVS 26.08.01 as built by the OpenSearch remote-vector-index-builder)
#!/usr/bin/env bash
# Builds faiss + its Python bindings on this host the same way RVIB's base image does
# (remote-vector-index-builder/base_image/build_scripts/{Dockerfile,build-faiss.sh}), without Docker:
# Miniconda (pinned) -> conda packages (python 3.11, cmake 4.0.3, swig 4.0, gxx 14.2, libcuvs 26.08.01, cuda-nvcc 12.9)
# -> faiss submodule + RVIB patches 0001-0003 -> cmake/make with the image's flags -> python setup.py install
# -> RVIB core requirements, as in remote_vector_index_builder/core/Dockerfile.
# Usage: git clone --recursive https://github.com/opensearch-project/remote-vector-index-builder
# RVIB_DIR=./remote-vector-index-builder ./setup_faiss_from_source.sh (idempotent; log in ./setup-faiss.log)
# Env: RVIB_DIR (default ../remote-vector-index-builder), CONDA_DIR (default ../conda), JOBS (default 16),
# CUDA_ARCHS (default: the image's "80;86-real;120-real" plus 89-real for L4)
set -euo pipefail
HERE="$(cd "$(dirname "$0")" && pwd)"
RVIB_DIR="${RVIB_DIR:-$HERE/../remote-vector-index-builder}"
CONDA_DIR="${CONDA_DIR:-$HERE/../conda}"
FAISS_SRC="$HERE/faiss-src"
JOBS="${JOBS:-16}"
CUDA_ARCHS="${CUDA_ARCHS:-80;86-real;89-real;120-real}"
exec > >(tee -a "$HERE/setup-faiss.log") 2>&1
echo "== $(date -u) RVIB_DIR=$RVIB_DIR CONDA_DIR=$CONDA_DIR CUDA_ARCHS=$CUDA_ARCHS"
# 1. Miniconda, same pinned installer as the image
if [ ! -x "$CONDA_DIR/bin/conda" ]; then
wget -q https://repo.anaconda.com/miniconda/Miniconda3-py311_26.1.1-1-Linux-x86_64.sh -O /tmp/miniconda.sh
bash /tmp/miniconda.sh -b -p "$CONDA_DIR" && rm -f /tmp/miniconda.sh
fi
export PATH="$CONDA_DIR/bin:$PATH" CONDA_PLUGINS_AUTO_ACCEPT_TOS=yes
# 2. Conda packages, same pins as the image
if [ ! -f "$CONDA_DIR/.rvib-deps-done" ]; then
conda install -c conda-forge -y -q python=3.11 cmake=4.0.3 make=4.2 swig=4.0 "numpy>=2,<2.3" scipy=1.14 pytest=7.4 gflags=2.2
conda install -y -q -c conda-forge gxx_linux-64=14.2 sysroot_linux-64=2.28
conda install -y -q libcuvs=26.08.01 cuda-nvcc=12.9 cuda-version=12.9 -c rapidsai -c conda-forge -c nvidia
conda clean --all --yes
touch "$CONDA_DIR/.rvib-deps-done"
fi
# 3. faiss source at the submodule commit RVIB pins, with RVIB's patches (on a private copy)
git -C "$RVIB_DIR" submodule update --init base_image/faiss
if [ ! -f "$FAISS_SRC/.rvib-patched" ]; then
rm -rf "$FAISS_SRC" && cp -a "$RVIB_DIR/base_image/faiss" "$FAISS_SRC" && rm -rf "$FAISS_SRC/.git"
for p in 0001-Skip-copying-vectors-to-flat-storage-during-CAGRA-to.patch \
0002-Do-not-auto-widen-intermediate_graph_degree-when-eq.patch \
0003-faiss-1.14-cuvs-26.08.patch; do
(cd "$FAISS_SRC" && patch -p1 < "$RVIB_DIR/base_image/patches/$p")
done
git -C "$RVIB_DIR/base_image/faiss" rev-parse HEAD > "$FAISS_SRC/.rvib-patched"
fi
# 4. cmake + make, flags from build-faiss.sh. The image's /usr/local/cuda is a runtime-only base image, so its
# toolkit is conda's cuda-nvcc 12.9; point CMake at conda explicitly so the host's CUDA 13.2 is not picked up.
cd "$FAISS_SRC"
CUDACXX="$CONDA_DIR/bin/nvcc" cmake -B build \
-DBUILD_SHARED_LIBS=OFF -DFAISS_ENABLE_GPU=ON -DFAISS_OPT_LEVEL=generic -DFAISS_ENABLE_C_API=OFF \
-DFAISS_ENABLE_PYTHON=ON -DPYTHON_EXECUTABLE="$CONDA_DIR/bin/python" \
-DCMAKE_CXX_COMPILER="$CONDA_DIR/bin/x86_64-conda-linux-gnu-c++" \
-DCMAKE_CUDA_HOST_COMPILER="$CONDA_DIR/bin/x86_64-conda-linux-gnu-c++" \
-DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES="$CUDA_ARCHS" -DFAISS_ENABLE_CUVS=ON \
-DCUDAToolkit_ROOT="$CONDA_DIR" .
make -C build -j"$JOBS" faiss swigfaiss
(cd build/faiss/python && python setup.py install)
# 5. RVIB core Python deps (core/Dockerfile); lets a script import RVIB's own classes
pip install -q --upgrade -r "$RVIB_DIR/remote_vector_index_builder/core/requirements.txt"
python - <<'PY'
import faiss
print("faiss", faiss.__version__, "GPUs:", faiss.get_num_gpus(),
"guarantee_connectivity:", hasattr(faiss.GpuIndexCagraConfig(), "guarantee_connectivity"))
PY
echo "== done. Python: $CONDA_DIR/bin/python"Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsNeeds Triage
Activity
navneet1v commentedon Oct 28, 2026
Just to be fair, this issue description was created using LLM. I have tried to validate most of the things but feel free to ignore the Halucination.
The recall drop is real. Scripts and Product catalog dataset added can be used to repro the results.
Main ask here is:
What we can do to improve the recall here when Cagra graph needs to be converted to HNSW graph.
May be a wild Approach
One approach I was thinking which we benchmarked thanks to @naveentatikonda, was to build another layer 1 of HNSW and then add the layer 1 nodes links in layer 0 so that we can build the long range links which were not present in layer 0. This can bring back the HNSW behavior to some extent, but if we can do a similar step during the MST pass, that may be better since building another layer on top of layer 0, is expensive in some sense as that happens purely on CPU
Tagging : @cjnolet , @singhmanas1 , @divyegala , @tarang-jain .
[-][BUG] CAGRA graph built with IVF-PQ is disconnected on clustered data; `guarantee_connectivity` doesn't restore recall; NN-descent connectivity depends on stopping early[/-][+][BUG] CAGRA graph built with IVF-PQ is disconnected on clustered data; `guarantee_connectivity` doesn't restore recall[/+][-][BUG] CAGRA graph built with IVF-PQ is disconnected on clustered data; `guarantee_connectivity` doesn't restore recall[/-][+][BUG] CAGRA graph built with IVF-PQ is disconnected on clustered data leading to poor recall[/+]tfeher commentedon Oct 28, 2026
Thanks @navneet1v for filing the issue!
This is indeed a limitation of starting from a k-NN graph. The
guarantee_connectivityflag intends to fix the problem, but according to your tests it does not recover all the accuracy loss.An incremental insertion is probably helpful for such clustered dataset. CAGRA has an iterative build method which builds incrementally, and I would expect that it would be helpful. But it is not yet enabled through FAISS, and is slightly slower than the default build method.
There could be various ways to improve the MST step. We should investigate what works with a reasonable computation budget.
Yes, it would be useful to have such a check.
That is a good point, and could be a workaround. This should be benchmarked against alternative methods using iterative build or upgrades of the MST method.
navneet1v commentedon Nov 5, 2026
Thanks @tfeher for your response. I tried the test with building layer 1 and adding links back. Yes it is able to bring back most of the recall but the diff is still there, 3-4%. Which further is not helped by
HNSWCagraIndexusing random entry points.This is what I did after this:
Will keep on testing more to see what I can do. But I believe this is where Cagra Graph itself needs to become better.
mfoerste4 commentedon Nov 6, 2026
Hi @navneet1v , I agree and have been thinking about this issue. As @tfeher already mentioned, the current optimize code itself cannot recover from a disconnected knn input. Other available options fail for different reasons:
guarantee_connectivity / MST: The MST computation does not know the dataset and cannot add 'good' connections in between components w.r.t. distance. The connections that are picked make the graph technically connected, but they tend to be too far away to be considered during search. Even if we had a distance aware MST we would only get 1 bridge in between each cluster pair instead of many bridges to nearby clusters at cluster boundaries.
HNSW hierarchy: The Faiss code currently builds a flat HNSW index. I experimented with generating the hierarchy in order to reach multiple islands. While the upper layers do connect the islands, the search still only chooses and is limited by the most promising one.
Iterative CAGRA: While the hierarchical approach seems promising, the current implementation repeatedly replaces the graph edges from coarser level by fresh connections, which would then eventually also be bound to local components.
Random entry points
The alternative idea of better seeding to start off at multiple islands could also be an option, but it requires both samples covering each component and a large enough buffer/itopk to not reject the lead too early (which is what happens in HNSW I believe)
So what we really need in navigability on the base layer, not just connectivity. The proposed projection approach as implemented in your PR does directly address that as the numbers show.
mfoerste4 commentedon Nov 6, 2026
Looking forward, we will add a weak-component check (same as done in MST) after the optimize computation. In addition, we are currently evaluating ways to add bridge points within the cagra build in a performant way.
Fix HNSW GPU hierarchy copy dimension (#3029)
achirkin commentedon Nov 11, 2026
Here's a cheap complementary tweak to IVF-PQ to improve the connectivity of the intermediate graph #3018