From 6798876c5d6bc7c0378d924f8c485b8921171332 Mon Sep 17 00:00:00 2001 From: sophisid Date: Sun, 27 Sep 2026 23:45:38 +0200 Subject: [PATCH] FAISS streaming --- CMakeLists.txt | 45 ++++++ CONTINUITY.md | 18 ++- README.md | 15 +- benchmark/CMakeLists.txt | 40 ++++- benchmark/bm_Faiss_Streaming.cpp | 114 +++++++++++++++ benchmark/bm_Messi_Streaming.cpp | 57 +++++++- daisy/__init__.py | 1 + demos/CMakeLists.txt | 12 ++ demos/demo_Faiss_Streaming.cpp | 43 ++++++ demos/demo_Faiss_Streaming.py | 44 ++++++ docs/demos-guide.md | 9 +- lib/algos/CMakeLists.txt | 19 +++ lib/algos/Faiss.cpp | 243 +++++++++++++++++++++++++++++++ lib/algos/Faiss.hpp | 74 ++++++++++ lib/daisy.hpp | 5 + pybinds/setup.cpp | 80 ++++++++++ tests/CMakeLists.txt | 12 ++ tests/test_Faiss_Streaming.cpp | 177 ++++++++++++++++++++++ tests/test_streaming.py | 14 +- 19 files changed, 1002 insertions(+), 20 deletions(-) create mode 100644 benchmark/bm_Faiss_Streaming.cpp create mode 100644 demos/demo_Faiss_Streaming.cpp create mode 100644 demos/demo_Faiss_Streaming.py create mode 100644 lib/algos/Faiss.cpp create mode 100644 lib/algos/Faiss.hpp create mode 100644 tests/test_Faiss_Streaming.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8f75903..b4b2c6c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -41,6 +41,7 @@ option(ODYSSEY_DEBUG_RESULTS "Print Odyssey search results (query_result) for de option(BUILD_SING "Enable CUDA support" OFF) option(BUILD_SOFA "Build SOFA with FFTW3 support" OFF) option(BUILD_COCONUT "Build the COCONUT sortable-SAX algorithm (static + streaming)" ON) +option(BUILD_FAISS "Build the FAISS-backed baseline algorithm (static + streaming)" OFF) # Backward compatibility: ENABLE_MPI and ODYSSEY_MPI map to BUILD_ODYSSEY if(DEFINED ENABLE_MPI) @@ -76,6 +77,7 @@ message(STATUS " BUILD_ODYSSEY: ${BUILD_ODYSSEY}") message(STATUS " ODYSSEY_DEBUG_RESULTS: ${ODYSSEY_DEBUG_RESULTS}") message(STATUS " BUILD_SING: ${BUILD_SING}") message(STATUS " BUILD_COCONUT: ${BUILD_COCONUT}") +message(STATUS " BUILD_FAISS: ${BUILD_FAISS}") # Define PROJECT_ROOT_DIR for all targets (paramSetup.cpp is compiled by commons_lib and by benchmark executables) get_filename_component(PROJECT_ROOT_DIR "${CMAKE_SOURCE_DIR}" ABSOLUTE) @@ -249,6 +251,49 @@ if(BUILD_TESTS) enable_testing() endif() +# ====== FAISS (CPU-only) ====== +# FAISS ships as a submodule under benchmark/faiss. Two things need it: the FAISS +# benchmark competitors, and the daisy::FaissFlat algorithm when BUILD_FAISS is ON. +# It is added here, once, so both consumers share a single 'faiss' target. +# +# FAISS requires CMake >= 3.24, above this project's floor of 3.16. That is checked +# explicitly: otherwise configuring with BUILD_BENCHMARK=ON aborts inside the +# submodule with an error that does not say which dependency asked for 3.24. +set(BUILD_FAISS_AVAILABLE FALSE CACHE INTERNAL "Internal flag indicating if FAISS is available.") + +if(BUILD_FAISS OR BUILD_BENCHMARK) + if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/benchmark/faiss/CMakeLists.txt") + message(WARNING + "FAISS sources not found at benchmark/faiss. FAISS targets will NOT be built. " + "Fetch them with: git submodule update --init benchmark/faiss") + elseif(CMAKE_VERSION VERSION_LESS 3.24) + message(WARNING + "FAISS requires CMake >= 3.24 but this is CMake ${CMAKE_VERSION}. " + "FAISS targets will NOT be built. Install a newer CMake to enable them.") + else() + set(FAISS_ENABLE_GPU OFF CACHE BOOL "" FORCE) + set(FAISS_ENABLE_PYTHON OFF CACHE BOOL "" FORCE) + set(FAISS_ENABLE_EXTRAS OFF CACHE BOOL "" FORCE) + set(FAISS_ENABLE_C_API OFF CACHE BOOL "" FORCE) + + # FAISS gates its own test suite on BUILD_TESTING. Shadow it for the + # submodule only, then restore it so DaiSy's CTest registration is intact. + set(_daisy_saved_build_testing "${BUILD_TESTING}") + set(BUILD_TESTING OFF) + add_subdirectory(benchmark/faiss ${CMAKE_BINARY_DIR}/faiss) + set(BUILD_TESTING "${_daisy_saved_build_testing}") + + set(BUILD_FAISS_AVAILABLE TRUE CACHE INTERNAL "Internal flag indicating if FAISS is available." FORCE) + if(DEBUG_MSG) + message(STATUS "FAISS found and configured (CPU-only). BUILD_FAISS_AVAILABLE=TRUE") + endif() + endif() +endif() + +if(BUILD_FAISS AND NOT BUILD_FAISS_AVAILABLE) + message(WARNING "BUILD_FAISS is ON but FAISS is unavailable. daisy::FaissFlat will NOT be built.") +endif() + # Add subdirectories if(DEBUG_MSG) diff --git a/CONTINUITY.md b/CONTINUITY.md index 0ba0bd5..71fc81b 100644 --- a/CONTINUITY.md +++ b/CONTINUITY.md @@ -58,6 +58,7 @@ From the current source tree and public includes, the main algorithm set include - `Hercules` - `DumpyOS` - `Fresh` +- `FaissFlat` (optional, `BUILD_FAISS`) These algorithms do not all share the same dependency profile or feature set. @@ -65,13 +66,21 @@ These algorithms do not all share the same dependency profile or feature set. - Top-k search is the baseline capability. - Range search is modeled through `SearchConfig` and is not universally implemented. -- Streaming insert is implemented by `BruteForceSearch`, `LbBruteforce`, `Messi`, and `Coconut`; - the base implementation still throws for algorithms that do not support it. +- Streaming insert is implemented by `BruteForceSearch`, `LbBruteforce`, `Messi`, `Coconut`, and + `FaissFlat`; the base implementation still throws for algorithms that do not support it. - Bruteforce streaming grows the owned in-memory database incrementally. LbBruteforce also computes SAX summaries incrementally, using the breakpoint set fixed by the initial build. - MESSI uses those fixed breakpoints to route stable SAX/position records into its live iSAX tree, including new-root creation and leaf splitting. Callers must serialize inserts and queries; simultaneous update/search is not supported. +- `FaissFlat` wraps `faiss::IndexFlatL2` and is the streaming baseline: `add()` appends with no + training and no rebuild, so it has no build-time state that can drift from the live data and + stays exact after every insert. It is `L2_SQUARED` only and rejects DTW in its constructor. + Its inherited `database` pointer is a non-owning view into FAISS storage, refreshed after every + build and insert; it must never be freed by DaiSy. +- FAISS range search keeps only `dist < radius` while DaiSy's convention is `dist <= r`, so + `FaissFlat` widens the radius by one float and filters the result to restore the inclusive + boundary. FAISS also returns range hits unsorted; DaiSy sorts them by distance. - `setNormalized(bool)` is a declaration about the input data, not a preprocessing step. - Data can come from in-memory arrays or file-backed sources via `DataSource`. @@ -91,6 +100,7 @@ Important options: - `BUILD_SING` - `BUILD_SOFA` - `BUILD_COCONUT` +- `BUILD_FAISS` Current optional dependency model: @@ -98,6 +108,10 @@ Current optional dependency model: - CUDA gates `Sing` - FFTW3 gates `Sofa` - Coconut can be fully toggled off +- The `benchmark/faiss` submodule gates `FaissFlat` and the FAISS benchmarks. FAISS requires + CMake >= 3.24, above this project's floor of 3.16; the root `CMakeLists.txt` checks the version + and warns instead of letting the submodule abort configuration. FAISS is added exactly once, + at the root, and shared by `dino_lib` and the benchmarks via `BUILD_FAISS_AVAILABLE`. Backward-compatibility option aliases exist for some old names such as MPI and CUDA toggles. diff --git a/README.md b/README.md index f4754ec..29e1351 100644 --- a/README.md +++ b/README.md @@ -57,11 +57,13 @@ The following table summarizes the key features of each algorithm: | **[DumpyOS](https://helios2.mi.parisdescartes.fr/~themisp/publications/vldbj24-dumpyos.pdf)** | In-memory scalable data series similarity search using an adaptive multi-ary iSAX index | | **[FreSH](http://publications.ics.forth.gr/tech-reports/2023/2023.TR489_FreSh_A_LockFree_Data_Series_Index.pdf)** | In-memory lock-free parallel similarity search using an iSAX index (SRDS 2023) | | **[COCONUT](http://www.vldb.org/pvldb/vol11/p677-kondylakis.pdf)** | Sortable-SAX index built bottom-up; supports both static datasets and **streaming** (incremental) inserts (PVLDB 2018) | +| **[FAISS](https://github.com/facebookresearch/faiss) flat** | Exact flat baseline backed by `faiss::IndexFlatL2`; static build plus streaming inserts with no retraining. Optional: build with `-DBUILD_FAISS=ON` | ### Incremental streaming inserts -`BruteForceSearch`, `LbBruteforce`, `Messi`, and `Coconut` implement the common streaming API. Build -the initial index once, then append one series or a contiguous batch without rebuilding: +`BruteForceSearch`, `LbBruteforce`, `Messi`, `Coconut`, and `FaissFlat` implement the common +streaming API. Build the initial index once, then append one series or a contiguous batch without +rebuilding: ```cpp daisy::Messi search(daisy::DistanceType::L2_SQUARED); @@ -76,6 +78,10 @@ SAX summary for each insert using the breakpoints established during the initial routes each new summary into the live iSAX tree and splits full leaves without rebuilding the index. Its first insert copies a borrowed initial in-memory database into owned growable storage. +`FaissFlat` is the streaming baseline: `faiss::IndexFlatL2::add()` appends into flat storage with +no training step and no rebuild, so nothing is frozen at build time that could drift from the live +data and the index stays exact after every insert. It supports `L2_SQUARED` only. + Streaming updates are not concurrent with queries. Inserts can reallocate the owned database, so callers should not retain a pointer returned by `getDatabase()` across them. @@ -133,6 +139,7 @@ Based on the available hardware, you can specify the below arguments to enable/d | `BUILD_ODYSSEY` | Enable MPI for distributed computing | `OFF` | OpenMPI/MPICH | | `BUILD_SING` | Enable CUDA for GPU acceleration | `OFF` | CUDA Toolkit | | `BUILD_COCONUT` | Enable the COCONUT sortable-SAX algorithm | `ON` | Core library | +| `BUILD_FAISS` | Enable the `FaissFlat` baseline algorithm | `OFF` | FAISS submodule, CMake 3.24+, BLAS/LAPACK | | `DEBUG_MSG` | Enable debug output | `OFF` | None | | `BUILD_SOFA` | Enable SOFA with SFA-Based indexing | `OFF` | FFTW3 | @@ -220,6 +227,10 @@ cd build ./benchmark/bm_Messi_L2Square ./benchmark/bm_Messi_Streaming +# FAISS baselines (CMake 3.24+ required by the FAISS submodule) +./benchmark/bm_FaissFlat_L2Square +./benchmark/bm_Faiss_Streaming + # Advanced algorithms (if available) ./benchmark/bm_Odyssey_L2Square # MPI required ./benchmark/bm_Sing_L2Square # CUDA required diff --git a/benchmark/CMakeLists.txt b/benchmark/CMakeLists.txt index aa8a5f0..9455cb2 100644 --- a/benchmark/CMakeLists.txt +++ b/benchmark/CMakeLists.txt @@ -15,6 +15,12 @@ if(DEBUG_MSG) message(STATUS "FetchContent module included.") endif() +# Google Benchmark's own test suite wants a googletest checkout nested inside its +# source tree, which FetchContent does not provide. We only need the library, so +# keep its self-tests off or configuration fails before FAISS is even reached. +set(BENCHMARK_ENABLE_TESTING OFF CACHE BOOL "" FORCE) +set(BENCHMARK_ENABLE_GTEST_TESTS OFF CACHE BOOL "" FORCE) + FetchContent_Declare( benchmark GIT_REPOSITORY https://github.com/google/benchmark.git @@ -42,13 +48,12 @@ if(DEBUG_MSG) message(STATUS "GoogleTest fetched and available.") endif() -# ====== FAISS (CPU-only) for benchmarks ====== -set(FAISS_ENABLE_GPU OFF CACHE BOOL "" FORCE) -set(FAISS_ENABLE_PYTHON OFF CACHE BOOL "" FORCE) -set(BUILD_TESTING OFF CACHE BOOL "" FORCE) -set(FAISS_ENABLE_EXTRAS OFF CACHE BOOL "" FORCE) -set(FAISS_ENABLE_C_API OFF CACHE BOOL "" FORCE) -add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/faiss ${CMAKE_CURRENT_BINARY_DIR}/faiss) +# FAISS is configured once by the root CMakeLists (it is shared with the +# daisy::FaissFlat algorithm) and exposes BUILD_FAISS_AVAILABLE. The FAISS +# benchmarks below are skipped when it could not be configured. +if(NOT BUILD_FAISS_AVAILABLE AND DEBUG_MSG) + message(STATUS "BUILD_FAISS_AVAILABLE is FALSE. Skipping FAISS benchmarks.") +endif() # ////// BRUTEFORCE ////// if(DEBUG_MSG) @@ -221,7 +226,9 @@ target_include_directories(bm_Messi_Streaming ${CMAKE_CURRENT_SOURCE_DIR}/../lib ) -# ////// FAISS FLAT ////// +# ////// FAISS FLAT + FAISS STREAMING ////// +if(BUILD_FAISS_AVAILABLE) + if(DEBUG_MSG) message(STATUS "---") message(STATUS "## Benchmark: FAISS Flat L2Square") @@ -249,6 +256,23 @@ target_include_directories(bm_FaissFlat_L2Square ${CMAKE_CURRENT_SOURCE_DIR}/../commons ) +# ////// FAISS STREAMING ////// +if(DEBUG_MSG) + message(STATUS "---") + message(STATUS "## Benchmark: FAISS Streaming") +endif() + +add_executable(bm_Faiss_Streaming bm_Faiss_Streaming.cpp) + +target_link_libraries(bm_Faiss_Streaming + PRIVATE + benchmark::benchmark + benchmark::benchmark_main + faiss +) + +endif() # BUILD_FAISS_AVAILABLE + # ////// PARIS ////// if(DEBUG_MSG) message(STATUS "---") diff --git a/benchmark/bm_Faiss_Streaming.cpp b/benchmark/bm_Faiss_Streaming.cpp new file mode 100644 index 0000000..5e251d4 --- /dev/null +++ b/benchmark/bm_Faiss_Streaming.cpp @@ -0,0 +1,114 @@ +// FAISS streaming baseline. +// +// faiss::IndexFlatL2::add() is a pure append into the flat code storage: no +// training, no rebuild, and the index stays exact. That makes it the natural +// lower bound on what an incremental insert can cost, and the reference point +// for the DaiSy streaming algorithms (Bruteforce, LbBruteforce, Messi, Coconut). +// +// The series generator, DIM, INITIAL and the batch sizes mirror +// bm_Messi_Streaming.cpp so the insert numbers are directly comparable. +// +// Insert-only numbers alone are misleading: a flat index buys its cheap insert +// by paying O(n) per query. BM_Faiss_StreamingMixed therefore interleaves +// inserts and queries, which is where an indexed competitor earns its keep. + +#include + +#include + +#include +#include + +namespace +{ + constexpr int DIM = 96; + constexpr int INITIAL = 4096; + constexpr int N_QUERY = 16; + constexpr int K = 10; + + std::vector makeSeries(int n, int phase_offset) + { + std::vector data(static_cast(n) * DIM); + for (int i = 0; i < n; ++i) + { + float *series = data.data() + static_cast(i) * DIM; + const float phase = static_cast(phase_offset + i) * 0.013f; + for (int j = 0; j < DIM; ++j) + series[j] = std::sin(0.07f * j + phase) + + 0.5f * std::cos(0.19f * j - phase); + } + return data; + } +} + +static void BM_Faiss_InsertBatch(benchmark::State &state) +{ + const faiss::idx_t batch_size = static_cast(state.range(0)); + const auto initial = makeSeries(INITIAL, 0); + const auto batch = makeSeries(static_cast(batch_size), INITIAL); + + faiss::IndexFlatL2 index(DIM); + index.add(INITIAL, initial.data()); + + // One untimed insert absorbs the reallocation that the first add() after a + // bulk build triggers (~2ms at INITIAL=4096, measured). Inside the loop that + // single spike dominates: it alone accounts for ~108us of an apparent 113us + // mean over 20 iterations, while steady-state add(1) is ~0.2us. + index.add(batch_size, batch.data()); + + for (auto _ : state) + { + index.add(batch_size, batch.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed( + static_cast(state.iterations()) * static_cast(batch_size)); +} + +BENCHMARK(BM_Faiss_InsertBatch) + ->Arg(1) + ->Arg(64) + ->Arg(1024) + ->Iterations(20) + ->Unit(benchmark::kMicrosecond); + +// One insert batch followed by one top-k query round, repeated. This is the +// workload a streaming index actually serves, and it exposes the O(n) scan that +// the flat index pays back on every query. +static void BM_Faiss_StreamingMixed(benchmark::State &state) +{ + const faiss::idx_t batch_size = static_cast(state.range(0)); + const auto initial = makeSeries(INITIAL, 0); + const auto batch = makeSeries(static_cast(batch_size), INITIAL); + const auto queries = makeSeries(N_QUERY, INITIAL / 2); + + faiss::IndexFlatL2 index(DIM); + index.add(INITIAL, initial.data()); + + std::vector I(static_cast(N_QUERY) * K); + std::vector D(static_cast(N_QUERY) * K); + + index.add(batch_size, batch.data()); + index.search(N_QUERY, queries.data(), K, D.data(), I.data()); + + for (auto _ : state) + { + index.add(batch_size, batch.data()); + index.search(N_QUERY, queries.data(), K, D.data(), I.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed( + static_cast(state.iterations()) * static_cast(batch_size)); + state.counters["n_database_final"] = static_cast(index.ntotal); +} + +BENCHMARK(BM_Faiss_StreamingMixed) + ->Arg(1) + ->Arg(64) + ->Arg(1024) + ->Iterations(20) + ->Unit(benchmark::kMicrosecond); + +BENCHMARK_MAIN(); diff --git a/benchmark/bm_Messi_Streaming.cpp b/benchmark/bm_Messi_Streaming.cpp index 8aaebdc..edaedc0 100644 --- a/benchmark/bm_Messi_Streaming.cpp +++ b/benchmark/bm_Messi_Streaming.cpp @@ -9,6 +9,8 @@ namespace { constexpr int DIM = 96; constexpr int INITIAL = 4096; + constexpr int N_QUERY = 16; + constexpr int K = 10; std::vector makeSeries(int n, int phase_offset) { @@ -27,7 +29,9 @@ namespace static void BM_Messi_InsertBatch(benchmark::State &state) { - state.PauseTiming(); + // Setup before the KeepRunning loop is already outside the timed region. + // Calling PauseTiming() here instead corrupts the real-time measurement, + // because the timer has not been started yet. const daisy::idx_t batch_size = static_cast(state.range(0)); auto initial = makeSeries(INITIAL, 0); auto batch = makeSeries(static_cast(batch_size), INITIAL); @@ -37,7 +41,12 @@ static void BM_Messi_InsertBatch(benchmark::State &state) config.search_workers = 2; daisy::Messi search(daisy::DistanceType::L2_SQUARED, config); search.buildIndex(initial.data(), INITIAL, DIM); - state.ResumeTiming(); + + // One untimed insert absorbs the one-off costs of the first update: MESSI + // converts the borrowed build buffer into owned, growable storage and grows + // its SAX cache. Leaving it inside the loop would spread that fixed cost + // over the iterations and understate steady-state insert throughput. + search.insertBatch(batch.data(), batch_size); for (auto _ : state) { @@ -56,4 +65,48 @@ BENCHMARK(BM_Messi_InsertBatch) ->Iterations(20) ->Unit(benchmark::kMicrosecond); +// One insert batch followed by one top-k query round, repeated: the workload a +// streaming index actually serves. Insert-only numbers flatter a flat baseline, +// which buys its cheap append by rescanning the whole database on every query. +// The counterpart is BM_Faiss_StreamingMixed, with matching DIM/INITIAL/args. +// Inserts and queries are issued sequentially; MESSI does not support +// concurrent updates and searches. +static void BM_Messi_StreamingMixed(benchmark::State &state) +{ + const daisy::idx_t batch_size = static_cast(state.range(0)); + auto initial = makeSeries(INITIAL, 0); + auto batch = makeSeries(static_cast(batch_size), INITIAL); + auto queries = makeSeries(N_QUERY, INITIAL / 2); + + daisy::MessiConfig config; + config.index_workers = 2; + config.search_workers = 2; + daisy::Messi search(daisy::DistanceType::L2_SQUARED, config); + search.buildIndex(initial.data(), INITIAL, DIM); + + std::vector I(static_cast(N_QUERY) * K); + std::vector D(static_cast(N_QUERY) * K); + + search.insertBatch(batch.data(), batch_size); + search.searchIndex(queries.data(), N_QUERY, K, I.data(), D.data()); + + for (auto _ : state) + { + search.insertBatch(batch.data(), batch_size); + search.searchIndex(queries.data(), N_QUERY, K, I.data(), D.data()); + benchmark::ClobberMemory(); + } + + state.SetItemsProcessed( + static_cast(state.iterations()) * static_cast(batch_size)); + state.counters["n_database_final"] = static_cast(search.getNDatabase()); +} + +BENCHMARK(BM_Messi_StreamingMixed) + ->Arg(1) + ->Arg(64) + ->Arg(1024) + ->Iterations(20) + ->Unit(benchmark::kMicrosecond); + BENCHMARK_MAIN(); diff --git a/daisy/__init__.py b/daisy/__init__.py index 7002cc8..75229fb 100644 --- a/daisy/__init__.py +++ b/daisy/__init__.py @@ -3,6 +3,7 @@ This library provides multiple algorithms for nearest neighbor search on time series data: - BruteForceSearch - exact brute-force baseline +- FaissFlat - exact FAISS IndexFlatL2 baseline (requires BUILD_FAISS) - LbBruteforce - brute-force with iSAX lower-bound pruning - Messi - in-memory iSAX index (L2 / DTW) - Fresh - FRESH in-memory iSAX index diff --git a/demos/CMakeLists.txt b/demos/CMakeLists.txt index 6e04dbf..db2284c 100644 --- a/demos/CMakeLists.txt +++ b/demos/CMakeLists.txt @@ -51,6 +51,18 @@ if(BUILD_DEMO) ${CMAKE_CURRENT_SOURCE_DIR}/../commons ) + # ////// FAISS (streaming baseline, requires BUILD_FAISS) ////// + if(BUILD_FAISS AND BUILD_FAISS_AVAILABLE) + add_executable(demo_Faiss_Streaming demo_Faiss_Streaming.cpp) + target_link_libraries(demo_Faiss_Streaming PRIVATE dino_lib commons_lib) + target_include_directories(demo_Faiss_Streaming PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../lib + ${CMAKE_CURRENT_SOURCE_DIR}/../commons + ) + elseif(DEBUG_MSG) + message(STATUS "BUILD_FAISS is OFF or FAISS unavailable. Skipping demo_Faiss_Streaming.") + endif() + # ////// COCONUT (static + streaming) ////// if(BUILD_COCONUT) if(DEBUG_MSG) diff --git a/demos/demo_Faiss_Streaming.cpp b/demos/demo_Faiss_Streaming.cpp new file mode 100644 index 0000000..37f9a79 --- /dev/null +++ b/demos/demo_Faiss_Streaming.cpp @@ -0,0 +1,43 @@ +// FAISS streaming: build once, then append new series without rebuilding. +// +// faiss::IndexFlatL2::add() appends with no training step, so unlike the +// iSAX-based algorithms nothing is frozen at build time and the index stays +// exact after every insert. This makes FaissFlat DaiSy's streaming baseline. + +#include "../commons/dataloaders.hpp" +#include "../lib/daisy.hpp" + +#include + +int main() +{ + const daisy::idx_t dim = 96; + const daisy::idx_t initial = 50000; + const daisy::idx_t batch = 25000; + const daisy::idx_t n_query = 5; + const daisy::idx_t k = 5; + + float *stream = loadRandomData(initial + batch, dim, 100, true); + float *query = loadRandomData(n_query, dim, 50, true); + + daisy::FaissFlat search(daisy::DistanceType::L2_SQUARED); + search.buildIndex(stream, initial, dim); + search.insert(stream + initial * dim); + search.insertBatch(stream + (initial + 1) * dim, batch - 1); + + daisy::idx_t *indices = new daisy::idx_t[n_query * k]; + float *distances = new float[n_query * k]; + search.searchIndex(query, n_query, k, indices, distances); + + std::printf("FaissFlat now contains %llu series. Query 0 kNN: ", + search.getNDatabase()); + for (daisy::idx_t j = 0; j < k; ++j) + std::printf("%llu(%.3f) ", indices[j], distances[j]); + std::printf("\n"); + + delete[] stream; + delete[] query; + delete[] indices; + delete[] distances; + return 0; +} diff --git a/demos/demo_Faiss_Streaming.py b/demos/demo_Faiss_Streaming.py new file mode 100644 index 0000000..e108aa1 --- /dev/null +++ b/demos/demo_Faiss_Streaming.py @@ -0,0 +1,44 @@ +"""FAISS streaming inserts, side by side with the exact bruteforce baseline. + +FaissFlat is only present when DaiSy was built with BUILD_FAISS=ON. +""" + +import numpy as np + +from daisy import BruteForceSearch, DistanceType + +try: + from daisy import FaissFlat +except ImportError: + FaissFlat = None + + +def main(): + if FaissFlat is None: + print("FaissFlat is not available: rebuild DaiSy with -DBUILD_FAISS=ON") + return + + rng = np.random.default_rng(100) + stream = rng.normal(size=(1000, 32)).astype(np.float32) + query = rng.normal(size=(5, 32)).astype(np.float32) + + index = FaissFlat(DistanceType.L2_SQUARED) + index.buildIndex(stream[:500]) + index.insert(stream[500]) + index.insertBatch(stream[501:]) + print("FaissFlat now contains", index.getNDatabase(), "series") + + indices, distances = index.searchIndex(query, 3) + print("FaissFlat query 0 indices:", indices[0]) + print("FaissFlat query 0 distances:", distances[0]) + + # A flat FAISS index stays exact across inserts, so it must agree with a + # bruteforce scan over the whole stream. + truth = BruteForceSearch(DistanceType.L2_SQUARED) + truth.buildIndex(stream) + truth_indices, _ = truth.searchIndex(query, 3) + print("matches bruteforce:", np.array_equal(indices, truth_indices)) + + +if __name__ == "__main__": + main() diff --git a/docs/demos-guide.md b/docs/demos-guide.md index ca45601..933fe2c 100644 --- a/docs/demos-guide.md +++ b/docs/demos-guide.md @@ -4,10 +4,11 @@ The demos module provides practical examples of how to use the DaiSy library's a Each demo illustrates a specific algorithm or specific distance metric. This module includes both C++ and Python implementations for various algorithms and use cases. Most demos follow the same batch pattern: `buildIndex(...)` once, then `searchIndex(...)`. -**Bruteforce**, **LbBruteforce**, **MESSI**, and **Coconut** additionally support streaming through -`insert(...)` and `insertBatch(...)`. See `demo_Bruteforce_Streaming`, -`demo_LbBruteforce_Streaming`, `demo_Messi_Streaming`, and `demo_Coconut_Streaming` for -live-index examples. +**Bruteforce**, **LbBruteforce**, **MESSI**, **Coconut**, and **FaissFlat** additionally support +streaming through `insert(...)` and `insertBatch(...)`. See `demo_Bruteforce_Streaming`, +`demo_LbBruteforce_Streaming`, `demo_Messi_Streaming`, `demo_Coconut_Streaming`, and +`demo_Faiss_Streaming` for live-index examples. `demo_Faiss_Streaming` is only built with +`-DBUILD_FAISS=ON`, and its Python counterpart skips itself when the binding is absent. Range search is exposed through `SearchConfig` and is implemented by **Bruteforce**, **LbBruteforce**, **MESSI**, **Coconut**, **ParIS**, **Fresh**, **DumpyOS**, **Hercules**, diff --git a/lib/algos/CMakeLists.txt b/lib/algos/CMakeLists.txt index 890bfb4..a930d67 100644 --- a/lib/algos/CMakeLists.txt +++ b/lib/algos/CMakeLists.txt @@ -43,6 +43,25 @@ else() endif() endif() +# ////// FAISS ////// +if(BUILD_FAISS AND BUILD_FAISS_AVAILABLE) + if(DEBUG_MSG) + message(STATUS "Adding Faiss.cpp to dino_lib sources.") + endif() + target_sources(dino_lib + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/Faiss.cpp + ) + # PRIVATE: Faiss.hpp forward-declares faiss::IndexFlatL2, so consumers of + # dino_lib do not need the FAISS headers, only the linked symbols. + target_link_libraries(dino_lib PRIVATE faiss) + target_compile_definitions(dino_lib PUBLIC FAISS_ENABLED) +else() + if(DEBUG_MSG) + message(STATUS "BUILD_FAISS/BUILD_FAISS_AVAILABLE is OFF. Skipping FAISS sources.") + endif() +endif() + # ////// LBBRUTEFORCE ////// if(DEBUG_MSG) message(STATUS "Adding LbBruteforce.cpp to dino_lib sources.") diff --git a/lib/algos/Faiss.cpp b/lib/algos/Faiss.cpp new file mode 100644 index 0000000..d8ac0c4 --- /dev/null +++ b/lib/algos/Faiss.cpp @@ -0,0 +1,243 @@ +#include "Faiss.hpp" + +#include +#include + +#include +#include +#include +#include +#include + +#ifdef _OPENMP +#include +#endif + +namespace daisy +{ + namespace + { + // FAISS labels are int64_t, DaiSy indices are unsigned long long. Both are + // 64-bit, but the signedness differs, so conversions go through here. + inline idx_t toDaisyIndex(faiss::idx_t label) + { + if (label < 0) + throw std::runtime_error("FaissFlat: FAISS returned a missing result (-1)"); + return static_cast(label); + } + } + + FaissFlat::FaissFlat(DistanceType distance_type) + : SimilaritySearchAlgorithm(distance_type) + { + if (distance_type != DistanceType::L2_SQUARED) + throw std::invalid_argument( + "FaissFlat supports L2_SQUARED only; FAISS has no DTW equivalent"); + } + + FaissFlat::~FaissFlat() = default; + + void FaissFlat::setNumThreads(int num_threads) + { + if (num_threads < 1) + throw std::invalid_argument("FaissFlat::setNumThreads requires at least one thread"); + this->num_threads = num_threads; + } + + void FaissFlat::refreshDatabaseView() + { + // Non-owning view into FAISS storage: for IndexFlatL2 the code size is + // dim * sizeof(float), so the code array is exactly the vector array. + // Never freed here; the FAISS index owns it. + this->database = (faiss_index && faiss_index->ntotal > 0) ? faiss_index->get_xb() : nullptr; + this->n_database = faiss_index ? static_cast(faiss_index->ntotal) : 0; + } + + void FaissFlat::buildIndex(DataSource *data_source) + { + if (data_source == nullptr) + throw std::invalid_argument("FaissFlat::buildIndex received a null data source"); + + const idx_t new_dim = data_source->getDim(); + if (new_dim == 0) + throw std::invalid_argument("FaissFlat::buildIndex requires a positive dimension"); + if (new_dim > static_cast(std::numeric_limits::max())) + throw std::length_error("FaissFlat: dimension exceeds what FAISS can index"); + + idx_t new_n_database = data_source->getTotalRecords(); + if (new_n_database == 0) + { + data_source->reset(); + std::vector dummy(new_dim); + idx_t count = 0; + while (data_source->nextRecord(dummy.data())) + count++; + new_n_database = count; + data_source->reset(); + } + + if (new_n_database > static_cast(std::numeric_limits::max())) + throw std::length_error("FaissFlat database is too large"); + + auto new_index = std::make_unique(static_cast(new_dim)); + + // A contiguous in-memory source can be handed to FAISS in one call. + if (const float *raw = data_source->rawPointer()) + { + new_index->add(static_cast(new_n_database), raw); + } + else + { + // Stream the source in blocks so a large file-backed build does not + // need a full second copy of the data alongside the FAISS storage. + constexpr idx_t BLOCK = 8192; + std::vector block(static_cast(BLOCK) * new_dim); + idx_t loaded = 0; + while (loaded < new_n_database) + { + idx_t in_block = 0; + while (in_block < BLOCK && loaded + in_block < new_n_database && + data_source->nextRecord(block.data() + static_cast(in_block) * new_dim)) + in_block++; + + if (in_block == 0) + break; + + new_index->add(static_cast(in_block), block.data()); + loaded += in_block; + } + } + + this->faiss_index = std::move(new_index); + this->dim = new_dim; + refreshDatabaseView(); + } + + void FaissFlat::insert(const float *series) + { + if (series == nullptr) + throw std::invalid_argument("FaissFlat::insert received null data"); + insertBatch(series, 1); + } + + void FaissFlat::insertBatch(const float *data, idx_t n) + { + if (n == 0) + return; + if (faiss_index == nullptr || this->dim == 0) + throw std::runtime_error("FaissFlat::insertBatch requires an initial buildIndex first"); + if (data == nullptr) + throw std::invalid_argument("FaissFlat::insertBatch received null data"); + if (n > std::numeric_limits::max() - this->n_database) + throw std::length_error("FaissFlat database size overflow"); + if (this->n_database + n > static_cast(std::numeric_limits::max())) + throw std::length_error("FaissFlat database is too large"); + + // A caller may pass a slice of the live database, which FAISS would read + // from while reallocating its own storage. Copy first in that case. + const float *storage_begin = faiss_index->ntotal > 0 ? faiss_index->get_xb() : nullptr; + const float *storage_end = storage_begin + ? storage_begin + static_cast(faiss_index->ntotal) * this->dim + : nullptr; + const bool aliases_storage = storage_begin && data >= storage_begin && data < storage_end; + + if (aliases_storage) + { + std::vector owned(data, data + static_cast(n) * this->dim); + faiss_index->add(static_cast(n), owned.data()); + } + else + { + faiss_index->add(static_cast(n), data); + } + + refreshDatabaseView(); + } + + void FaissFlat::searchIndex(const float *query, const idx_t n_query, const idx_t k, idx_t *I, float *D) + { + if (!validateSearchParams(k, n_query)) + return; + if (query == nullptr || I == nullptr || D == nullptr) + throw std::invalid_argument("FaissFlat::searchIndex received a null buffer"); + +#ifdef _OPENMP + omp_set_num_threads(this->num_threads); +#endif + + // FAISS writes int64_t labels; translate into DaiSy's unsigned indices. + std::vector labels(static_cast(n_query) * k); + faiss_index->search(static_cast(n_query), query, + static_cast(k), D, labels.data()); + + for (size_t i = 0; i < labels.size(); ++i) + I[i] = toDaisyIndex(labels[i]); + } + + void FaissFlat::searchIndex(const float *query, idx_t n_query, const SearchConfig &config, + std::vector> &I, + std::vector> &D) + { + if (config.type == QueryType::TOP_K) + { + SimilaritySearchAlgorithm::searchIndex(query, n_query, config, I, D); + return; + } + + if (faiss_index == nullptr || this->database == nullptr) + { + std::cerr << "[Error] Index must be built before searching\n"; + return; + } + if (n_query == 0) + { + std::cerr << "[Error] n_query must be greater than 0\n"; + return; + } + if (query == nullptr) + throw std::invalid_argument("FaissFlat::searchIndex received a null query buffer"); + +#ifdef _OPENMP + omp_set_num_threads(this->num_threads); +#endif + + // DaiSy range search includes hits exactly at the radius (dist <= r), while + // FAISS keeps only dist < radius. Widening by one float makes r itself + // reachable; the explicit filter below then drops anything in the gap, so + // the boundary matches the other algorithms exactly. + const float faiss_radius = std::nextafter(config.r, std::numeric_limits::max()); + + faiss::RangeSearchResult result(static_cast(n_query)); + faiss_index->range_search(static_cast(n_query), query, faiss_radius, &result); + + I.assign(n_query, {}); + D.assign(n_query, {}); + + std::vector> hits; + for (idx_t qi = 0; qi < n_query; ++qi) + { + const size_t begin = result.lims[qi]; + const size_t end = result.lims[qi + 1]; + + hits.clear(); + hits.reserve(end - begin); + for (size_t j = begin; j < end; ++j) + { + if (result.distances[j] <= config.r) + hits.emplace_back(result.distances[j], toDaisyIndex(result.labels[j])); + } + + // FAISS returns range hits unsorted; DaiSy reports them by distance. + std::sort(hits.begin(), hits.end()); + + I[qi].resize(hits.size()); + D[qi].resize(hits.size()); + for (size_t j = 0; j < hits.size(); ++j) + { + D[qi][j] = hits[j].first; + I[qi][j] = hits[j].second; + } + } + } + +} diff --git a/lib/algos/Faiss.hpp b/lib/algos/Faiss.hpp new file mode 100644 index 0000000..05a9894 --- /dev/null +++ b/lib/algos/Faiss.hpp @@ -0,0 +1,74 @@ +#ifndef DAISY_FAISS_HPP +#define DAISY_FAISS_HPP + +#include "SimilaritySearchAlgorithm.hpp" + +#include + +// Declared rather than included so consumers of daisy.hpp do not need the FAISS +// headers on their include path. The concrete type is only needed in Faiss.cpp. +namespace faiss +{ + struct IndexFlatL2; +} + +namespace daisy +{ + + /** + * Exact similarity search backed by faiss::IndexFlatL2. + * + * This is DaiSy's reference baseline rather than a new index: a flat FAISS + * index answers every query with a full SIMD/BLAS scan, so results are exact + * and no structure has to be maintained across updates. + * + * That makes its streaming behaviour the cheapest an insert can be. + * faiss::IndexFlatL2::add() appends into the flat code storage with no + * training step and no rebuild, and the index stays exact afterwards, so + * unlike LbBruteforce, Messi and Coconut there are no breakpoints, centroids + * or codebooks frozen at build time that could drift from the live data. + * + * Only L2_SQUARED is supported. FAISS METRIC_L2 reports squared Euclidean + * distances, which is what DaiSy's L2_SQUARED already means, so distances + * pass through unscaled. DTW has no FAISS equivalent and is rejected. + * + * As with the other streaming algorithms, inserts are not concurrent with + * queries: callers must serialize updates against searches. + */ + class FaissFlat : public SimilaritySearchAlgorithm + { + private: + std::unique_ptr faiss_index; + + // FAISS owns the vectors inside its own storage, which moves when it + // grows. The inherited `database` pointer is kept as a non-owning view of + // that storage and refreshed after every build and insert. + void refreshDatabaseView(); + + public: + explicit FaissFlat(DistanceType distance_type); + + void setNumThreads(int num_threads) override; + int getNumThreads() const { return this->num_threads; } + + using SimilaritySearchAlgorithm::buildIndex; + + void buildIndex(DataSource *data_source) override; + + // Appends into the live FAISS index. No retraining, and the index stays exact. + void insert(const float *series) override; + void insertBatch(const float *data, idx_t n) override; + + void searchIndex(const float *query, const idx_t n_query, const idx_t k, idx_t *I, float *D) override; + + void searchIndex(const float *query, idx_t n_query, const SearchConfig &config, + std::vector> &I, + std::vector> &D) override; + + // Defined in the .cpp, where faiss::IndexFlatL2 is a complete type. + ~FaissFlat() override; + }; + +} + +#endif diff --git a/lib/daisy.hpp b/lib/daisy.hpp index 4c90749..8ad5da0 100644 --- a/lib/daisy.hpp +++ b/lib/daisy.hpp @@ -13,4 +13,9 @@ #include "algos/DumpyOS.hpp" #include "algos/Fresh.hpp" +// Optional: built only with BUILD_FAISS=ON and the benchmark/faiss submodule present. +#ifdef FAISS_ENABLED +#include "algos/Faiss.hpp" +#endif + #endif diff --git a/pybinds/setup.cpp b/pybinds/setup.cpp index 084820f..ca227a6 100644 --- a/pybinds/setup.cpp +++ b/pybinds/setup.cpp @@ -32,6 +32,9 @@ #include "../lib/algos/Sofa.hpp" #endif #endif +#ifdef FAISS_ENABLED +#include "../lib/algos/Faiss.hpp" +#endif // Define a Python module named 'daisy._core' PYBIND11_MODULE(_core, m) @@ -140,6 +143,83 @@ PYBIND11_MODULE(_core, m) self.searchIndex(static_cast(query_buf.ptr), n_query, config, I, D); return pybind11::make_tuple(I, D); }, "Search using SearchConfig (top-k or range) and return (indices, distances)"); + ////// FAISS ////// +#ifdef FAISS_ENABLED + pybind11::class_(m, "FaissFlat", + "Exact similarity search backed by faiss::IndexFlatL2 " + "(static build + streaming insert). L2_SQUARED only.") + .def(pybind11::init(), + "Create a new FaissFlat. Only DistanceType.L2_SQUARED is supported; DTW raises.") + + .def("setNumThreads", &daisy::FaissFlat::setNumThreads, "Set the number of threads to use") + .def("getNumThreads", &daisy::FaissFlat::getNumThreads, "Get the number of threads") + .def("getNDatabase", &daisy::FaissFlat::getNDatabase, "Number of series currently indexed") + .def("getDim", &daisy::FaissFlat::getDim, "Dimension of the indexed series") + + .def("buildIndex", [](daisy::FaissFlat &self, pybind11::array_t db) + { + pybind11::buffer_info buf = db.request(); + if (buf.ndim != 2) + throw std::runtime_error("Database array must be 2D"); + + daisy::idx_t n = buf.shape[0]; + daisy::idx_t d = buf.shape[1]; + + daisy::InMemoryDataSource data_source(static_cast(buf.ptr), n, d); + self.buildIndex(&data_source); }, "Build the index from a 2D float32 numpy array") + + // Streaming: FAISS flat appends with no retraining, so the index stays exact. + .def("insert", [](daisy::FaissFlat &self, pybind11::array_t series) + { + pybind11::buffer_info buf = series.request(); + if (buf.ndim != 1) + throw std::runtime_error("insert expects a 1D float32 array"); + if (self.getDim() != 0 && static_cast(buf.shape[0]) != self.getDim()) + throw std::runtime_error("insert series dimension does not match the index dimension"); + self.insert(static_cast(buf.ptr)); }, "Incrementally insert one series into the live index") + + .def("insertBatch", [](daisy::FaissFlat &self, pybind11::array_t batch) + { + pybind11::buffer_info buf = batch.request(); + if (buf.ndim != 2) + throw std::runtime_error("insertBatch expects a 2D float32 array"); + if (self.getDim() != 0 && static_cast(buf.shape[1]) != self.getDim()) + throw std::runtime_error("insertBatch series dimension does not match the index dimension"); + self.insertBatch(static_cast(buf.ptr), buf.shape[0]); }, "Incrementally insert a batch of series into the live index") + + .def("searchIndex", [](daisy::FaissFlat &self, pybind11::array_t query, daisy::idx_t k) + { + pybind11::buffer_info query_buf = query.request(); + if (query_buf.ndim != 2) + throw std::runtime_error("Query array must be 2D"); + if (k <= 0) + throw std::runtime_error("k must be positive"); + + daisy::idx_t n_query = query_buf.shape[0]; + + std::vector indices(n_query * k); + std::vector distances(n_query * k); + + self.searchIndex(static_cast(query_buf.ptr), n_query, k, + indices.data(), distances.data()); + + return pybind11::make_tuple( + pybind11::array_t({n_query, k}, indices.data()), + pybind11::array_t({n_query, k}, distances.data()) + ); }, "Search the index with queries and return (indices, distances)") + + .def("searchIndex", [](daisy::FaissFlat &self, pybind11::array_t query, daisy::SearchConfig config) + { + pybind11::buffer_info query_buf = query.request(); + if (query_buf.ndim != 2) + throw std::runtime_error("Query array must be 2D"); + daisy::idx_t n_query = query_buf.shape[0]; + std::vector> I; + std::vector> D; + self.searchIndex(static_cast(query_buf.ptr), n_query, config, I, D); + return pybind11::make_tuple(I, D); }, "Search using SearchConfig (top-k or range) and return (indices, distances)"); +#endif + ////// LBBRUTEFORCE ////// pybind11::class_(m, "LbBruteforce", "Lower Bound brute-force similarity search") // Constructor diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 517f0d1..8dad2f7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,18 @@ target_include_directories(test_Bruteforce_Streaming PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../commons) gtest_discover_tests(test_Bruteforce_Streaming WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) +# ////// FAISS Streaming (requires BUILD_FAISS) ////// +if(BUILD_FAISS AND BUILD_FAISS_AVAILABLE) + add_executable(test_Faiss_Streaming test_Faiss_Streaming.cpp) + target_link_libraries(test_Faiss_Streaming PRIVATE GTest::gtest_main dino_lib commons_lib stdc++fs) + target_include_directories(test_Faiss_Streaming PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../lib + ${CMAKE_CURRENT_SOURCE_DIR}/../commons) + gtest_discover_tests(test_Faiss_Streaming WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) +elseif(DEBUG_MSG) + message(STATUS "BUILD_FAISS is OFF or FAISS unavailable. Skipping test_Faiss_Streaming.") +endif() + # # ////// BRUTEFORCE DTW ////// # if(DEBUG_MSG) # message(STATUS "---") diff --git a/tests/test_Faiss_Streaming.cpp b/tests/test_Faiss_Streaming.cpp new file mode 100644 index 0000000..3451e27 --- /dev/null +++ b/tests/test_Faiss_Streaming.cpp @@ -0,0 +1,177 @@ +#include + +#include "../lib/algos/Bruteforce.hpp" +#include "../lib/algos/Faiss.hpp" + +#include +#include +#include + +namespace +{ + constexpr int DIM = 32; + + std::vector makeSeries(int n, int first_phase = 0) + { + std::vector data(static_cast(n) * DIM); + for (int i = 0; i < n; ++i) + { + float *series = data.data() + static_cast(i) * DIM; + const float phase = static_cast(first_phase + i) * 0.37f; + double mean = 0.0; + for (int j = 0; j < DIM; ++j) + { + series[j] = std::sin(0.21f * j + phase) + + 0.35f * std::cos(0.47f * j - phase); + mean += series[j]; + } + mean /= DIM; + + double variance = 0.0; + for (int j = 0; j < DIM; ++j) + variance += (series[j] - mean) * (series[j] - mean); + const double stddev = std::sqrt(variance / DIM); + for (int j = 0; j < DIM; ++j) + series[j] = static_cast((series[j] - mean) / stddev); + } + return data; + } +} + +TEST(FaissStreamingTest, RejectsDtw) +{ + EXPECT_THROW(daisy::FaissFlat(daisy::DistanceType::DTW), std::invalid_argument); +} + +TEST(FaissStreamingTest, RequiresBuildAndRejectsNullInput) +{ + daisy::FaissFlat search(daisy::DistanceType::L2_SQUARED); + EXPECT_THROW(search.insert(nullptr), std::invalid_argument); + EXPECT_THROW(search.insertBatch(nullptr, 1), std::runtime_error); + + auto initial = makeSeries(2); + search.buildIndex(initial.data(), 2, DIM); + EXPECT_THROW(search.insert(nullptr), std::invalid_argument); + EXPECT_THROW(search.insertBatch(nullptr, 1), std::invalid_argument); +} + +TEST(FaissStreamingTest, SingleAndBatchInsertsAreImmediatelySearchable) +{ + auto all = makeSeries(8); + daisy::FaissFlat search(daisy::DistanceType::L2_SQUARED); + search.buildIndex(all.data(), 3, DIM); + + daisy::SimilaritySearchAlgorithm *streaming = &search; + streaming->insert(all.data() + 3 * DIM); + streaming->insertBatch(all.data() + 4 * DIM, 4); + + ASSERT_EQ(search.getNDatabase(), 8u); + for (int j = 0; j < DIM; ++j) + EXPECT_FLOAT_EQ(search.getDatabase()[7 * DIM + j], all[7 * DIM + j]); + + daisy::idx_t index = 0; + float distance = -1.0f; + search.searchIndex(all.data() + 7 * DIM, 1, 1, &index, &distance); + EXPECT_EQ(index, 7u); + EXPECT_NEAR(distance, 0.0f, 1e-5f); +} + +// A flat FAISS index stays exact across inserts: no breakpoints, centroids or +// codebooks are frozen at build time, so an incrementally grown index must agree +// with a bruteforce scan over the same data, index for index. +TEST(FaissStreamingTest, StreamedIndexMatchesBruteforceExactly) +{ + constexpr int TOTAL = 64; + constexpr int INITIAL = 10; + constexpr int N_QUERY = 5; + constexpr int K = 7; + + auto data = makeSeries(TOTAL, 3); + auto queries = makeSeries(N_QUERY, 900); + + daisy::FaissFlat streamed(daisy::DistanceType::L2_SQUARED); + streamed.buildIndex(data.data(), INITIAL, DIM); + streamed.insertBatch(data.data() + INITIAL * DIM, 20); + for (int i = INITIAL + 20; i < TOTAL; ++i) + streamed.insert(data.data() + static_cast(i) * DIM); + ASSERT_EQ(streamed.getNDatabase(), static_cast(TOTAL)); + + daisy::BruteForceSearch ground_truth(daisy::DistanceType::L2_SQUARED); + ground_truth.setNumThreads(1); + ground_truth.buildIndex(data.data(), TOTAL, DIM); + + std::vector expected_I(static_cast(N_QUERY) * K); + std::vector expected_D(static_cast(N_QUERY) * K); + std::vector actual_I(static_cast(N_QUERY) * K); + std::vector actual_D(static_cast(N_QUERY) * K); + + ground_truth.searchIndex(queries.data(), N_QUERY, K, expected_I.data(), expected_D.data()); + streamed.searchIndex(queries.data(), N_QUERY, K, actual_I.data(), actual_D.data()); + + for (size_t i = 0; i < actual_I.size(); ++i) + { + EXPECT_EQ(actual_I[i], expected_I[i]) << "at result " << i; + EXPECT_NEAR(actual_D[i], expected_D[i], 1e-3f) << "at result " << i; + } +} + +// Range search must use DaiSy's inclusive boundary (dist <= r) and be sorted by +// distance, even though FAISS keeps only dist < radius and returns hits unsorted. +TEST(FaissStreamingTest, RangeSearchMatchesBruteforceIncludingTheBoundary) +{ + constexpr int TOTAL = 40; + auto data = makeSeries(TOTAL, 77); + + daisy::FaissFlat streamed(daisy::DistanceType::L2_SQUARED); + streamed.buildIndex(data.data(), 8, DIM); + streamed.insertBatch(data.data() + 8 * DIM, TOTAL - 8); + ASSERT_EQ(streamed.getNDatabase(), static_cast(TOTAL)); + + daisy::BruteForceSearch ground_truth(daisy::DistanceType::L2_SQUARED); + ground_truth.setNumThreads(1); + ground_truth.buildIndex(data.data(), TOTAL, DIM); + + // A query drawn from the database has an exact-zero hit, so r = 0 pins down + // the inclusive boundary: FAISS alone (dist < radius) would return nothing. + for (float r : {0.0f, 5.0f, 30.0f}) + { + daisy::SearchConfig config; + config.type = daisy::QueryType::RANGE; + config.r = r; + + std::vector> expected_I, actual_I; + std::vector> expected_D, actual_D; + + ground_truth.searchIndex(data.data() + 12 * DIM, 1, config, expected_I, expected_D); + streamed.searchIndex(data.data() + 12 * DIM, 1, config, actual_I, actual_D); + + ASSERT_EQ(actual_I.size(), 1u) << "r=" << r; + ASSERT_EQ(actual_I[0].size(), expected_I[0].size()) << "r=" << r; + for (size_t j = 0; j < actual_I[0].size(); ++j) + { + EXPECT_EQ(actual_I[0][j], expected_I[0][j]) << "r=" << r << " hit " << j; + EXPECT_NEAR(actual_D[0][j], expected_D[0][j], 1e-3f) << "r=" << r << " hit " << j; + } + EXPECT_TRUE(std::is_sorted(actual_D[0].begin(), actual_D[0].end())) << "r=" << r; + for (float d : actual_D[0]) + EXPECT_LE(d, r) << "hit outside the radius at r=" << r; + } +} + +// FAISS storage moves when it grows, so inserting a slice of the live database +// would otherwise read from a buffer that add() is reallocating underneath it. +TEST(FaissStreamingTest, CanInsertFromItsOwnDatabaseAcrossReallocation) +{ + auto initial = makeSeries(4, 150); + daisy::FaissFlat search(daisy::DistanceType::L2_SQUARED); + search.buildIndex(initial.data(), 4, DIM); + + search.insert(search.getDatabase() + 2 * DIM); + ASSERT_EQ(search.getNDatabase(), 5u); + + daisy::idx_t index = 0; + float distance = -1.0f; + search.searchIndex(search.getDatabase() + 4 * DIM, 1, 1, &index, &distance); + EXPECT_EQ(index, 2u); + EXPECT_NEAR(distance, 0.0f, 1e-5f); +} diff --git a/tests/test_streaming.py b/tests/test_streaming.py index c1f79bf..0fac1b3 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -6,13 +6,23 @@ from daisy import BruteForceSearch, DistanceType, LbBruteforce, Messi +# FaissFlat is only bound when DaiSy was built with BUILD_FAISS=ON. +try: + from daisy import FaissFlat +except ImportError: + FaissFlat = None + +STREAMING_ALGORITHMS = [BruteForceSearch, LbBruteforce, Messi] +if FaissFlat is not None: + STREAMING_ALGORITHMS.append(FaissFlat) + class StreamingBindingsTest(unittest.TestCase): def test_streaming_algorithms(self): rng = np.random.default_rng(123) data = rng.normal(size=(8, 32)).astype(np.float32) - for algorithm in (BruteForceSearch, LbBruteforce, Messi): + for algorithm in STREAMING_ALGORITHMS: with self.subTest(algorithm=algorithm.__name__): index = algorithm(DistanceType.L2_SQUARED) if algorithm is Messi: @@ -36,7 +46,7 @@ def test_streaming_algorithms(self): self.assertAlmostEqual(float(distances[0, 0]), 0.0, places=6) def test_dimension_validation(self): - for algorithm in (BruteForceSearch, LbBruteforce, Messi): + for algorithm in STREAMING_ALGORITHMS: with self.subTest(algorithm=algorithm.__name__): index = algorithm(DistanceType.L2_SQUARED) if algorithm is Messi: