From c5544c4434c57a6eaa45373f9f2b3b3dc619806f Mon Sep 17 00:00:00 2001 From: gouyt13clear Date: Thu, 19 Nov 2026 19:49:53 +0800 Subject: [PATCH] fix(hnsw): explain how to train an index loaded from an untrained file The C++ API of releases before 0.8 could save an HNSW-RaBitQ index before training it. 0.9 loads such a file untrained, with num_clusters 16, but the file records no seed, so the first add cannot train it. add, search, remove and save then said "HnswIndex must be trained or loaded before add", which is wrong for a loaded index. They now say to call train or set_centroids. A release-produced fixture from v0.7.2 (tests/fixtures/persistence/v0.7.2) covers the path, which no test exercised: C++ and Python tests load it, check the messages, and train it with train or set_centroids before add and a save/load round trip. --- docs/docs/index/hnsw.md | 3 + docs/docs/releases/unreleased.md | 1 + include/rabitqlib/index/hnsw_index.hpp | 2 + src/index/hnsw_index.cpp | 15 ++++- tests/fixtures/persistence/README.md | 2 + .../persistence/v0.7.2/CMakeLists.txt | 13 ++++ tests/fixtures/persistence/v0.7.2/README.md | 30 +++++++++ .../fixtures/persistence/v0.7.2/generate.cpp | 20 ++++++ .../persistence/v0.7.2/hnsw4_empty_l2.index | Bin 0 -> 205 bytes .../fixtures/persistence/v0.7.2/manifest.json | 11 ++++ tests/python/test_historical_persistence.py | 26 ++++++++ .../unit/rabitqlib/index/hnsw_index_test.cpp | 60 ++++++++++++++++++ 12 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 tests/fixtures/persistence/v0.7.2/CMakeLists.txt create mode 100644 tests/fixtures/persistence/v0.7.2/README.md create mode 100644 tests/fixtures/persistence/v0.7.2/generate.cpp create mode 100644 tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index create mode 100644 tests/fixtures/persistence/v0.7.2/manifest.json diff --git a/docs/docs/index/hnsw.md b/docs/docs/index/hnsw.md index 2cf6f78e..4fd2543f 100644 --- a/docs/docs/index/hnsw.md +++ b/docs/docs/index/hnsw.md @@ -305,6 +305,9 @@ IDs, so do not open such a file with them. `save` writes [index format 2](https://github.com/VectorDB-NTU/RaBitQ-Library/blob/main/docs/formats.md#index-format-2), which also records the construction seed, so `seed` survives a reload. Releases up to 0.8 cannot read these files; every earlier file still loads, without a recorded seed, and saving it writes format 2. +The C++ API of releases before 0.8 could also save an index before training it. Such a +file from 0.7 loads untrained, with `num_clusters` 16; without a recorded seed its first `add` +cannot train it, so call `train` or `set_centroids` before `add`. New HNSW-RaBitQ indexes pad dimensions to multiples of 32 for all supported bit widths. Loading preserves the saved padded dimension and rotation, so older indexes diff --git a/docs/docs/releases/unreleased.md b/docs/docs/releases/unreleased.md index 94ebe9ce..556b9008 100644 --- a/docs/docs/releases/unreleased.md +++ b/docs/docs/releases/unreleased.md @@ -55,6 +55,7 @@ - Loading a format-2 file keeps the `seed` of every index, and `ef_construction` and `init` of SymphonyQG. They were `None` after `load`, and still are for files from releases up to 0.8. - With a recorded seed, `cp.seed` after `load` follows 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 that the 0.7 C++ API saved before training loads untrained, with `num_clusters` 16. Without a recorded seed its first `add` cannot train it, so `add`, `search`, `remove` and `save` raise `HnswIndex loaded from an untrained file must be trained before add; call train or set_centroids` (naming the operation) until `train` or `set_centroids` runs. - A new exception, `rabitqlib.FormatError`, subclasses both `ValueError` and `RuntimeError`: - Every index `load` raises it for a truncated, corrupt, mismatched or unsupported file, in format 2 and in every earlier layout. These were `RuntimeError`, which still catches them. A file that cannot be opened still raises a plain `RuntimeError`. - `quant.FormatError` is now the same class. It was a subclass of `ValueError` only, which still catches it. diff --git a/include/rabitqlib/index/hnsw_index.hpp b/include/rabitqlib/index/hnsw_index.hpp index 25377f54..22bf22ce 100644 --- a/include/rabitqlib/index/hnsw_index.hpp +++ b/include/rabitqlib/index/hnsw_index.hpp @@ -114,6 +114,8 @@ class HnswIndex { * existing centroids, which do not move. Capacity grows to fit the points, at least * doubling, after the points and cluster IDs are checked. A failure while linking may * leave part of the batch in the index, which stays safe to search, save and destroy. + * An index loaded from an empty, untrained file saved before 0.8 has no seed, so + * add does not train it; call train or set_centroids first. * * @param data New points (num_points * dim) * @param num_points Number of new points diff --git a/src/index/hnsw_index.cpp b/src/index/hnsw_index.cpp index 14104af9..3a8570e8 100644 --- a/src/index/hnsw_index.cpp +++ b/src/index/hnsw_index.cpp @@ -24,7 +24,7 @@ namespace rabitqlib { namespace { using rabitqkmeans::RaBitQKMeansParameters; -// What an empty, untrained file saved by 0.7 trains, as a new index does by default. +// What an empty, untrained file saved before 0.8 trains, as a new index does by default. constexpr size_t kDefaultNumClusters = 16; // Grow the capacity to fit num_points more points, at least doubling it. The points are @@ -249,11 +249,20 @@ size_t HnswIndex::num_stored_points() const { return index_->num_stored_points() bool HnswIndex::is_trained() const { return index_->is_trained(); } void HnswIndex::check_trained(const char* operation) const { - if (!index_->is_trained()) { + if (index_->is_trained()) { + return; + } + // Only an empty file saved before 0.8 loads untrained, and it lacks the seed that + // lets the first add train. + if (!index_->seed().has_value()) { throw std::logic_error( - std::string("HnswIndex must be trained or loaded before ") + operation + std::string("HnswIndex loaded from an untrained file must be trained before ") + + operation + "; call train or set_centroids" ); } + throw std::logic_error( + std::string("HnswIndex must be trained or loaded before ") + operation + ); } void HnswIndex::check_trainable() const { diff --git a/tests/fixtures/persistence/README.md b/tests/fixtures/persistence/README.md index 1273ab8f..9648d47c 100644 --- a/tests/fixtures/persistence/README.md +++ b/tests/fixtures/persistence/README.md @@ -34,6 +34,8 @@ routing (with its `.hnsw` sidecar), HNSW-RaBitQ at 1, 5 and 9 bits, and Symphony 4- and 8-bit with FHT/Kac and matrix rotation. Historical auto-selected HNSW routing at 20,000 clusters is not represented by fixtures; Python tests cover it with headers built around the v0.8.3 layout. +The [v0.7.2](v0.7.2/README.md) file is an HNSW-RaBitQ index saved before training, +which the C++ API of releases before 0.8 could write and later releases refuse to. ## Deliberate regeneration diff --git a/tests/fixtures/persistence/v0.7.2/CMakeLists.txt b/tests/fixtures/persistence/v0.7.2/CMakeLists.txt new file mode 100644 index 00000000..f43d12cf --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) +project(rabitq_v072_fixtures LANGUAGES CXX) + +if(NOT IS_DIRECTORY "${RABITQ_HISTORICAL_SOURCE}") + message(FATAL_ERROR "Set RABITQ_HISTORICAL_SOURCE to the pinned v0.7.2 checkout") +endif() +set(RABITQ_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) +set(RABITQ_BUILD_PYTHON_BINDINGS OFF CACHE BOOL "" FORCE) +set(RABITQ_ENABLE_NATIVE_OPTIMIZATION OFF CACHE BOOL "" FORCE) +add_subdirectory("${RABITQ_HISTORICAL_SOURCE}" historical) +add_executable(generate_fixtures generate.cpp) +target_link_libraries(generate_fixtures PRIVATE rabitqlib::index) diff --git a/tests/fixtures/persistence/v0.7.2/README.md b/tests/fixtures/persistence/v0.7.2/README.md new file mode 100644 index 00000000..051b4af3 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/README.md @@ -0,0 +1,30 @@ +# Index fixture from v0.7.2 + +This file was written by release **v0.7.2**, commit +`655c9c6656318e9726e3a3908d0abe0563f7630c`, using [generate.cpp](generate.cpp). +[manifest.json](manifest.json) records the producer and SHA-256 hash. +Keep it unchanged; tests never regenerate it with the current writer. + +`hnsw4_empty_l2.index` is an HNSW-RaBitQ index that was constructed and saved without +points or training: capacity 130, 65 original dimensions, 4 bits, L2, M = 8, +`ef_construction` 64, seed 42. The C++ API of releases before 0.8 allowed this; 0.8 +and later releases refuse to save an empty index. Such a file has no +centroids and does not record its seed, so it loads untrained. + +## Deliberate regeneration + +Build the generator only against an isolated copy of the release: + +```bash +mkdir -p build/fixtures/v0.7.2 +git archive v0.7.2 | tar -x -C build/fixtures/v0.7.2 +cmake -S tests/fixtures/persistence/v0.7.2 -B build/fixtures/v0.7.2-generator \ + -DRABITQ_HISTORICAL_SOURCE="$PWD/build/fixtures/v0.7.2" \ + -DCMAKE_BUILD_TYPE=Release +cmake --build build/fixtures/v0.7.2-generator --target generate_fixtures +``` + +Run it with a new output directory. The file has no points, and its rotation is seeded +with 42, so the generator writes the same bytes on every run with the same toolchain +(the manifest records it); record a new hash in the manifest before adopting a +different file. diff --git a/tests/fixtures/persistence/v0.7.2/generate.cpp b/tests/fixtures/persistence/v0.7.2/generate.cpp new file mode 100644 index 00000000..161405f0 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/generate.cpp @@ -0,0 +1,20 @@ +// Build only against the pinned v0.7.2 source, never the current checkout. Writes an +// HNSW-RaBitQ index that was constructed and saved without points, which the 0.7.x +// C++ API allowed (0.8 and later refuse to save an empty index). +#include +#include + +#include "rabitqlib/core/metric.hpp" +#include "rabitqlib/index/hnsw/hnsw.hpp" + +int main(int argc, char** argv) { + if (argc != 2) { + throw std::invalid_argument("Pass the fixture output directory"); + } + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + // Capacity 130, 65 dimensions, 4 bits, M 8, ef_construction 64, seed 42. + rabitqlib::hnsw::HierarchicalNSW index(130, 65, 4, 8, 64, 42, rabitqlib::METRIC_L2); + index.save((directory / "hnsw4_empty_l2.index").string().c_str()); + return 0; +} diff --git a/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index b/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index new file mode 100644 index 0000000000000000000000000000000000000000..a911eacb52cb80fcb7cd8760180ea068c1b0bbca GIT binary patch literal 205 zcmZo-Kn0FaZUU+>12c>-0cGewX%{H%1Eo`-vHko`0p-JJ0Vw|;v(+8W z normal; + std::vector data(kNumPoints * kFileDim); + for (auto& value : data) { + value = normal(rng); + } + const auto message = [](const std::string& operation) { + return "HnswIndex loaded from an untrained file must be trained before " + + operation + "; call train or set_centroids"; + }; + expect_error( + [&] { index.add(data.data(), kNumPoints, single_thread()); }, message("add") + ); + Id ids[1]; + const Id remove_ids[] = {0}; + expect_error( + [&] { index.search(data.data(), 1, 1, ids, nullptr); }, message("search") + ); + expect_error([&] { index.remove(remove_ids, 1); }, message("remove")); + const rabitq_test::TempFile file("hnsw_index_untrained_07.index"); + expect_error( + [&] { index.save(file.path().c_str()); }, message("save") + ); + EXPECT_EQ(index.num_points(), 0U); + + index.train(data.data(), kNumPoints, 1); + EXPECT_EQ(index.num_clusters(), 16U); + EXPECT_EQ(index.add(data.data(), kNumPoints, single_thread()), 0); + const auto expected = search(index, data.data(), 3, 5); + EXPECT_EQ(count_found(expected), 15U); + index.save(file.path().c_str()); + const HnswIndex reloaded = HnswIndex::load(file.path().c_str()); + EXPECT_TRUE(reloaded.is_trained()); + EXPECT_EQ(reloaded.num_points(), kNumPoints); + EXPECT_EQ(reloaded.num_clusters(), 16U); + EXPECT_EQ(search(reloaded, data.data(), 3, 5).ids, expected.ids); + + // Setting centroids makes it trained as well. + HnswIndex other = HnswIndex::load(path.string().c_str()); + other.set_centroids(data.data()); // the first 16 points + EXPECT_EQ(other.add(data.data(), kNumPoints, single_thread()), 0); + EXPECT_EQ(other.num_points(), kNumPoints); +} + TEST(HnswIndexTest, LoadsFilesWithoutASeedAndWithA64BitSeed) { // Releases up to 0.8 did not record the seed; training defaults to the k-means seed. const auto path =