RaBitQ Library 0.9.0¶
This release removes the Python forms that 0.8 deprecated, saves every index in index format 2, adds the cosine metric and 64-bit IDs, and adds C++ index classes that match the Python API. Index files from every earlier release still load; files saved by 0.9 need 0.9 or later.
Index files¶
- IVF-RaBitQ, HNSW-RaBitQ and SymphonyQG
savewrite index format 2, a single file with a header, a section table and checksummed metadata. - Releases up to 0.8 cannot read these files. Keep a copy saved by 0.8 if you may downgrade.
- Files written by every earlier release still load, including the
.hnswsidecars of HNSW-routed IVF files. Saving one writes format 2 with the same rotation, codes and results. - IVF-RaBitQ stores HNSW centroid routing inside the file, so
saveno longer writes a<file>.hnswsidecar. A sidecar left by an earlier save is not removed. - The saved bytes now include that routing graph. It is reproducible only when
train,set_centroidsor the firstaddbuilds it withnum_threads=1. Saving the same index twice still gives identical files. saverejects IVF-RaBitQ indexes of more than 65,536 dimensions.- A format-2 file that uses read-only-compatible features unknown to this release loads for search only: operations that change or save the index raise. A new index built from the original data is writable.
Removed and renamed Python forms¶
0.9 removes every Python form that 0.8 deprecated. The migration guide lists each replacement; all of them work in 0.8.5, where the old forms warn.
- The 0.7 call forms, deprecated since 0.8.0 (#213):
IvfIndex(dim, max_elements, num_clusters, nbits, ...),HnswIndex(dim, max_elements, ...)and itsrandom_seed=, andSymqgIndex(dim, max_degree, metric, quantization_bits)and itsquantization_bits=;build()andis_builton every index, andSymqgIndex.search_batch()andSymqgIndex.quantization_bits;cluster_ids,num_threadsandfast_quantizationpassed toaddby position.- The 0.8 index spellings, deprecated since 0.8.5 (#232):
max_elements: readcapacityonHnswIndexandnum_stored_pointsonIvfIndexandSymqgIndex;HnswIndex.resize(n): callreserve(n), which only grows the capacity;IvfIndex.reserve(cluster_id, num_points): callreserve_cluster;IvfIndex(initializer=...)andindex.initializer: userouting;search(queries, k, ef=...)onHnswIndexandSymqgIndex: useef_search=;high_accuracyandnum_threadspassed tosearchby position: they are keyword-only, and onlynprobeoref_searchstays positional;nprobe=0andef_search=0for the default: they raiseValueError, andNoneselects the default.num_threads=0still means every available CPU;HnswIndexseeds above2**32 - 1: they raiseValueError, as on the other two classes.- The 0.8 k-means spellings, deprecated since 0.8.5 (#233):
QGKMeansandQGKMeansParameterstakenbits(32, 4 or 8),max_degreeandef_constructioninstead ofquantization_bits(0, 4 or 8),graph_degreeandef_build;final_assignmentis'approximate'or'exact', also onindex.cp, and reads back as that string.FinalAssignmentModeis no longer in the package;KMeansIterationStatsis the only name of the statistics class;QGKMeansIterationStatsandRaBitQKMeansIterationStatsare no longer in the package.- A removed call form of an index raises
TypeError, and a removed attribute or nameAttributeError(ImportErrorwhen imported), as does a removedQGKMeanskeyword, like any unknown keyword there; none is read as a different call. For example,IvfIndex(dim, 1000, 64)is an error, not an index with 1000 clusters. - Changes that 0.8.5 could not announce with a warning:
metric="innerproduct"raisesValueErroron the index classes and inrabitqlib.quant. Use"ip", which every release accepts and themetricproperties return.HnswIndex()withoutseed=draws a seed, asIvfIndexandSymqgIndexdo, instead of using 100.index.seedreports it; passseed=, andnum_threads=1toadd, for a reproducible build.repr(index)printscapacity=forHnswIndexandrouting=forIvfIndex, and no longer printsmax_elements=forIvfIndex.- The index classes are now the extension's own, without replaced methods:
- A wrong argument raises pybind11's
TypeError, which lists the supported signature. Messages such asIvfIndex() got an unexpected keyword argument 'x'are gone. inspect.signature()no longer works on the index constructors and methods;help()and the type stubs describe them.- k-means messages name the new parameters:
QGKMeans nbits must be 4, 8, or 32,QGKMeans max_degree must be a positive multiple of 32,QGKMeans requires more centroids than max_degreeandQGKMeans ef_construction and ef_search must be positive. As for the other parameters,trainreports an invalidnbits; 0.8.5 rejected it when it was set. - txtai 9.14.0, the first txtai release with a RaBitQ backend, uses the 0.7 forms and fails with this release. It also filters results with
uid != 0xFFFFFFFF, which no longer matches a missing result (seeint64IDs below). txtai 9.15.0, the first release with neuml/txtai#1616, works with this release and with 0.8.5 (#213). With txtai 9.14.0, keeprabitqlib<0.9.
Python changes¶
- New
metric="cosine"forIvfIndex,HnswIndexandSymqgIndex(#212). The index scales data, queries and centroids passed toset_centroidsto unit length and returns1 - cos; results equal those of ametric="ip"index built from the scaled vectors and given the scaled centroids (#259). A zero vector stays zero, so its true distance to every vector is 1. The saved file records the metric, so a loaded index keeps scaling.index.metriccan now return"cosine", and an invalid metric raisesmetric must be 'l2', 'ip' or 'cosine'. See the cosine metric. - Point IDs are
int64at the Python boundary (#211): searchreturnsint64IDs, and slots without a neighbor hold-1instead of2**32 - 1; their distance is stillinf. Code that compares IDs with2**32 - 1,0xFFFFFFFFornp.iinfo(np.uint32).maxmust change;np.isfinite(distances), recommended since 0.8.2, works before and after.addreturnsint64IDs.removealready took any integer IDs and still rejects-1and other out-of-range values without removing anything.-
IDs remain the row numbers the index assigns. The C++
IvfIndex,HnswIndexandSymqgIndexuse 64-bitrabitqlib::Idvalues withkNoId(-1) for a missing result, as Python does. The indexes still hold 32-bit row numbers inside, so they keep their limit of 2^31 points; the unsupportedivf::IVF,hnsw::HierarchicalNSWandsymqg::QuantizedGraphkeepPIDandkPidMax. -
An
IvfIndex,HnswIndexorSymqgIndexcall with both an invalid argument and the wrong state may now report the argument first, for exampleValueErrorfornprobe=0on an untrained index, which raisedRuntimeError, or for data of the wrong dimension passed toSymqgIndex.addafter the graph is built.HnswIndex()with an invalidmetricorseedand an out-of-rangenum_clustersnow reports the metric or seed.SymqgIndex()with an invalidinitand an invaliddim,nbitsormax_degreenow reports theinit, and with an invalidseedand an invaliddim,nbits,max_degreeoref_constructionthe seed. -
k-means training accepts every coordinate that
addandsearchaccept. For many dimensions, including 64, 100, 256, 960 and 1024,trainandassignofQGKMeansandRaBitQKMeans, andtrainand the firstadd, which trains, ofIvfIndexandHnswIndexrejected a coordinate whose magnitude equals the float32 coordinate bound withexceeds the safe float32 coordinate range, although a trained index accepted it. The C++rabitqkmeans::RaBitQKMeansandqgkmeans::QGKMeanschange the same way. -
Loading a format-2 file keeps the
seedof every index, andef_constructionandinitof SymphonyQG. They wereNoneafterload, and still are for files from releases up to 0.8. - With a recorded seed,
cp.seedafterloadfollows it as for a new index; for an HNSW-RaBitQ file whose seed exceeds 32 bits, which only C++ can write, it is the low 32 bits. It was the k-means default. - An HNSW-RaBitQ file saved before training, which the C++ API of earlier releases allowed, loads untrained, with
num_clusters16. Without a recorded seed its firstaddcannot train it, soadd,search,removeandsaveraiseRuntimeError: HnswIndex loaded from an untrained file must be trained before add; call train or set_centroids(naming the operation) untiltrainorset_centroidsruns. - A new exception,
rabitqlib.FormatError, subclasses bothValueErrorandRuntimeError: - Every index
loadraises it for a truncated, corrupt, mismatched or unsupported file, in format 2 and in every earlier layout. These wereRuntimeError, which still catches them. A file that cannot be opened still raises a plainRuntimeError. quant.FormatErroris now the same class. It was a subclass ofValueErroronly, which still catches it.- Messages for damaged or mismatched files change:
- A format-2 file names the problem, for example
IVF index file is 6916 bytes, but its sections end at 6852for trailing bytes. - Errors in an HNSW routing graph name the graph rather than the sidecar:
Truncated HNSW centroid graphandHNSW centroid graph changed while loadingreplace theirsidecarforms. - A missing sidecar of an earlier file still raises
Cannot open HNSW centroid sidecar. - A failed HNSW-RaBitQ write raises
HNSW index file cannot be writteninstead ofHNSW failed to write index file. pickle.dumps(obj, protocol=0)orprotocol=1on arabitqlibobject no longer aborts the Python process.quant.Rotatorandquant.Querynow pickle with every protocol; the index, k-means, parameter and iteration-statistics classes raiseTypeError: cannot pickle ..., as they already did with protocol 2 and higher, which include the default. Protocols 0 and 1 cannot reduce pybind11 objects (pybind11#3745), so they now use the protocol-2 reduction.quant.Rotator(method="matrix")now draws a Haar-distributed rotation, uniform over orthogonal matrices. It used the orthogonal factor of a Householder QR factorization as returned, whose determinant is fixed and whose first entry is always negative; each column now takes the sign of the matching diagonal entry of the triangular factor. RaBitQ's codes and estimator do not change when the same rotated coordinate changes sign in every vector and query, and the old rotation was Haar distributed up to such sign changes, so accuracy is not expected to change. A givenseednow produces a different matrix; rotators saved withto_bytes()and saved indexes keep theirs.
C++ changes¶
- New
rabitqlib::IvfIndexinrabitqlib/index/ivf_index.hpp(#234), with the workflow and defaults of the Python class, which now wraps it, and its messages where they do not name Python values: IvfIndex(dim, num_clusters, options)takes anIvfOptionsstruct with anivf::Routing, an alias ofivf::InitializerType. A staticloadreturns a trained index, andtrain,set_centroids,add,remove,reserve_cluster,searchandsavefollow the Python methods.- The first
addtrains an untrained index and leaves it untrained and empty if it fails.addtakes anAddOptionsstruct and returns the first new ID. - IDs are
rabitqlib::Id(int64_t). A missing search result iskNoId(-1) with distance+inf. searchtakes a batch of queries and anIvfSearchOptionsstruct. Without annprobeit probesnum_clusters / 16clusters, rounded and at least 1, and an explicit 0 throws.- A seed is drawn unless given, and
num_threads == 0means every available CPU, capped byOMP_NUM_THREADS. - Arguments out of range throw
std::invalid_argument, and calls in the wrong statestd::logic_error. - New
rabitqlib::HnswIndexinrabitqlib/index/hnsw_index.hpp(#234), built the same way, which the PythonHnswIndexnow wraps: HnswIndex(dim, options)takes anHnswOptionsstruct (metric,nbits,num_clusters,M,ef_construction, seed).train,set_centroids,add,remove,reserve,search,saveand the staticloadfollow the Python methods.- The first
addtrainsmin(num_clusters, number of points)centroids and leaves the index untrained, empty and with its capacity if it fails. - Capacity starts at one point and grows on
add, at least doubling, after the points and cluster IDs are checked;reserveonly grows it. adduses every available CPU unlessnum_threadsis set, whereashnsw::HierarchicalNSW::adduses one; passnum_threads = 1and a seed for a reproducible graph.searchtakes aGraphSearchOptionsstruct. Without anef_searchit usesmax(k, 64), and an explicit 0 throws.seed()is astd::optional<uint64_t>, because a file written byhnsw::HierarchicalNSWmay record a seed above 32 bits.- New
rabitqlib::SymqgIndexinrabitqlib/index/symqg_index.hpp(#234), which the PythonSymqgIndexnow wraps: SymqgIndex(dim, options)takes aSymqgOptionsstruct (metric,nbitsof 32, 4 or 8 with 32 for raw float32,max_degree,ef_construction,init, seed).addbuilds the graph from every vector, once, and a built or loaded index throwsstd::logic_erroronadd.trainonly checks its input.search,saveand the staticloadfollow the Python methods.- A failed
addleaves the index without a graph.addtakes a worker count, with 0, the default, for every available CPU. searchtakes aGraphSearchOptionsstruct. Without anef_searchit usesmax(k, 64), a smaller value is raised tok, and an explicit 0 throws;symqg::QuantizedGraphrejects anef_searchbelowk.seed(),ef_construction()andinit()have no value for a file of a release up to 0.8.IvfIndex,HnswIndexandSymqgIndexare the supported and documented C++ index API from 0.9.ivf::IVF,hnsw::HierarchicalNSW,symqg::QuantizedGraphandsymqg::QGBuilderstay installed at their paths and keep their interfaces apart from the changes listed below, but they leave the documentation and carry no compatibility promise.
Move to the new classes as follows:
| 0.8 | 0.9 |
|---|---|
IVF(num_points, dim, num_clusters, bits, ...), then construct(data, centroids, cluster_ids) |
IvfIndex(dim, num_clusters, options), set_centroids(centroids), then add(data, num_points, add_options) with add_options.cluster_ids |
HierarchicalNSW(max_elements, dim, bits, M, ef_construction, seed, metric), then construct(...) |
HnswIndex(dim, options) with options.num_clusters, then the same two calls; capacity grows on add |
QuantizedGraph(num_points, dim, max_degree, ...) with quantization_bits 0 for raw vectors, then QGBuilder(graph, ef_construction, data).build() |
SymqgIndex(dim, options) with options.nbits 32 for raw vectors, then add(data, num_points) |
IVF::search, IVF::search_batch, HierarchicalNSW::search (nested vectors), set_ef with QuantizedGraph::search_batch |
search(queries, num_queries, k, ids, distances, search_options) |
Index index; index.load(filename); |
auto index = IvfIndex::load(filename);, and likewise HnswIndex::load and SymqgIndex::load |
PID results, kPidMax for a missing IVF or SymphonyQG result |
Id results, kNoId for a missing result |
dimension(), metric_type(), initializer_type(), max_elements() (HNSW), degree_bound(), quantization_bits() (0 for raw), num_vertices(); IVF::reserve, HierarchicalNSW::resize |
dim(), metric(), routing(), capacity(), max_degree(), nbits() (32 for raw), num_points(); reserve_cluster, reserve |
IVF::train(num_points, data, cp), HierarchicalNSW::train(num_clusters, num_points, data, cp), HierarchicalNSW::set_centroids(num_clusters, centroids); add returning void or every label |
train(data, num_points) with cp(), set_centroids(centroids), add returning the first Id |
Four differences are not renames: HnswIndex::add uses every CPU unless num_threads is set; HnswIndex::search writes all k slots, padding with kNoId and +inf, where HierarchicalNSW::search returns only the pairs found; a seed is drawn unless given, where HierarchicalNSW defaults to 100; and default thread counts are capped by OMP_NUM_THREADS. The new classes do not offer the matrix rotator, rebuilding with IVF::construct, shrinking with HierarchicalNSW::resize, HierarchicalNSW::cluster_id_of, QuantizedGraph::search_with_scratch with its warm-start hint, QGBuilder's multi-pass build(n), reset, refine, avg_degree, check_dup and cache_vectors, or padded_dim(); use the existing classes for them.
-
The C++ examples in
sample/cppand the IVFaddhot-path benchmark use the new classes.symqg_indexingtakesnbits(32 for raw vectors, 4 or 8, default 32) and still reads 0 as raw vectors; it no longer prints stage times or the average degree. Its optional thread count 0 selects every available CPU. The default thread counts ofsymqg_indexingandivf_rabitq_indexingare now capped byOMP_NUM_THREADS, which they ignored.ivf_rabitq_indexing,hnsw_rabitq_indexingandsymqg_indexingacceptcosineas the metric and reject unknown metric names; all three used to build an L2 index silently. -
qgkmeans::QGKMeansParametersuses the Python names (#233):graph_degreebecomesmax_degree,ef_buildbecomesef_construction, andquantization_bits(0, 4 or 8) becomesnbits(32, 4 or 8, with 32 for raw float32). The fields keep their order and types. Annbitsof 0 is rejected, so code that initialized the field positionally with 0 must pass 32.QGAssignerkeeps its constructor, includingquantization_bitswith 0 for raw storage. - Messages follow the names:
QGKMeans nbits must be 4, 8, or 32,QGKMeans max_degree must be a positive multiple of 32,QGKMeans requires more centroids than max_degreeandQGKMeans ef_construction and ef_search must be positive. FinalAssignmentMode::SymphonyQG, an alias ofApproximate, is removed.-
The aliases
qgkmeans::QGKMeansIterationStatsandrabitqkmeans::RaBitQKMeansIterationStatsare removed; useclustering::KMeansIterationStats. -
MetricTypegainsMETRIC_COSINE, whichIVF,HierarchicalNSW,QuantizedGraph<float>anddefault_training_parametersaccept. The indexes normalize their inputs and store inner-product codes;metric_type()returnsMETRIC_COSINE. Entry points that validate the metric reject it with their existing messages: the stable core API v1, factor computation in the encoders, the query classes, FastScan queries, clustering and the IVF initializers. Code with an exhaustiveswitchoverMetricTypemay warn about the new value. -
Loading an index throws
rabitqlib::FormatError, a subclass ofstd::runtime_errorin the new headerrabitqlib/index/format_error.hpp, for a damaged, mismatched or unsupported file. Failing to open the file still throwsstd::runtime_error. Files of earlier layouts that threw other exceptions for invalid contents now throwFormatErrortoo: an IVF-RaBitQ file with an invalid metric or a dimension its rotation does not support, which threwstd::invalid_argument, and a SymphonyQG file with invalid settings or dimensions, which threwstd::invalid_argumentorstd::length_error. -
ivf::Initializerand its subclasses: save(std::ofstream&, const char*)becomeswrite(std::ostream&), andload(std::ifstream&, const char*)becomesread(std::istream&, uint64_t bytes).- The HNSW initializer no longer writes a sidecar itself.
- New accessors report what format-2 files record, or no value when unknown:
IVF::seed();HierarchicalNSW::seed();QuantizedGraph<float>::seed(),ef_construction()andinitialization().symqg::QGInitializationmoves fromqg_builder.hpptorabitqlib/index/symqg/types.hpp, whichqg.hpp, and through itqg_builder.hpp, includes.-
The vendored hnswlib adds
saveIndex(std::ostream&)andloadIndex(std::istream&, size_t bytes, ...); the path overloads are unchanged. -
rabitqlib::ceil_log2inrabitqlib/utils/tools.hppshifts asize_t, so an input of 2^32 or more is no longer undefined on 64-bit Windows, whereunsigned longhas 32 bits (#247). The library does not call it. -
rabitqlib::distance_ratioandrabitqlib::horizontal_avgare removed fromrabitqlib/utils/tools.hpp(#262). They were evaluation helpers for the C++ samples, and the library does not call them.distance_ratioread out of bounds for a missing result ID (kNoIdorkPidMax), andhorizontal_avgread out of bounds for empty or ragged input and averaged negative integer columns wrongly, for examplehorizontal_avg<int>gave 1431655764 for three rows of -1. Code that uses them needs its own version that handles these inputs; the samples now average their measurements with a local helper.tools.hppno longer includes<queue>, so code that usedstd::priority_queuethrough RaBitQ headers must include<queue>itself. -
MatrixRotator, whichchoose_rotatorreturns forRotatorType::MatrixRotatorandIVFandQuantizedGraphuse when given it, draws a Haar-distributed rotation, as described forquant.Rotatorabove. A given seed now produces a different matrix; saved rotators and indexes keep theirs. -
The installed CMake package satisfies
find_package(rabitqlib X.Y[.Z])only when the major and minor versions match:find_package(rabitqlib 0.8)no longer finds 0.9, whichSameMajorVersioncompatibility allowed, and a version range must stay within one minor release, such as0.9...<0.10. Before 1.0 a minor release may break the API.
Upgrading¶
From 0.8, first run your code on 0.8.5 and replace every form that raises a
DeprecationWarning, using the migration guide;
each replacement also works in 0.9. The same section lists the changes that come without
a warning, including int64 IDs and index format 2. Files saved by every earlier release
load in 0.9, but releases up to 0.8 cannot read files that 0.9 saves, so keep a copy
saved by 0.8 if you may downgrade. Rebuild C++ consumers with matching headers and
libraries; no cross-version C++ binary ABI is promised.
When upgrading from 0.7, follow the 0.8.0 release notes and the migration guide.