|
| 1 | +// SPDX-License-Identifier: Apache-2.0 OR MIT |
| 2 | +// Benchmark: HNSW ef_construction sweep for validating for_corpus() thresholds |
| 3 | +// |
| 4 | +// Tests ef_construction values from 50 to 400 across different corpus sizes |
| 5 | +// to determine the minimum ef_construction needed for acceptable recall. |
| 6 | +// |
| 7 | +// This directly validates whether ef_construction=100 (current for_corpus() |
| 8 | +// default for <100K corpora) is sufficient, or whether 200 should be the floor. |
| 9 | +// |
| 10 | +// Usage: |
| 11 | +// ./hnsw_ef_sweep_benchmark [--corpus=N] [--queries=N] [--dim=N] [--M=N] |
| 12 | + |
| 13 | +#include <algorithm> |
| 14 | +#include <chrono> |
| 15 | +#include <cmath> |
| 16 | +#include <cstdio> |
| 17 | +#include <cstdlib> |
| 18 | +#include <cstring> |
| 19 | +#include <numeric> |
| 20 | +#include <random> |
| 21 | +#include <span> |
| 22 | +#include <thread> |
| 23 | +#include <unordered_set> |
| 24 | +#include <vector> |
| 25 | + |
| 26 | +#include <sqlite-vec-cpp/distances/cosine.hpp> |
| 27 | +#include <sqlite-vec-cpp/distances/l2.hpp> |
| 28 | +#include <sqlite-vec-cpp/index/hnsw.hpp> |
| 29 | + |
| 30 | +using namespace sqlite_vec_cpp::index; |
| 31 | +using namespace sqlite_vec_cpp::distances; |
| 32 | + |
| 33 | +// ============================================================================ |
| 34 | +// Configuration |
| 35 | +// ============================================================================ |
| 36 | + |
| 37 | +struct EFSweepConfig { |
| 38 | + size_t corpus_size = 10000; |
| 39 | + size_t num_queries = 100; |
| 40 | + size_t dim = 768; |
| 41 | + size_t k = 10; |
| 42 | + size_t M = 16; // fixed M for this sweep |
| 43 | + // ef_construction values to sweep |
| 44 | + std::vector<size_t> ef_construction_values = {50, 100, 150, 200, 250, 300, 400, 500}; |
| 45 | + // ef_search values to test per ef_construction |
| 46 | + std::vector<size_t> ef_search_values = {50, 100, 200, 400}; |
| 47 | + uint32_t seed = 42; |
| 48 | + bool use_l2 = false; |
| 49 | +}; |
| 50 | + |
| 51 | +static EFSweepConfig parseArgs(int argc, char* argv[]) { |
| 52 | + EFSweepConfig cfg; |
| 53 | + for (int i = 1; i < argc; ++i) { |
| 54 | + if (strncmp(argv[i], "--corpus=", 9) == 0) |
| 55 | + cfg.corpus_size = std::stoul(argv[i] + 9); |
| 56 | + else if (strncmp(argv[i], "--queries=", 10) == 0) |
| 57 | + cfg.num_queries = std::stoul(argv[i] + 10); |
| 58 | + else if (strncmp(argv[i], "--dim=", 6) == 0) |
| 59 | + cfg.dim = std::stoul(argv[i] + 6); |
| 60 | + else if (strncmp(argv[i], "--k=", 4) == 0) |
| 61 | + cfg.k = std::stoul(argv[i] + 4); |
| 62 | + else if (strncmp(argv[i], "--M=", 4) == 0) |
| 63 | + cfg.M = std::stoul(argv[i] + 4); |
| 64 | + else if (strncmp(argv[i], "--seed=", 7) == 0) |
| 65 | + cfg.seed = std::stoul(argv[i] + 7); |
| 66 | + else if (strcmp(argv[i], "--l2") == 0) |
| 67 | + cfg.use_l2 = true; |
| 68 | + else if (strcmp(argv[i], "--help") == 0) { |
| 69 | + printf("Usage: %s [options]\n", argv[0]); |
| 70 | + printf(" --corpus=N Corpus size (default: 10000)\n"); |
| 71 | + printf(" --queries=N Number of queries (default: 100)\n"); |
| 72 | + printf(" --dim=N Vector dimension (default: 768)\n"); |
| 73 | + printf(" --k=N Top-K results (default: 10)\n"); |
| 74 | + printf(" --M=N HNSW M parameter (default: 16)\n"); |
| 75 | + printf(" --seed=N Random seed (default: 42)\n"); |
| 76 | + printf(" --l2 Use L2 distance (default: cosine)\n"); |
| 77 | + exit(0); |
| 78 | + } |
| 79 | + } |
| 80 | + return cfg; |
| 81 | +} |
| 82 | + |
| 83 | +// ============================================================================ |
| 84 | +// Data Generation |
| 85 | +// ============================================================================ |
| 86 | + |
| 87 | +static std::vector<float> generateVector(size_t dim, std::mt19937& rng, bool normalize = true) { |
| 88 | + std::uniform_real_distribution<float> dist(-1.0f, 1.0f); |
| 89 | + std::vector<float> vec(dim); |
| 90 | + float norm = 0.0f; |
| 91 | + for (auto& v : vec) { |
| 92 | + v = dist(rng); |
| 93 | + norm += v * v; |
| 94 | + } |
| 95 | + if (normalize && norm > 0.0f) { |
| 96 | + norm = std::sqrt(norm); |
| 97 | + for (auto& v : vec) |
| 98 | + v /= norm; |
| 99 | + } |
| 100 | + return vec; |
| 101 | +} |
| 102 | + |
| 103 | +static std::vector<std::vector<float>> generateDataset(size_t count, size_t dim, |
| 104 | + std::mt19937& rng) { |
| 105 | + std::vector<std::vector<float>> data; |
| 106 | + data.reserve(count); |
| 107 | + for (size_t i = 0; i < count; ++i) { |
| 108 | + data.push_back(generateVector(dim, rng)); |
| 109 | + } |
| 110 | + return data; |
| 111 | +} |
| 112 | + |
| 113 | +// ============================================================================ |
| 114 | +// Ground Truth |
| 115 | +// ============================================================================ |
| 116 | + |
| 117 | +static std::vector<std::unordered_set<size_t>> |
| 118 | +computeGroundTruth(const std::vector<std::vector<float>>& queries, |
| 119 | + const std::vector<std::vector<float>>& corpus, size_t k, bool use_l2) { |
| 120 | + const size_t numQueries = queries.size(); |
| 121 | + const size_t numThreads = std::min<size_t>(std::thread::hardware_concurrency(), numQueries); |
| 122 | + |
| 123 | + std::vector<std::unordered_set<size_t>> gtSets(numQueries); |
| 124 | + std::vector<std::thread> threads; |
| 125 | + |
| 126 | + auto worker = [&](size_t start, size_t end) { |
| 127 | + CosineMetric<float> cosineMetric; |
| 128 | + L2Metric<float> l2Metric; |
| 129 | + for (size_t q = start; q < end; ++q) { |
| 130 | + std::vector<std::pair<size_t, float>> dists; |
| 131 | + dists.reserve(corpus.size()); |
| 132 | + std::span<const float> qspan{queries[q]}; |
| 133 | + for (size_t i = 0; i < corpus.size(); ++i) { |
| 134 | + std::span<const float> cspan{corpus[i]}; |
| 135 | + float d = use_l2 ? l2Metric(qspan, cspan) : cosineMetric(qspan, cspan); |
| 136 | + dists.emplace_back(i, d); |
| 137 | + } |
| 138 | + std::partial_sort(dists.begin(), dists.begin() + static_cast<ptrdiff_t>(k), dists.end(), |
| 139 | + [](auto& a, auto& b) { return a.second < b.second; }); |
| 140 | + for (size_t i = 0; i < k; ++i) { |
| 141 | + gtSets[q].insert(dists[i].first); |
| 142 | + } |
| 143 | + } |
| 144 | + }; |
| 145 | + |
| 146 | + size_t chunk = (numQueries + numThreads - 1) / numThreads; |
| 147 | + for (size_t t = 0; t < numThreads; ++t) { |
| 148 | + size_t start = t * chunk; |
| 149 | + size_t end = std::min(start + chunk, numQueries); |
| 150 | + if (start < end) { |
| 151 | + threads.emplace_back(worker, start, end); |
| 152 | + } |
| 153 | + } |
| 154 | + for (auto& t : threads) { |
| 155 | + t.join(); |
| 156 | + } |
| 157 | + return gtSets; |
| 158 | +} |
| 159 | + |
| 160 | +// ============================================================================ |
| 161 | +// Result |
| 162 | +// ============================================================================ |
| 163 | + |
| 164 | +struct EFSweepResult { |
| 165 | + size_t ef_construction; |
| 166 | + size_t ef_search; |
| 167 | + double buildTimeMs; |
| 168 | + double searchLatencyUs; |
| 169 | + double qps; |
| 170 | + double recall; |
| 171 | +}; |
| 172 | + |
| 173 | +static void printHeader() { |
| 174 | + printf("%-16s | %-12s | %-12s | %-12s | %-12s | %-10s\n", "ef_construction", "ef_search", |
| 175 | + "Build(ms)", "Latency(us)", "QPS", "Recall@10"); |
| 176 | + printf("-----------------+--------------+--------------+-" |
| 177 | + "-------------+--------------+-----------\n"); |
| 178 | +} |
| 179 | + |
| 180 | +static void printRow(const EFSweepResult& r) { |
| 181 | + printf("%-16zu | %-12zu | %10.1f | %10.1f | %10.0f | %8.2f%%\n", r.ef_construction, |
| 182 | + r.ef_search, r.buildTimeMs, r.searchLatencyUs, r.qps, r.recall); |
| 183 | +} |
| 184 | + |
| 185 | +// ============================================================================ |
| 186 | +// Main |
| 187 | +// ============================================================================ |
| 188 | + |
| 189 | +int main(int argc, char* argv[]) { |
| 190 | + EFSweepConfig cfg = parseArgs(argc, argv); |
| 191 | + |
| 192 | + printf("# HNSW ef_construction Sweep Benchmark\n"); |
| 193 | + printf("# Corpus: %zu vectors, %zud, M=%zu, k=%zu\n", cfg.corpus_size, cfg.dim, cfg.M, cfg.k); |
| 194 | + printf("# Metric: %s\n\n", cfg.use_l2 ? "L2" : "cosine"); |
| 195 | + |
| 196 | + // Generate data |
| 197 | + std::mt19937 rng(cfg.seed); |
| 198 | + auto corpus = generateDataset(cfg.corpus_size, cfg.dim, rng); |
| 199 | + auto queries = generateDataset(cfg.num_queries, cfg.dim, rng); |
| 200 | + |
| 201 | + printf("# Computing ground truth...\n"); |
| 202 | + fflush(stdout); |
| 203 | + auto gtSets = computeGroundTruth(queries, corpus, cfg.k, cfg.use_l2); |
| 204 | + printf("# Ground truth computed.\n\n"); |
| 205 | + |
| 206 | + printHeader(); |
| 207 | + |
| 208 | + for (size_t efc : cfg.ef_construction_values) { |
| 209 | + printf("# Building HNSW with ef_construction=%zu...\n", efc); |
| 210 | + fflush(stdout); |
| 211 | + |
| 212 | + HNSWIndex<float, CosineMetric<float>>::Config hnswCfg; |
| 213 | + hnswCfg.M = cfg.M; |
| 214 | + hnswCfg.M_max = cfg.M * 2; |
| 215 | + hnswCfg.M_max_0 = cfg.M * 4; |
| 216 | + hnswCfg.ef_construction = efc; |
| 217 | + hnswCfg.normalize_vectors = !cfg.use_l2; |
| 218 | + hnswCfg.random_seed = cfg.seed; |
| 219 | + |
| 220 | + HNSWIndex<float, CosineMetric<float>> idx(hnswCfg); |
| 221 | + |
| 222 | + auto buildStart = std::chrono::high_resolution_clock::now(); |
| 223 | + idx.reserve(corpus.size()); |
| 224 | + for (size_t i = 0; i < corpus.size(); ++i) { |
| 225 | + idx.insert_single_threaded(i, std::span<const float>{corpus[i]}); |
| 226 | + } |
| 227 | + auto buildEnd = std::chrono::high_resolution_clock::now(); |
| 228 | + double buildMs = |
| 229 | + std::chrono::duration<double, std::milli>(buildEnd - buildStart).count(); |
| 230 | + |
| 231 | + for (size_t ef : cfg.ef_search_values) { |
| 232 | + size_t totalHits = 0; |
| 233 | + auto searchStart = std::chrono::high_resolution_clock::now(); |
| 234 | + for (size_t q = 0; q < queries.size(); ++q) { |
| 235 | + auto res = idx.search_read_mostly(std::span<const float>{queries[q]}, cfg.k, ef); |
| 236 | + for (const auto& [id, _] : res) { |
| 237 | + if (gtSets[q].count(id)) |
| 238 | + ++totalHits; |
| 239 | + } |
| 240 | + } |
| 241 | + auto searchEnd = std::chrono::high_resolution_clock::now(); |
| 242 | + double totalUs = |
| 243 | + std::chrono::duration<double, std::micro>(searchEnd - searchStart).count(); |
| 244 | + double latencyUs = totalUs / static_cast<double>(queries.size()); |
| 245 | + double qps = 1e6 / latencyUs; |
| 246 | + double recall = 100.0 * static_cast<double>(totalHits) / |
| 247 | + static_cast<double>(queries.size() * cfg.k); |
| 248 | + |
| 249 | + printRow(EFSweepResult{efc, ef, buildMs, latencyUs, qps, recall}); |
| 250 | + } |
| 251 | + printf("\n"); |
| 252 | + fflush(stdout); |
| 253 | + } |
| 254 | + |
| 255 | + printf("# Done.\n"); |
| 256 | + return 0; |
| 257 | +} |
0 commit comments