Ginger is a C++ library for approximate nearest neighbor (ANN) retrieval using graph-structured indices. It delivers state-of-the-art performance on dense single-vector embeddings using dot product or squared L2 distance, and also supports arbitrary distance functions (BYOD). See the Ginger paper for details and benchmarks.
Query throughput relative to Hnswlib at 95% 10@10 recall (top left, higher is better) and memory footprint (graph and compressed vectors) relative to raw vectors (top right, lower is better) as the geometric mean across 14 datasets, alongside index construction time on MS-MARCO (bottom, lower is better). See the paper for details and the full experimental results.
- Extremely fast index builds with PiPNN: The PiPNN graph construction algorithm builds indices an order of magnitude faster than Vamana and other well-known libraries (such as DiskANN and HNSW), while achieving equivalent QPS-recall search performance.
- Approximate kNN graphs: PiPNN can also build approximate kNN graphs directly (see kNN Graph Construction).
- High retrieval quality at scale: Delivers state-of-the-art recall and speed on dense single-vector embeddings, scaling up to a billion vectors in memory on a single machine.
- Extreme compression without speed loss: Integrating graph indices with TurboQuant 4-bit quantization enables extremely fast distance computations. Rerank with either floats or 1–8 additional bits of precision.
- Flexible similarity functions: Easily extensible to custom distance metrics, currently providing native support for MIPS (dot product) and squared L2 distance.
The easiest way to get a good index is to start from the recommended configuration:
#include <memory>
#include <vector>
#include "absl/status/status_macros.h"
#include "ginger/ginger.h"
// vectors[i] and query are float vectors of length dim.
auto dataset = std::make_shared<ginger::SpanDataset>(num_points, dim);
for (int i = 0; i < num_points; ++i) dataset->Set<float>(i, vectors[i]);
ABSL_ASSIGN_OR_RETURN(
ginger::GingerSearcherConfig config,
ginger::RecommendGingerConfig(dim, ginger::SQUARED_L2,
ginger::kDefaultRobustPruneAlpha));
ABSL_ASSIGN_OR_RETURN(
std::unique_ptr<ginger::GingerSearcher> searcher,
ginger::GingerSearcherBuilder(config).AddDataset(dataset).Build());
// The 10 nearest neighbors, sorted by distance (lower = more similar).
// Increase beam_size for higher recall at the cost of latency.
ABSL_ASSIGN_OR_RETURN(
std::vector<ginger::DistanceAndId> neighbors,
searcher->FindNeighbors(query, searcher->DefaultSearchOptions(
/*num_neighbors=*/10, /*beam_size=*/64)));Ginger supports both CMake and Bazel (Bzlmod) builds.
- A C++20-compatible compiler (GCC 13+ or Clang 17+). When building against libc++, libc++ 19+ is required.
- Git (used to fetch dependencies when building from source)
- CMake 3.24+ (for CMake builds) or Bazel 8+ (for Bazel builds). Bazel
builds also need
cmakeandmakeinstalled, because the KaMinPar dependency is built with CMake.
For the best performance, link jemalloc into your
binaries, as the paper's benchmarks do. In CMake, pass
-DGINGER_USE_JEMALLOC=ON (this needs the jemalloc development package, e.g.
libjemalloc-dev). In Bazel, build with --config=jemalloc. In your own Bazel
project, add jemalloc to your MODULE.bazel and set --custom_malloc to it
instead (with -fno-exceptions, also copy the -fexceptions exemption from
Ginger's .bazelrc).
Configure and build the library, unit tests, and example binaries:
cmake -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -jRun the unit test suite via CTest:
ctest --test-dir build --output-on-failure -jRun the example binaries:
./build/ginger_example
./build/ginger_byod_example
./build/pipnn_knn_exampleTo use system-installed dependencies instead of fetching them, pass
-DGINGER_USE_SYSTEM_DEPS=ON. The build guide lists all
CMake options and shows how to add Ginger to your own CMake
project.
Build all targets and run unit tests using Bazel. Always pass -c opt; the
default fastbuild mode builds without optimizations and is far slower.
bazel build -c opt //...
bazel test -c opt //...Run the examples with Bazel:
bazel run -c opt //ginger/examples:ginger_example
bazel run -c opt //ginger/examples:ginger_byod_example
bazel run -c opt //ginger/examples:pipnn_knn_exampleThe build guide also shows how to add Ginger as a Bzlmod dependency.
The Quick Start above builds the index from the recommended configuration, which picks the graph algorithm, quantization and compression for you. These choices may change between releases. The recommended configuration supports float datasets only. The tuning guide explains each choice and how to change it.
A few things to know:
- Datasets can hold
float,int8_t, oruint8_tcoordinates. - Index construction runs in parallel on all cores. To use fewer threads, set
the
PARLAY_NUM_THREADSenvironment variable. FindNeighborsisconstand thread-safe, so multiple threads can query the same searcher concurrently.
To control each part yourself, write the configuration directly. This example builds a PiPNN graph, reorders and compresses it, and reranks with 2 extra TurboQuant bits per dimension:
#include "google/protobuf/text_format.h"
#include "ginger/ginger.h"
ginger::GingerSearcherConfig config;
google::protobuf::TextFormat::ParseFromString(R"pb(
distance_metric: SQUARED_L2
pipnn_config {
max_degree: 64
prune_config { alpha: 1.15 }
leader_selection { fanout_sequence: [ 10, 3 ] }
}
use_graph_compression: true
reordering_algorithm: RECURSIVE_GRAPH_PARTITIONING
turbo_quant { seed: 42 extra_bits: 2 } # 4+2 = 6 bits/dim
)pb", &config);
ABSL_ASSIGN_OR_RETURN(
std::unique_ptr<ginger::GingerSearcher> searcher,
ginger::GingerSearcherBuilder(config).AddDataset(dataset).Build());
ginger::SearchOptions options;
google::protobuf::TextFormat::ParseFromString(R"pb(
search_space: SEARCH_SPACE_TURBO_QUANT
reranking_strategy: RERANKING_STRATEGY_TURBO_QUANT_EXTRA_BITS
beam_size: 64
num_neighbors: 10
)pb", &options);
ABSL_ASSIGN_OR_RETURN(std::vector<ginger::DistanceAndId> results,
searcher->FindNeighbors(query, options));To build a Vamana graph instead, set vamana_config in place of
pipnn_config. See pipnn/config.proto and
vamana/config.proto for all options.
ginger/io/io.h stores each index in a single file:
#include "ginger/io/io.h"
// The parent directory ("/path/to/dir") must already exist.
const std::string path = "/path/to/dir/my_index";
ABSL_RETURN_IF_ERROR(ginger::io::SaveGingerSearcher(*searcher, path));
ABSL_ASSIGN_OR_RETURN(std::unique_ptr<ginger::GingerSearcher> loaded_searcher,
ginger::io::LoadGingerSearcher(path));To save the index without its dataset and attach your existing dataset at load time, see the serialization guide.
ginger_example: Builds aGingerSearcherover synthetic vectors and runs nearest-neighbor queries.ginger_byod_example: Builds a Vamana index and runs beam search with a custom distance callback.pipnn_knn_example: Builds an approximate k-NN graph with PiPNN, without a search index.
The ginger package wraps the searcher and the kNN graph construction for
numpy arrays. It is built from source, so it needs the
prerequisites of the CMake build, and it currently supports
Linux.
pip install .import numpy as np
import ginger
data = np.random.default_rng(0).standard_normal((10_000, 64), np.float32)
# Build a searcher with the recommended configuration and query it.
searcher = ginger.build(data, ginger.SQUARED_L2)
ids, distances = searcher.search(data[:5], k=10, beam_size=64)
searcher.save("/tmp/index.ginger")
searcher = ginger.load("/tmp/index.ginger")
# The 15 nearest neighbors of every point, without building a searcher.
ids, distances = ginger.build_knn_graph(data, ginger.SQUARED_L2, k=15)Arrays must be C-contiguous float32 arrays; they are passed to Ginger as they
are and never converted. help(ginger) documents every function.
- Threads. Builds and batched searches run on Ginger's worker threads,
one per CPU by default. Set the environment variable
PARLAY_NUM_THREADSto limit their number. The calls release the GIL. - Processes. Ginger's worker threads do not survive
fork(). Do not use the package in a process forked from one that has already used it; start worker processes with thespawnorforkservermethod instead.
Compresses float vectors to 4 bits/dim for extremely fast distance computations;
decodes on-the-fly using in-register table lookups and fast dot product instructions
(e.g., VNNI's vpdpbusd).
- Extra precision (4+k): 1, 2, 3, 4, 6, or 8 additional bits per dimension for higher-accuracy reranking. Disaggregated storage retains 4-bit scoring speed.
- TurboSlice: Score a prefix of dimensions for even faster pruning, then
full-length distance computation on survivors. Enable via
turbo_quant.set_turboslice_dimensionality(...).
Reduces dimensionality before TurboQuant quantization to save memory and speed up
search. Configure via config.mutable_pca().
- Fixed target dimension, or variance-based truncation (e.g., preserve 90% variance).
- Projection matrix can be stored as float32 or quantized with TurboQuant.
Two algorithms for building the search graph:
- PiPNN (paper): Recursive partitioning → leaf kNN graphs → HashPrune + RobustPrune. Extremely fast build (significantly faster than Vamana and HNSW) with equivalent QPS-recall search performance to Vamana. Recommended for fast index construction.
- Vamana (DiskANN, ParlayANN): Incremental batch-insert with beam search + RobustPrune.
The index construction guide explains the parameters of both.
BuildPipnnKnnGraph (pipnn/pipnn_knn.h) builds an approximate directed kNN
graph with PiPNN's partitioning, without building a search index. This is
useful for clustering, graph mining, or as input to other graph algorithms.
Candidates are scored on 4-bit TurboQuant codes and can be reranked with float
or extra-bit distances. See the pipnn_knn_example binary.
- FlatGraph: Contiguous degree+neighbors per node. Cache-friendly.
- CompressedCSRGraph: Stores each sorted neighbor list as variable-length
encoded gaps with the SIMD-decoded AdaptiveGap codec. Best for memory
footprint. Enable with
config.set_use_graph_compression(true), together with a node reordering (config.set_reordering_algorithm(...)) to shrink the gaps.
The graph storage guide compares the formats, reordering algorithms, and codecs.
GingerSearcher::FindNeighbors supports multi-stage retrieval: graph traversal
over TurboQuant codes or raw vectors, followed by optional reranking with floats
or extra TurboQuant bits. All search parameters are set in SearchOptions (see
searcher.proto). Tune beam_size to trade latency for
recall. The search guide covers each option.
| Metric | Enum | Notes |
|---|---|---|
| Dot product | DOT_PRODUCT |
Negative dot product used as distance. Lower = more similar. |
| Squared L2 | SQUARED_L2 |
Recommended for unit-normalized data. |
There is no default metric: Build() returns an error if distance_metric is
not set.
For distance functions not built into GingerSearcher, you can use the lower-level
BuildVamanaIndex and NavigationBeamSearch APIs directly. Both accept a
compute_distances callback that you implement with any distance logic. Set
nonpositive_distances in the prune config to match the sign of your
distances: true for distances <= 0 (e.g., negative dot product), false for
>= 0. See the ginger_byod_example binary for a
complete runnable example.
- Index updates
- Filtered search
- Multi-vector search
- Ginger: arXiv
- TurboQuant: ICLR '26 / arXiv
- PiPNN: KDD '26
- ParlayANN: PPoPP '24
- Vamana / DiskANN: NeurIPS '19
- Recursive Graph Partitioning (KaMinPar): ESA '21
- Recursive Graph Bisection: KDD '16
If you use Ginger in your research, please cite:
@article{salwasser2026ginger,
title = {{GINGER}: Spicing Up Graph-Based Vector Search},
author = {Salwasser, Daniel and Gottesb{\"u}ren, Lars and Dhulipala, Laxman and {\L}{\k{a}}cki, Jakub and Blelloch, Guy and Jayaram, Rajesh and Rubel, Tobias and Sheth, Kshiteej and Zandieh, Amir and Mirrokni, Vahab},
journal = {arXiv preprint arXiv:2611.08306},
year = {2026}
}
Apache 2.0, see LICENSE. See CONTRIBUTING and SECURITY.md for contributions and security reports.
This is not an officially supported Google product.
