Repository navigation
Add hnsw_incremental_build benchmark - #6615
Conversation
📝 WalkthroughWalkthroughThe changes introduce a new benchmark tool for evaluating incremental building of HNSW indices in the codebase, implemented as Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (4)
✅ Files skipped from review due to trivial changes (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ Context from checks skipped due to timeout of 90000ms (14)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
lib/segment/benches/hnsw_incremental_build.rs (2)
152-161: Improve error handling for better debugging experience.The code uses many
unwrap()calls without context. Consider usingexpect()with descriptive messages or proper error handling.Example improvement:
- let dataset_file = File::open(dataset_path).unwrap(); + let dataset_file = File::open(&dataset_path) + .expect(&format!("Failed to open dataset file: {:?}", dataset_path)); dataset_mmap = unsafe { memmap2::Mmap::map(&dataset_file).unwrap() }; - dataset = ArrayView2::<f32>::view_npy(&dataset_mmap).unwrap(); + dataset = ArrayView2::<f32>::view_npy(&dataset_mmap) + .expect("Failed to parse numpy file - ensure it contains f32 data");
451-476: Consider using existing crates for human-readable number parsing.The custom number parsing implementation could be replaced with existing crates like
byte-unitor simplified.Consider using the
byte-unitcrate which provides similar functionality:use byte_unit::Byte; fn parse_number(n: &str) -> Result<usize, String> { // Parse as byte unit, then convert to number let bytes = n.parse::<Byte>() .map_err(|e| format!("Invalid number: {}", e))?; bytes.as_u64() .try_into() .map_err(|_| format!("Number too large: {}", n)) }Alternatively, if you want to keep the custom implementation, consider adding unit tests to ensure correctness.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (3)
lib/segment/Cargo.toml(3 hunks)lib/segment/benches/hnsw_incremental_build.rs(1 hunks)lib/segment/src/segment_constructor/simple_segment_constructor.rs(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (13)
- GitHub Check: test-consistency
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: Basic TLS/HTTPS tests
- GitHub Check: test-low-resources
- GitHub Check: test-snapshot-operations-s3-minio
- GitHub Check: test-consensus-compose
- GitHub Check: integration-tests
- GitHub Check: integration-tests-consensus
- GitHub Check: lint
- GitHub Check: storage-compat-test
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: rust-tests (macos-latest)
🔇 Additional comments (2)
lib/segment/Cargo.toml (1)
226-228: LGTM!The benchmark target configuration is correct for a custom benchmark implementation.
lib/segment/benches/hnsw_incremental_build.rs (1)
141-144: Well-designed caching and cleanup implementation!The caching mechanism using CARGO_TARGET_TMPDIR and proper cleanup of old segments shows good resource management practices.
Also applies to: 265-272
| size: dim, | ||
| distance, | ||
| storage_type: VectorStorageType::Memory, | ||
| storage_type: VectorStorageType::InRamChunkedMmap, |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
Verify the impact of changing the default vector storage type.
The change from VectorStorageType::Memory to VectorStorageType::InRamChunkedMmap affects the default behavior of build_simple_segment. Please verify:
- Is this change intended to affect all usages of this function, or just for the benchmark?
- Have all existing tests been validated with this new storage type?
- Should
build_simple_segment_with_payload_storageandbuild_multivec_segmentalso be updated for consistency?
Run the following script to check the usage of this function:
🏁 Script executed:
#!/bin/bash
# Description: Find all usages of build_simple_segment to assess impact
# Find all calls to build_simple_segment
echo "=== Searching for build_simple_segment usage ==="
rg -A 3 "build_simple_segment\(" --type rust
# Check if tests pass with the new storage type
echo -e "\n=== Checking test files that might be affected ==="
fd -e rs -t f | xargs rg -l "build_simple_segment" | grep -E "(test|spec)" | head -20Length of output: 12457
🏁 Script executed:
#!/bin/bash
# Display build_simple_segment implementation
echo "=== build_simple_segment ==="
rg -n "pub fn build_simple_segment" -A 50 lib/segment/src/segment_constructor/simple_segment_constructor.rs
# Display build_simple_segment_with_payload_storage implementation
echo -e "\n=== build_simple_segment_with_payload_storage ==="
rg -n "pub fn build_simple_segment_with_payload_storage" -A 50 lib/segment/src/segment_constructor/simple_segment_constructor.rs
# Display build_multivec_segment implementation
echo -e "\n=== build_multivec_segment ==="
rg -n "pub fn build_multivec_segment" -A 50 lib/segment/src/segment_constructorLength of output: 9564
Align vector storage types across all segment constructors
The default in build_simple_segment was changed to VectorStorageType::InRamChunkedMmap, but the other constructors still use VectorStorageType::Memory. This inconsistency can lead to unexpected behavior when consumers use build_simple_segment_with_payload_storage or build_multivec_segment.
Please update the storage type in:
- build_simple_segment_with_payload_storage (simple_segment_constructor.rs: line 63)
- build_multivec_segment (simple_segment_constructor.rs: lines 89 and 101)
so they also default to InRamChunkedMmap, unless there’s a deliberate reason to keep them as Memory. Also, ensure all existing tests and benchmarks pass with the new default.
🤖 Prompt for AI Agents
In lib/segment/src/segment_constructor/simple_segment_constructor.rs around
lines 35, 63, 89, and 101, the default vector storage type was changed to
VectorStorageType::InRamChunkedMmap only in build_simple_segment, causing
inconsistency with build_simple_segment_with_payload_storage and
build_multivec_segment which still use VectorStorageType::Memory. To fix this,
update the storage_type in build_simple_segment_with_payload_storage (line 63)
and both occurrences in build_multivec_segment (lines 89 and 101) to
VectorStorageType::InRamChunkedMmap to align defaults across all constructors.
After making these changes, run all existing tests and benchmarks to verify
compatibility with the new default storage type.
| .collect_vec(); | ||
|
|
||
| // Shuffle the dataset to avoid bias. | ||
| slices_vec.shuffle(&mut StdRng::from_rng(&mut main_rng)); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Ensure deterministic randomness for reproducible benchmarks.
Using StdRng::from_rng creates non-deterministic sub-RNGs. For reproducible benchmark results, consider using deterministic seeds.
Use deterministic seeding:
- slices_vec.shuffle(&mut StdRng::from_rng(&mut main_rng));
+ slices_vec.shuffle(&mut StdRng::seed_from_u64(42));Similarly for other RNG creations:
- let mut rng = StdRng::from_rng(&mut main_rng);
+ let mut rng = StdRng::seed_from_u64(43);Also applies to: 186-186, 192-192
🤖 Prompt for AI Agents
In lib/segment/benches/hnsw_incremental_build.rs at lines 173, 186, and 192, the
use of StdRng::from_rng with main_rng creates non-deterministic RNGs, which
affects reproducibility of benchmarks. Replace these with StdRng instances
seeded with fixed, deterministic seeds or derive seeds deterministically from
main_rng to ensure the randomness is reproducible across runs.
| // Load the dataset from a file. | ||
| (None, Some(dataset_path)) => { | ||
| let dataset_file = File::open(dataset_path).unwrap(); | ||
| dataset_mmap = unsafe { memmap2::Mmap::map(&dataset_file).unwrap() }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Document safety guarantees for unsafe memory mapping.
The unsafe memory mapping operation needs safety documentation explaining why this is safe (e.g., file is read-only, not modified during benchmark execution).
Add safety documentation:
let dataset_file = File::open(dataset_path).unwrap();
+ // SAFETY: The file is opened read-only and not modified during the benchmark.
+ // The mmap remains valid for the lifetime of dataset_mmap.
dataset_mmap = unsafe { memmap2::Mmap::map(&dataset_file).unwrap() };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| dataset_mmap = unsafe { memmap2::Mmap::map(&dataset_file).unwrap() }; | |
| let dataset_file = File::open(dataset_path).unwrap(); | |
| // SAFETY: The file is opened read-only and not modified during the benchmark. | |
| // The mmap remains valid for the lifetime of dataset_mmap. | |
| dataset_mmap = unsafe { memmap2::Mmap::map(&dataset_file).unwrap() }; |
🤖 Prompt for AI Agents
In lib/segment/benches/hnsw_incremental_build.rs at line 153, the unsafe block
performing memory mapping with memmap2::Mmap::map requires safety documentation.
Add a comment above this unsafe block explaining why it is safe, such as
confirming the dataset_file is opened read-only and remains unmodified during
the benchmark execution, ensuring no data races or invalid memory access occur.
| top, | ||
| ); | ||
| println!("iteration={iteration}, accuracy={accuracy}"); | ||
| assert!(accuracy > 0.4); |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Make accuracy threshold configurable to support different datasets.
The hardcoded accuracy threshold of 0.4 may not be appropriate for all datasets or configurations.
Add a CLI argument for minimum accuracy:
/// Check the accuracy every Nth iteration.
/// Set to 0 to disable accuracy checks.
#[clap(long, default_value = "1", value_parser(parse_number))]
accuracy_check_period: usize,
+
+ /// Minimum required accuracy (0.0 to 1.0).
+ /// The benchmark will panic if accuracy falls below this threshold.
+ #[clap(long, default_value = "0.4")]
+ min_accuracy: f64,
}Then use it:
println!("iteration={iteration}, accuracy={accuracy}");
- assert!(accuracy > 0.4);
+ assert!(
+ accuracy > args.min_accuracy,
+ "Accuracy {accuracy} is below minimum threshold {}",
+ args.min_accuracy
+ );Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In lib/segment/benches/hnsw_incremental_build.rs at line 260, the accuracy
threshold is hardcoded to 0.4, which limits flexibility for different datasets.
Modify the code to accept a CLI argument for the minimum accuracy threshold,
parse this argument at the start of the benchmark or test, and replace the
hardcoded 0.4 in the assert statement with the configurable value to allow
dynamic adjustment based on dataset or configuration.
2bffdc8 to
529923d
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
lib/segment/benches/hnsw_incremental_build.rs (2)
186-186:⚠️ Potential issueEnsure deterministic randomness for reproducible benchmarks.
Same issue as line 177 - using
StdRng::from_rngcreates non-deterministic sub-RNGs.Use deterministic seeding:
- let mut rng = StdRng::from_rng(&mut main_rng); + let mut rng = StdRng::seed_from_u64(44); // Use different seed than line 177And for line 192:
- let mut rng = StdRng::from_rng(&mut main_rng); + let mut rng = StdRng::seed_from_u64(45);Also applies to: 192-192
222-222:⚠️ Potential issueEnsure deterministic randomness for reproducible benchmarks.
Same issue as lines 177, 186, and 192 - using
StdRng::from_rngcreates non-deterministic sub-RNGs.Use deterministic seeding:
- let mut rng = StdRng::from_rng(&mut main_rng); + let mut rng = StdRng::seed_from_u64(46);
🧹 Nitpick comments (1)
lib/segment/benches/hnsw_incremental_build.rs (1)
310-329: Efficient hashing strategy for dataset identification.Excellent optimization to hash only the first and last 100 vectors while including dataset metadata. This provides a good balance between performance and collision resistance.
Consider documenting this hashing strategy in the function's doc comment to clarify why this approach is sufficient for cache key generation and what assumptions it makes about dataset uniqueness.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (3)
lib/segment/Cargo.toml(3 hunks)lib/segment/benches/hnsw_incremental_build.rs(1 hunks)lib/segment/src/segment_constructor/simple_segment_constructor.rs(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- lib/segment/src/segment_constructor/simple_segment_constructor.rs
- lib/segment/Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms (13)
- GitHub Check: test-low-resources
- GitHub Check: test-consistency
- GitHub Check: test-shard-snapshot-api-s3-minio
- GitHub Check: test-snapshot-operations-s3-minio
- GitHub Check: test-consensus-compose
- GitHub Check: storage-compat-test
- GitHub Check: integration-tests
- GitHub Check: rust-tests (macos-latest)
- GitHub Check: Basic TLS/HTTPS tests
- GitHub Check: rust-tests (ubuntu-latest)
- GitHub Check: integration-tests-consensus
- GitHub Check: rust-tests (windows-latest)
- GitHub Check: lint
🔇 Additional comments (4)
lib/segment/benches/hnsw_incremental_build.rs (4)
283-308: Well-implemented segment creation with proper randomization.Good use of the passed RNG for deterministic shuffling and correct handling of vector index wrapping with modulo operation.
331-382: Robust HNSW index building with effective caching.Good implementation with proper caching logic and configuration handling. The use of dummy resource permits is appropriate for benchmarking.
384-440: Excellent accuracy measurement implementation with smart optimizations.Great use of caching for expensive exact search results and parallel processing for performance. The accuracy calculation using set intersection is correct and efficient.
455-480: Excellent number parsing implementation with comprehensive unit support.The parser correctly handles underscores, SI prefixes (k, M, G, T), and binary prefixes (Ki, Mi, Gi, Ti), making the CLI very user-friendly. The implementation is robust with proper overflow checking.
529923d to
33f0f95
Compare
|
Note: this benchmark accepts datasets in the
help:
@echo "Available targets:"
@awk '/^# /{desc=substr($$0,3); next} /^[a-zA-Z0-9_/.-]+:/ {split($$0, a, ":"); if (desc) {printf "\033[36m%-35s\033[0m %s\n", a[1], desc}; desc=""}' $(MAKEFILE_LIST)
@echo
@echo "Set DATASETS to path to vector-db-benchmark/datasets to avoid re-downloading datasets"
# Download function
define dl
mkdir -p $$(dirname $@)
EXISTING=$$([ -n "$(DATASETS)" ] && find $(DATASETS) -name $(notdir $@) -print -quit); \
if [ -n "$$EXISTING" ]; \
then ln -sf "$$EXISTING" $@; \
else wget -c $(1) -O $@.tmp && mv $@.tmp $@; \
fi
endef
define hdf5tonpy
python -c 'import h5py, numpy, sys; f = h5py.File(sys.argv[1], "r"); data = numpy.concatenate([f["train"], f["test"]], axis=0); numpy.save(sys.argv[2], data)' $< $@
endef
# Start a shell with the required packages
shell:
nix-shell -p wget "python3.withPackages(p:[p.datasets p.h5py p.numpy])"
# 📥 Download laion (f16)
download/img_emb_0.npy:
$(call dl,https://deploy.laion.ai/8f83b608504d46bb81708ec86e912220/embeddings/img_emb/img_emb_0.npy)
# ♻️ Convert laion to npy/f32
out/img_emb_0_f32.npy: download/img_emb_0.npy
python -c 'import numpy as np; d = np.load("download/img_emb_0.npy"); np.save("out/img_emb_0_f32.npy", d.astype(np.float32))'
# 📥 Download dbpedia_openai_1M
download/dbpedia_openai_1M.tgz:
$(call dl,https://storage.googleapis.com/ann-filtered-benchmark/datasets/dbpedia_openai_1M.tgz)
# ♻️ Extract dbpedia_openai_1M to npy
out/dbpedia_openai_1M.npy: download/dbpedia_openai_1M.tgz
tar -xzf $< -O vectors.npy > $@.tmp
mv $@.tmp $@
# 📥 Download glove-100
download/glove-100-angular.hdf5:
$(call dl,http://ann-benchmarks.com/glove-100-angular.hdf5)
# ♻️ Convert glove-100 to npy
out/glove-100-angular.npy: download/glove-100-angular.hdf5
$(hdf5tonpy)
# 📥 Download gist-960
download/gist-960-euclidean.hdf5:
$(call dl,http://ann-benchmarks.com/gist-960-euclidean.hdf5)
# ♻️ Convert gist-960 to npy
out/gist-960-euclidean.npy: download/gist-960-euclidean.hdf5
$(hdf5tonpy)
# 📥 Download deep-image-96
download/deep-image-96-angular.hdf5:
$(call dl,http://ann-benchmarks.com/deep-image-96-angular.hdf5)
# ♻️ Convert deep-image-96 to npy
out/deep-image-96-angular.npy: download/deep-image-96-angular.hdf5
$(hdf5tonpy)
# 📥 Download cohere-wiki-1M
out/cohere-wiki-1m.npy:
./cohere.py $@
#!/usr/bin/env python3
import datasets
import numpy
import os
import sys
import tqdm
TARGET_ROWS = 1_000_000
out_path = sys.argv[1]
stream = datasets.load_dataset(
"Cohere/wikipedia-22-12-en-embeddings", split="train", streaming=True
)
stream = iter(stream)
first = next(stream)
dim = len(first["emb"])
vecs = numpy.lib.format.open_memmap(
out_path + ".tmp", mode="w+", dtype=numpy.float32, shape=(TARGET_ROWS, dim)
)
vecs[0] = first["emb"]
for i in tqdm.trange(1, TARGET_ROWS):
vecs[i] = numpy.asarray(next(stream)["emb"], numpy.float32)
del vecs
os.rename(out_path + ".tmp", out_path) |
This PR add a new benchmark for the
segmentcrate:hnsw_incremental_build.Unlike most of the other benchmarks, this benchmark is not a criterion benchmark but rather a CLI tool that measures build time/accuracy for a given dataset (random or real vectors from
.npy). It could be used to tune our incremental indexing algorithm implementation and check its quality.