Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
- [x] **Inverted Index (BM25):** Реализовать стемминг, стоп-слова, сжатие постинг-списков (Elias-Fano / Varint).
- [x] **Слияние и фильтрация:** Реализовать Roaring Bitmaps и Bloom-фильтры. Реализовать алгоритм RRF для слияния результатов векторного и текстового поиска.
- [x] **Tombstoning & Graph Deletion:** Интегрировать `Roaring Bitmap` для пометки удаленных `node_id` (Internal ID) в HNSW без физического перестроения графа в реальном времени. Реализовать фоновое сжатие (LSM-style Compaction) для создания новых mmap-сегментов при превышении % удаленных узлов.
- [ ] **Recall Tests & Parameter Tuning:** Создать тесты на датасетах реального мира (например, SIFT1M) для замеров Recall (accuracy) HNSW индекса и калибровки параметров `M`, `M0`, `efConstruction`, `efSearch` для исключения проблемы "разрыва графа".
- [x] **Recall Tests & Parameter Tuning:** Создать тесты на датасетах реального мира (например, SIFT1M) для замеров Recall (accuracy) HNSW индекса и калибровки параметров `M`, `M0`, `efConstruction`, `efSearch` для исключения проблемы "разрыва графа".
- [x] **Модуль 2 (Часть 2): Метаданные и WAL:**
- [x] Выбрать или написать легковесное K/V хранилище (LSM-tree/B-Tree) для метаданных документов.
- [x] Реализовать строгий Write-Ahead Log (WAL) (append-only) для защиты от крашей.
Expand Down
Binary file added assets/datasets/siftsmall.tar.gz
Binary file not shown.
Binary file added assets/datasets/siftsmall/siftsmall_base.fvecs
Binary file not shown.
Binary file not shown.
Binary file added assets/datasets/siftsmall/siftsmall_learn.fvecs
Binary file not shown.
Binary file added assets/datasets/siftsmall/siftsmall_query.fvecs
Binary file not shown.
4 changes: 4 additions & 0 deletions benchmarks/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
find_package(benchmark CONFIG REQUIRED)
find_package(roaring CONFIG REQUIRED)

add_executable(rag_engine_benchmarks
bench_main.cpp
Expand All @@ -11,3 +12,6 @@ target_link_libraries(rag_engine_benchmarks PRIVATE
benchmark::benchmark_main
rag_engine_core
)

add_executable(hnsw_parameter_tuner hnsw_parameter_tuner.cpp)
target_link_libraries(hnsw_parameter_tuner PRIVATE rag_engine_core roaring::roaring-headers-cpp)
135 changes: 135 additions & 0 deletions benchmarks/hnsw_parameter_tuner.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#include "rag_engine/index/hnsw.hpp"
#include "../tests/sift_parser.hpp"
#include <iostream>
#include <vector>
#include <chrono>
#include <iomanip>
#include <filesystem>

using namespace rag_engine::index;
using namespace rag_engine::test_utils;

// Helper to calculate recall
double calc_recall(const std::vector<std::vector<SearchResult>>& results,
const std::vector<std::vector<int>>& truth,
size_t k) {
size_t hits = 0;
for (size_t i = 0; i < results.size(); ++i) {
int true_nn = truth[i][0];
size_t limit = std::min(k, results[i].size());
for (size_t j = 0; j < limit; ++j) {
if (results[i][j].id == static_cast<uint32_t>(true_nn)) {
hits++;
break;
}
}
}
return static_cast<double>(hits) / results.size();
}

void print_help(const char* prog) {
std::cerr << "Usage: " << prog << " <base.fvecs> <query.fvecs> <groundtruth.ivecs> [max_base_elements]\n";
}

int main(int argc, char** argv) {
if (argc < 4) {
print_help(argv[0]);
return 1;
}

std::string base_file = argv[1];
std::string query_file = argv[2];
std::string truth_file = argv[3];
size_t max_base = (argc >= 5) ? std::stoull(argv[4]) : 0;

std::cout << "Loading dataset...\n";
auto base_vectors = SiftParser::read_fvecs(base_file, max_base);
auto query_vectors = SiftParser::read_fvecs(query_file);
auto ground_truth = SiftParser::read_ivecs(truth_file);

std::cout << "Loaded " << base_vectors.size() << " base vectors, "
<< query_vectors.size() << " queries.\n\n";

if (base_vectors.empty() || query_vectors.empty() || ground_truth.empty()) {
std::cerr << "Empty dataset loaded.\n";
return 1;
}

size_t dim = base_vectors[0].size();

// Parameters to tune
std::vector<size_t> M_values = {16, 32};
std::vector<size_t> efConstruct_values = {100, 200};
std::vector<size_t> efSearch_values = {50, 100};

std::cout << "====================================================================================\n";
std::cout << std::left << std::setw(6) << "M"
<< std::setw(15) << "efConstruction"
<< std::setw(12) << "efSearch"
<< std::setw(15) << "BuildTime(ms)"
<< std::setw(15) << "QueryTime(ms)"
<< std::setw(12) << "Recall@10"
<< "\n";
std::cout << "====================================================================================\n";

for (size_t m : M_values) {
for (size_t efC : efConstruct_values) {

std::string index_path = "tuner_index.bin";
if (std::filesystem::exists(index_path)) std::filesystem::remove(index_path);
if (std::filesystem::exists(index_path + ".tombstones")) std::filesystem::remove(index_path + ".tombstones");

HnswConfig config;
config.dim = dim;
config.max_elements = base_vectors.size();
config.M = m;
config.M0 = m * 2;
config.ef_construction = efC;

auto t_build_start = std::chrono::high_resolution_clock::now();
{
HnswIndex index(index_path, config, false);
for (size_t i = 0; i < base_vectors.size(); ++i) {
index.add(i, base_vectors[i]);
}
index.sync();
}
auto t_build_end = std::chrono::high_resolution_clock::now();
double build_ms = std::chrono::duration<double, std::milli>(t_build_end - t_build_start).count();

// Load read-only for queries
HnswIndex index_ro(index_path, config, true);

for (size_t efS : efSearch_values) {

auto t_query_start = std::chrono::high_resolution_clock::now();
std::vector<std::vector<SearchResult>> all_results;
all_results.reserve(query_vectors.size());

for (const auto& q : query_vectors) {
all_results.push_back(index_ro.search(q, 10, efS));
}

auto t_query_end = std::chrono::high_resolution_clock::now();
double query_ms = std::chrono::duration<double, std::milli>(t_query_end - t_query_start).count();

double recall = calc_recall(all_results, ground_truth, 10);

std::cout << std::left << std::setw(6) << m
<< std::setw(15) << efC
<< std::setw(12) << efS
<< std::setw(15) << std::fixed << std::setprecision(2) << build_ms
<< std::setw(15) << std::fixed << std::setprecision(2) << query_ms
<< std::setw(12) << std::fixed << std::setprecision(4) << recall
<< "\n";
}

// Clean up index for next iteration
if (std::filesystem::exists(index_path)) std::filesystem::remove(index_path);
if (std::filesystem::exists(index_path + ".tombstones")) std::filesystem::remove(index_path + ".tombstones");
}
}
std::cout << "====================================================================================\n";

return 0;
}
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ add_executable(rag_engine_tests
wal_test.cpp
index/test_hnsw.cpp
index/hnsw_tombstone_test.cpp
index/test_hnsw_sift_recall.cpp
test_compression.cpp
test_tokenizer.cpp
test_inverted_index.cpp
Expand Down
163 changes: 163 additions & 0 deletions tests/index/test_hnsw_sift_recall.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#include <gtest/gtest.h>
#include "rag_engine/index/hnsw.hpp"
#include "../sift_parser.hpp"
#include <vector>
#include <string>
#include <filesystem>
#include <algorithm>
#include <iostream>

using namespace rag_engine::index;
using namespace rag_engine::test_utils;

class HnswRecallTest : public ::testing::Test {
protected:
void SetUp() override {
// Path to the downloaded siftsmall dataset
dataset_dir = "../assets/datasets/siftsmall";
index_file = "sift_test_index.bin";

// Remove old index file if it exists
if (std::filesystem::exists(index_file)) {
std::filesystem::remove(index_file);
}
if (std::filesystem::exists(index_file + ".tombstones")) {
std::filesystem::remove(index_file + ".tombstones");
}
}

void TearDown() override {
// Cleanup index files
if (std::filesystem::exists(index_file)) {
std::filesystem::remove(index_file);
}
if (std::filesystem::exists(index_file + ".tombstones")) {
std::filesystem::remove(index_file + ".tombstones");
}
}

std::string dataset_dir;
std::string index_file;
};

// Calculate Recall@K
double calculate_recall(const std::vector<std::vector<SearchResult>>& results,
const std::vector<std::vector<int>>& ground_truth,
size_t k) {
size_t total_queries = results.size();
size_t hits = 0;

for (size_t i = 0; i < total_queries; ++i) {
const auto& result_cands = results[i];
const auto& truth_cands = ground_truth[i];

// We check if any of the top-K ground truth IDs are in the top-K results
// SIFT 1M / SIFTSmall uses Recall@1 (is the actual nearest neighbor in the top-K results)
// Let's compute Recall@K (Intersection size / K) or Recall@1 for standard ANN benchmarks.

// For standard ANN benchmarks (like ann-benchmarks), Recall is defined as:
// Number of returned results that are in the true top-K / K
size_t local_hits = 0;
size_t current_k = std::min(k, result_cands.size());

for (size_t j = 0; j < current_k; ++j) {
uint32_t res_id = result_cands[j].id;
// Check if res_id is in the top-K of ground truth
for (size_t t = 0; t < k; ++t) {
if (res_id == static_cast<uint32_t>(truth_cands[t])) {
local_hits++;
break;
}
}
}
hits += local_hits;
}

return static_cast<double>(hits) / (total_queries * k);
}

// Calculate Recall@1@K: Is the *true nearest neighbor* (truth[0]) present in the top-K returned results?
// This is another very common metric for ANN (e.g. SIFT1M paper)
double calculate_recall_1_at_k(const std::vector<std::vector<SearchResult>>& results,
const std::vector<std::vector<int>>& ground_truth,
size_t k) {
size_t total_queries = results.size();
size_t hits = 0;

for (size_t i = 0; i < total_queries; ++i) {
const auto& result_cands = results[i];
int true_nn = ground_truth[i][0]; // The actual closest neighbor

size_t current_k = std::min(k, result_cands.size());
for (size_t j = 0; j < current_k; ++j) {
if (result_cands[j].id == static_cast<uint32_t>(true_nn)) {
hits++;
break;
}
}
}

return static_cast<double>(hits) / total_queries;
}

TEST_F(HnswRecallTest, SiftSmallRecallGreaterThan95) {
// Check if dataset exists
std::string base_file = dataset_dir + "/siftsmall_base.fvecs";
std::string query_file = dataset_dir + "/siftsmall_query.fvecs";
std::string truth_file = dataset_dir + "/siftsmall_groundtruth.ivecs";

if (!std::filesystem::exists(base_file)) {
GTEST_SKIP() << "SIFTSmall dataset not found at " << dataset_dir << ". Skipping test.";
}

// Load data
std::cout << "Loading dataset..." << std::endl;
auto base_vectors = SiftParser::read_fvecs(base_file);
auto query_vectors = SiftParser::read_fvecs(query_file);
auto ground_truth = SiftParser::read_ivecs(truth_file);

ASSERT_EQ(base_vectors.size(), 10000);
ASSERT_EQ(query_vectors.size(), 100);
ASSERT_EQ(ground_truth.size(), 100);

size_t dim = base_vectors[0].size();
ASSERT_EQ(dim, 128);

// Initialize HNSW
HnswConfig config;
config.dim = dim;
config.max_elements = base_vectors.size();
config.M = 16;
config.M0 = 32;
config.ef_construction = 100;

std::cout << "Building HNSW index..." << std::endl;
HnswIndex index(index_file, config, false);

for (size_t i = 0; i < base_vectors.size(); ++i) {
index.add(i, base_vectors[i]);
}
index.sync();

// Query
std::cout << "Querying..." << std::endl;
size_t k = 10;
size_t ef_search = 50;
std::vector<std::vector<SearchResult>> all_results;
all_results.reserve(query_vectors.size());

for (const auto& q : query_vectors) {
all_results.push_back(index.search(q, k, ef_search));
}

// Evaluate
double recall_at_10 = calculate_recall(all_results, ground_truth, 10);
double recall_1_at_10 = calculate_recall_1_at_k(all_results, ground_truth, 10);

std::cout << "Recall@10: " << recall_at_10 << std::endl;
std::cout << "Recall@1@10: " << recall_1_at_10 << std::endl;

// HNSW should easily hit > 0.95 on SIFTSmall with ef=50
EXPECT_GE(recall_1_at_10, 0.95);
EXPECT_GE(recall_at_10, 0.90); // Exact top-10 overlap is usually slightly lower but should be very high
}
Loading
Loading