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 00000000..a911eacb Binary files /dev/null and b/tests/fixtures/persistence/v0.7.2/hnsw4_empty_l2.index differ diff --git a/tests/fixtures/persistence/v0.7.2/manifest.json b/tests/fixtures/persistence/v0.7.2/manifest.json new file mode 100644 index 00000000..05ed0ef5 --- /dev/null +++ b/tests/fixtures/persistence/v0.7.2/manifest.json @@ -0,0 +1,11 @@ +{ + "source_tag": "v0.7.2", + "source_commit": "655c9c6656318e9726e3a3908d0abe0563f7630c", + "writer": "tests/fixtures/persistence/v0.7.2/generate.cpp", + "producer": "Linux x86-64, g++ 14.3.0, Release, one thread, native optimization OFF", + "byte_order": "little", + "size_t_bytes": 8, + "sha256": { + "v0.7.2/hnsw4_empty_l2.index": "0177215c1b20f127be7b8bff1027b366f7faaf76022efeabe2336a96da093603" + } +} diff --git a/tests/python/test_historical_persistence.py b/tests/python/test_historical_persistence.py index 6b57667d..bdb78899 100644 --- a/tests/python/test_historical_persistence.py +++ b/tests/python/test_historical_persistence.py @@ -264,3 +264,29 @@ def test_non_ascii_writer_version_still_raises_format_error(tmp_path): rabitqlib.FormatError, match=r"written by rabitqlib 0\.9\\xff\\x01$" ): IvfIndex.load(str(migrated)) + + +def test_untrained_hnsw_file_from_v072_loads_and_trains(tmp_path): + # The C++ API of releases before 0.8 could save an index before training it; + # without centroids or a recorded seed, the first add cannot train it. + index = HnswIndex.load(str(FIXTURES / "v0.7.2" / "hnsw4_empty_l2.index")) + assert (len(index), index.dim, index.nbits, index.metric) == (0, 65, 4, "l2") + assert (index.capacity, index.num_clusters, index.seed) == (130, 16, None) + assert not index.is_trained + data = np.random.default_rng(21).normal(size=(200, 65)).astype(np.float32) + with pytest.raises( + RuntimeError, + match="^HnswIndex loaded from an untrained file must be trained before add; " + "call train or set_centroids$", + ): + index.add(data, num_threads=1) + index.train(data, num_threads=1) + index.add(data, num_threads=1) + ids, _ = index.search(data[:3], 5) + resaved = tmp_path / "resaved.index" + index.save(str(resaved)) + reloaded = HnswIndex.load(str(resaved)) + assert reloaded.is_trained + assert len(reloaded) == 200 + assert reloaded.num_clusters == 16 + np.testing.assert_array_equal(reloaded.search(data[:3], 5)[0], ids) diff --git a/tests/unit/rabitqlib/index/hnsw_index_test.cpp b/tests/unit/rabitqlib/index/hnsw_index_test.cpp index 3ea2f19e..4d744d51 100644 --- a/tests/unit/rabitqlib/index/hnsw_index_test.cpp +++ b/tests/unit/rabitqlib/index/hnsw_index_test.cpp @@ -505,6 +505,66 @@ TEST(HnswIndexTest, SaveAndLoadKeepSettingsSeedAndResults) { EXPECT_EQ(actual.distances, expected.distances); } +TEST(HnswIndexTest, LoadsAnUntrainedFileSavedBy07) { + // The C++ API of releases before 0.8 could save an index before training it. The + // file has no centroids and no seed, so the first add cannot train it. + constexpr size_t kFileDim = 65; + const auto path = + std::filesystem::path(RABITQ_TEST_FIXTURE_ROOT) / "v0.7.2" / "hnsw4_empty_l2.index"; + HnswIndex index = HnswIndex::load(path.string().c_str()); + EXPECT_FALSE(index.is_trained()); + EXPECT_FALSE(index.seed().has_value()); + EXPECT_EQ(index.dim(), kFileDim); + EXPECT_EQ(index.nbits(), 4U); + EXPECT_EQ(index.metric(), METRIC_L2); + EXPECT_EQ(index.capacity(), 130U); + EXPECT_EQ(index.num_points(), 0U); + EXPECT_EQ(index.num_clusters(), 16U); + + std::mt19937 rng(21); + std::normal_distribution 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 =