Multi-bit rotated residual quantization

IVF-RQ

Partition vectors with IVF, spread each residual through a deterministic orthogonal transform, and store centered scalar levels as bit planes. A cheap sign-plane estimate rejects weak candidates before the remaining planes are evaluated.

4 bits / dimension by default1–8 build-time bitstwo-stage scanMagic: IVRQ

Positioning and trade-offs

Default codepadded_d / 2 bytes
Per-vector factors5 × f32
Learned modelIVF centroids only
DimensionAny positive value

Good fit

  • You need smaller codes than IVF-SQ while meeting the measured recall target.
  • Training time and model complexity should stay close to IVF-FLAT.
  • The source supports one concurrent multi-range read for selected lists.
  • Approximate in-list ranking is acceptable and measured against real ground truth.

Poor fit

  • Raw-vector or exact reranking accuracy is mandatory.
  • Sub-millisecond local latency matters more than 0.90-class recall.
  • The collection is highly mutable; this implementation writes immutable files.
  • Resident PQ tables and lower recall are acceptable in exchange for a still smaller IVF-PQ index.
Why it remains IVF-RQThe public index family name is unchanged. The pre-release 1-bit/query-bit experiment was replaced completely: bit width is now a property of persisted data, not a per-query switch.

Design and distance estimation

1

Train and assign IVF

Learn nlist coarse centroids and form r = x − c.

2

Rotate deterministically

Pad to a multiple of 64, then apply four rounds of random signs, 64-wide normalized FHT, and seeded permutation. The transform is orthogonal and reconstructed from the header seed.

3

Quantize centered levels

Choose 1–8 bits. Below 256 padded dimensions, retain the original three-round scale refinement. At 256 or more, compare max-based and Gaussian-clipping starts and keep the best-aligned code, including the original candidate. Store levels MSB first as bit planes.

4

Estimate in two stages

The MSB sign plane and its three factors produce an estimate plus a deterministic reconstruction-error bound. Only candidates whose lower bound can enter Top-K reach the remaining planes. Dense surviving blocks use quantized-LUT SIMD for those planes too; candidates that can still enter Top-K receive the original F32 full estimate. Error intervals use F64 accumulation, F32 rounding guards, and outward-rounded estimator endpoints.

5

Scan blocked data

Codes and factors are transposed within 32-vector blocks. The rotated query and byte LUT are built once and reused across every selected list.

The full estimator is exact for a query equal to the encoded source vector, while ranking other vectors through the scaled reconstruction. L2, inner product, and cosine have metric-specific additive/rescale factors; cosine inputs are normalized before IVF assignment.

Usage

Java · build and query
Map<String, String> options = new HashMap<>();
options.put("index.type", "ivf_rq");
options.put("dimension", "128");
options.put("nlist", "1024");
options.put("rq.bits", "4"); // optional; 4 is the default
options.put("metric", "l2");
// options.put("ivf.coarse-assignment", "exact"); // optional; default auto

try (VectorIndexTraining training =
             VectorIndexTrainer.train(options, trainingVectors, trainingCount);
     VectorIndexWriter writer = new VectorIndexWriter(training)) {
    writer.addVectors(rowIds, vectors, vectorCount);
    writer.writeIndex(vectorIndexOutput);
}

try (VectorIndexReader reader = new VectorIndexReader(vectorIndexInput)) {
    VectorSearchResult result =
            reader.search(query, new VectorSearchParams(10, 64));
    int storedBits = reader.metadata().rqBits();
}
Rust · configuration
let config = VectorIndexConfig::IvfRq {
    dimension: 128,
    nlist: 1024,
    bits: 4,
    metric: MetricType::L2,
    use_approximate_coarse_assignment: true,
    ivf_train_max_points_per_centroid: 256,
};
let params = VectorSearchParams::new(10, 64);

Estimated-distance range search

The Rust VectorIndexReader and IVFRQIndexReader support single/batch range search, with or without a serialized Roaring allow-list, using the shared DistanceBand, RangeSearchParams, and RangeSearchResult. L2, cosine and inner product are supported with fixed positive nprobe. Cosine normalizes queries before probe selection and rotation; each metric uses its own query terms and stored factors. Returned scores remain internal distances, not public inner-product similarities. See the shared usage examples.

Each eligible row is evaluated using its one-bit estimate or full multi-bit estimate from all stored bit planes. Membership is the half-open test lower <= estimate < upper, not a comparison against the original vector's exact distance. Negative estimates remain negative. Quantization can cause both missing rows and extra rows relative to an exact-distance band, even with every list probed.

Unlike top-K, range search does not use the coarse error-bound or quantized FastScan pruning stages: those do not certify membership in an estimate band. It uses F32 lookup sums for every allowed row, then hands the estimate to the shared collector. Probe selection computes direct L2 distances to every centroid, rejects non-finite values, and reuses selected distances in the estimate. A bounded candidate buffer uses O(nprobe) distance-selection storage per query, without skipping distance validation for unselected centroids. This range-only path uses the same calculations for single and batch queries, rather than top-K's SGEMM probe optimization. Lists are read once per call and shared across queries; sufficiently large scans run in parallel. Results have no fixed-K truncation, padding, or ordering guarantee.

Range statistics are returned with the result. rows_scanned counts filter-eligible rows, early_abandoned is zero, and list_reads counts unique non-empty lists. The last top-K statistics and all existing top-K behavior are unchanged. No storage-format change or C/JNI range binding is introduced.

Correctness is relative to the estimateTests compare range output against an independently accumulated estimated-distance oracle; they do not establish exact-distance recall guarantees. The Top-K recall and throughput measurements on this page are not range-search measurements. Use IVF-FLAT with full probing or an exhaustive raw-vector scan when exact, complete membership is required.

Parameters

ParameterRequirement / defaultPurposeGuidance
dimensionInferred by Java/Python one-shot training; otherwise > 0Logical vector dimensionStorage pads internally to a multiple of 64.
nlistAuto from expected-vector-count, or explicit > 0IVF partition countCompare the resolved value with the same IVF-FLAT baseline.
rq.bits1–8; auto from max-bytes-per-vector, otherwise 4Persisted residual level widthHigher values increase recall, file bytes, I/O, and scan work linearly.
metricRequiredL2 / inner product / cosineSemantic, not inferred; fixed in the file.
ivf.train.max-points-per-centroidPositive integer; default 256Maximum training vectors per coarse centroidCaps coarse K-means input at nlist × value vectors, including hierarchical clustering stages.
ivf.coarse-assignmentauto by default; optional exactControls build-time list assignmentauto uses Vamana when dimension × nlist ≥ 1,000,000, trading build speed for possible low-nprobe recall loss and graph startup cost; exact disables it.
nprobeAutomatic by default; explicit expert overrideLists probedAuto accounts for K, average list size, and filter selectivity.

Larger training samples increase training work and may improve centroid quality. These limits apply within the Trainer reservoir of max(65536, 64 × nlist) vectors; increasing them does not enlarge that reservoir. See the shared training options for sampling and Paimon integration details.

No query-side bit widthThe Reader always evaluates the representation stored in the file. Changing rq.bits requires rebuilding the index; this keeps one file's accuracy and cost contract stable.

Public-corpus measurements

11 November 2026: benchmark-gated optimization

Release builds with Rust 1.95 on Apple M4 Pro (48 GiB, 12 Rayon workers), full public corpora, 1,000 held-out queries, Top-10, nlist=1024, nprobe=64, four stored bits, and warm APFS pages. Each value below is a three-process median from alternating baseline/candidate runs against baseline b083416. QPS and P95 use the benchmark's warm timing phase. SIFT and GIST contain one million rows; normalized GloVe-100 contains 1,183,514. GIST query comparisons reuse separately built baseline and new-encoder files; their zero build-time CSV fields are not construction measurements.

DatasetRecall@10, before → afterBatch QPS, before → afterBatch gainSequential P95, before → after
SIFT1M, 128d0.9148 → 0.91482,857 → 4,07842.7%1.048 → 1.004 ms
GIST1M, 960d0.9039 → 0.9153421 → 2,7656.57× throughput4.943 → 2.545 ms
GloVe-100, 100d0.8203 → 0.82032,650 → 2,7865.1%1.028 → 1.009 ms

The high-dimensional encoder has a build trade-off: an independent three-build GIST A/B raised recall by 1.14 percentage points at unchanged file size, with median add time increasing from 5.339 to 5.797 seconds. Below 256 padded dimensions, the new scale search was removed because recall gains were small or inconsistent; original codes are retained. The scan changes preserve the original full F32 estimate of each stored row.

Filtered same-file A/B runs used 100 public queries and independently recomputed filtered ground truth, again with three-process medians. At 1% allow-list density, batch throughput improved by 14.7% / 41.8% / 16.0% on SIFT/GIST/GloVe. At 50%, GIST improved from 451 to 1,616 QPS (3.58×), while SIFT and GloVe were effectively unchanged. Every paired filtered recall was unchanged. Dense filtering does not establish a speedup for the low-dimensional path.

Two experiments were removed. SIMD lower-bound arithmetic did not improve throughput consistently across all three shapes. A v1 staged sign/ex read prototype was verified query-by-query on 100 SIFT and GloVe queries but changed one read round into three: SIFT local P95 rose from 1.012 to 12.320 ms while bytes fell only 0.07%; fixed-2-ms P95 rose from 5.247 to 19.804 ms, and fixed-20-ms P95 from 20.979 to 72.315 ms. These remote cases are latency models, not live object-store measurements.

Offline calibration also has a concrete cost trade-off. With the first 200 SIFT queries selecting parameters and the remaining 800 used only for three-run validation, tools/tune_ivfrq.py selected 5 bits / 32 probes for a 0.90 recall target. Held-out recall improved from 0.9161 to 0.9365, batch QPS from 3,866 to 5,758, and P95 from 1.009 to 0.707 ms; file size grew from 86.3 to 102.3 MB. This does not change library defaults. Compare options at the application's recall and storage target.

Combined build, storage-model and compatibility recheck

The combined three-optimization version was rebuilt against the same ann_bench source as baseline b083416, with both dependency graphs pinned to the repository lock file. Three alternating process pairs each built a complete index, then queried that same file under local warm disk, injected 2 ms latency and the 20 ms object-store model. Settings remained four stored bits, nlist=1024, nprobe=64, 65,536 training vectors, 1,000 queries, Top-10 and 12 Rayon threads. No filter or offline-calibrated parameter change is used in this main matrix.

DatasetRecall@10, before → afterTotal buildTrainAdd / encodeWrite + sync
SIFT1M0.9148 → 0.91481.092 → 1.117 s204 → 207 ms751 → 784 ms118 → 134 ms
GIST1M0.9039 → 0.91538.151 → 7.602 s1442 → 1423 ms5836 → 5604 ms590 → 573 ms
GloVe-1000.8203 → 0.82031.085 → 1.049 s153 → 153 ms794 → 775 ms127 → 124 ms

Each column is medianed independently, so stage medians need not add to the total median. Build times remain of the same order; their overlapping sample ranges do not establish a consistent construction speedup. Recall is identical across all three storage models within each version.

DatasetStorage modelSingle-query P95, before → afterBatch QPS, before → after
SIFT1MLocal warm disk1.056 → 3.138 ms2,885 → 3,804
SIFT1M2 ms injected5.168 → 4.809 ms2,743 → 3,499
SIFT1M20 ms model21.066 → 21.923 ms2,496 → 3,319
GIST1MLocal warm disk6.431 → 2.835 ms396 → 2,626
GIST1M2 ms injected8.097 → 5.232 ms403 → 2,489
GIST1M20 ms model25.799 → 22.680 ms342 → 1,768
GloVe-100Local warm disk1.054 → 1.028 ms2,756 → 3,026
GloVe-1002 ms injected6.238 → 6.191 ms2,771 → 2,821
GloVe-10020 ms model21.042 → 21.038 ms2,592 → 2,674

These are the first complete sequential sweep and one 1,000-query batch, rather than the optional steady timing phase reported above. SIFT optimized local P95 varied from 1.013 to 4.426 ms across the original three runs; the 3.138 ms median is retained in the table. A separate three-pair, same-file warm control measured 1.200 → 1.061 ms for sustained sequential P95 and did not reproduce a stable regression. Low-dimensional tail latency is therefore less conclusive than throughput. Query bytes and dependent read rounds were unchanged: one round per query, averaging 5.81 / 38.81 / 6.18 MB for SIFT/GIST/GloVe.

The 2 ms case actually sleeps per positional-read call and includes operating-system timer and scheduling overhead. The 20 ms case computes sequential latency as measured CPU/I/O time plus 20 ms per dependent round; batch timing injects the sleep. Neither models live object storage, bandwidth, retries or throttling.

Storage compatibility verified in both directions. Header, write, metadata-read and payload-decode code is unchanged; v1 retains its 64-byte header, required flags, rotation type 2 and factor layout 3. Both versions passed the existing golden fixtures. A separate old/new writer-reader matrix generated 144 files covering bits 1–8, L2/IP/cosine, dimensions 70/256/960, signed row IDs, partial 32-row blocks and zero queries. All 288 reader/file checks matched Top-K and complete estimated-distance digests. All 72 paired headers and file lengths matched; 37 paired payloads changed, demonstrating compatibility with new encoded content rather than merely identical old bytes.

Actual million-row GIST cross-reading also passed: the old Reader reading the new file retained Recall@10 0.9153, and the new Reader reading the old file retained 0.9039. Existing v1 indexes need no migration to obtain scan/filter improvements. The new high-dimensional scale search affects newly built codes, so its recall improvement requires rebuilding; the resulting file remains readable by the old Reader.

25 July 2026 historical measurements

Apple M4 Pro, 12 Rayon workers, one million base vectors, 1,000 published queries, nlist=1024, nprobe=64, Top-10, warm APFS pages. Times are release-build measurements from 25 July 2026.

DatasetBuildFileRecall@10Local P95Local batch QPSRead / query
SIFT1M, 128d3.92 s86.3 MB0.91481.20 ms3,0745.81 MB
GIST1M, 960d23.5 s505.8 MB0.90394.41 ms44438.81 MB
GloVe-100, 100d4.03 s102.1 MB0.82031.23 ms2,9176.18 MB

On SIFT1M, a controlled bit sweep produced Recall@10 0.7233 / 0.8365 / 0.9149 / 0.9530 / 0.9731 for 2 / 3 / 4 / 5 / 6 bits. The compact v1 factor layout removes four unused bytes per row, reducing the corresponding files from 58.3 / 74.3 / 90.3 / 106.3 / 122.3 MB to approximately 54.3 / 70.3 / 86.3 / 102.3 / 118.3 MB without changing the distance estimator. Four bits is the first point above 0.90 and is therefore the default.

GIST1M storage modelRecall@10P95Batch QPSQuery rounds
Warm local storage0.90394.41 ms4441
Remote cache, fixed 2 ms0.90397.80 ms4341
Object store, fixed 20 ms0.903924.34 ms3921
What changed in this runRows are assigned to IVF lists once, then independent lists are encoded in parallel with task-local residual, rotation, code, and factor scratch. The unfiltered scan removes the per-lane filter test from coarse-code accumulation, and the final estimator checks the Top-K threshold before entering the duplicate-aware heap. Relative to the immediately preceding same-machine build, add time fell 39% / 45% / 42% on SIFT/GIST/GloVe; a strict GIST same-file query A/B improved batch time by 8.7%. Rebuilt file hashes match the serial baseline exactly, so these are execution-path changes rather than a format or estimator change.

The fixed-latency rows model one concurrent multi-range round and do not model bandwidth, retries, TLS, or throttling. Batch QPS is one 1,000-query call, not independent clients.

v1 storage layout

64 B headerShape, bits, transform, layout
IVF centersnlist × d × f32
Offset tablenlist × 16 B
ListsIDs + blocked planes + blocked factors

The header records logical and padded dimensions, metric, required layout flags, persisted rq.bits, total vectors, rotation seed/rounds, plane bytes, rotation type 2, and compact factor layout 3. Every non-empty list begins with base_id, encoded-ID length, and code length, followed by sorted delta-varint IDs.

Within each 32-vector block, bytes are ordered by plane, byte position, then lane. For more than one bit, the five structure-of-arrays fields are coarse (f_add, f_rescale, f_error) followed by full (f_add, f_rescale). The omitted full error was never read: the full estimate is the final ranking stage and does not produce another lower bound. Readers reject the old pre-release layouts rather than guessing their meaning.

Open-source cross-checkFaiss IVFRaBitQ FastScan also groups database vectors in 32-lane blocks and separates RaBitQ correction factors from packed codes. Lance's RaBitQ kernels likewise use blocked multi-bit codes and architecture-specific dot products. The v1 plane/byte/lane layout and SoA factors already preserve the important scan locality, while sorted delta-varint row IDs avoid fixed-width ID overhead. AVX2 and NEON evaluate the sign plane with quantized nibble LUTs for full blocks at 256 or more padded dimensions. Filtered blocks also use this path when at least eight rows are eligible; empty blocks are skipped. With at least four surviving rows, the remaining planes use the same SIMD kernel before final F32 scoring. Sparse survivors retain scalar byte lookups. Quantization and floating-point accumulation errors are included in outward-rounded pruning bounds; final estimates keep their original F32 operation order.
Why the remaining factors stay F32Faiss additive quantizers can encode norms with qint8 or qint4. IVF-RQ cannot apply that choice blindly to its coarse factors: their error term makes the first-stage lower bound conservative, and inward rounding could incorrectly prune a true Top-K candidate. v1 takes the lossless 4-byte saving by deleting only the unused final-stage error; lower-precision factor encodings remain gated on a proof-preserving rounding rule and public-corpus recall data.
I/O contractOpen reads the 64-byte header once. Resident initialization reads centroids plus the offset table in one contiguous round. Search groups selected list payloads into at most 64 MiB per round and also honors SeekReadCapabilities.max_ranges_per_pread. Each returned payload remains the backing allocation for its blocked codes, so the reader decodes only IDs and factors instead of copying the usually much larger code region.

Capacity estimate

Approximate default size64 + 4×nlist×d + 16×nlist + N×(4×padded_d/8 + 20) + encoded_ids

For one bit, only the two estimate factors are stored, so the factor term is 8 bytes. For 2–8 bits it is 20 bytes. The formula excludes small per-list headers and delta-varint ID variability.

Tuning order

  1. Run IVF-FLAT with the target nlist/nprobe to establish the partition recall ceiling.
  2. Start IVF-RQ at the default four bits.
  3. If recall is low for both indexes, increase nprobe. If only IVF-RQ is low, try five bits before increasing I/O through more lists.
  4. Compare the current IVF-SQ recall and scan results when one byte per dimension fits; compare IVF-PQ when minimum size matters.
  5. Validate the final choice on a public or production corpus, including batch and the real storage adapter.

Implementation boundaries

  • The file is immutable; updates require a new index file.
  • Distances are approximate and raw vectors are not retained for exact reranking.
  • Four transform rounds and compact factor layout 3 are fixed for v1; readers reject other values.
  • Batch scan parallelism uses Rayon while sharing each loaded list payload across queries; a single query also scans independent lists in parallel once its candidate count reaches 8,192.
  • optimize_for_search() loads and validates resident metadata; it does not change search results.