Skip to content

Add hnsw_incremental_build benchmark - #6615

Merged
xzfc merged 1 commit into
devfrom
hnsw-incremental-benchmark
Jun 20, 2025
Merged

xzfc merged 1 commit into
devfrom
hnsw-incremental-benchmark

Conversation

@xzfc

@xzfc xzfc commented May 30, 2025

Copy link
Copy Markdown
Member

This PR add a new benchmark for the segment crate: 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.

@coderabbitai

coderabbitai Bot commented May 30, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The changes introduce a new benchmark tool for evaluating incremental building of HNSW indices in the codebase, implemented as hnsw_incremental_build.rs under the benches directory. This benchmark is configurable via command-line arguments, supports loading data from numpy files or generating random vectors, and measures both performance and accuracy of incremental HNSW index construction. To support this, new development dependencies on ndarray and ndarray-npy are added, and the clap crate is moved to workspace-level dependency management. The Distance enum is updated to derive EnumString, enabling parsing from strings.

Suggested reviewers

  • timvisee
  • coszio

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 529923d and 33f0f95.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • Cargo.toml (2 hunks)
  • lib/segment/Cargo.toml (2 hunks)
  • lib/segment/benches/hnsw_incremental_build.rs (1 hunks)
  • lib/segment/src/types.rs (2 hunks)
✅ Files skipped from review due to trivial changes (2)
  • lib/segment/src/types.rs
  • Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (2)
  • lib/segment/Cargo.toml
  • lib/segment/benches/hnsw_incremental_build.rs
⏰ Context from checks skipped due to timeout of 90000ms (14)
  • GitHub Check: test-snapshot-operations-s3-minio
  • GitHub Check: test-low-resources
  • GitHub Check: test-consistency
  • GitHub Check: Basic TLS/HTTPS tests
  • GitHub Check: test-shard-snapshot-api-s3-minio
  • GitHub Check: rust-tests (ubuntu-latest)
  • GitHub Check: rust-tests (windows-latest)
  • GitHub Check: test-consensus-compose
  • GitHub Check: integration-tests
  • GitHub Check: rust-tests (macos-latest)
  • GitHub Check: integration-tests-consensus
  • GitHub Check: rust-tests-no-rocksdb (ubuntu-latest)
  • GitHub Check: lint
  • GitHub Check: storage-compat-test
✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 using expect() 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-unit or simplified.

Consider using the byte-unit crate 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

📥 Commits

Reviewing files that changed from the base of the PR and between 01e5fab and 2bffdc8.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is 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

Comment thread lib/segment/Cargo.toml Resolved
size: dim,
distance,
storage_type: VectorStorageType::Memory,
storage_type: VectorStorageType::InRamChunkedMmap,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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:

  1. Is this change intended to affect all usages of this function, or just for the benchmark?
  2. Have all existing tests been validated with this new storage type?
  3. Should build_simple_segment_with_payload_storage and build_multivec_segment also 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 -20

Length 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_constructor

Length 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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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() };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

Suggested change
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ 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.

@xzfc
xzfc force-pushed the hnsw-incremental-benchmark branch from 2bffdc8 to 529923d Compare June 6, 2025 08:56

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
lib/segment/benches/hnsw_incremental_build.rs (2)

186-186: ⚠️ Potential issue

Ensure deterministic randomness for reproducible benchmarks.

Same issue as line 177 - using StdRng::from_rng creates 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 177

And 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 issue

Ensure deterministic randomness for reproducible benchmarks.

Same issue as lines 177, 186, and 192 - using StdRng::from_rng creates 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2bffdc8 and 529923d.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is 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.

@xzfc
xzfc force-pushed the hnsw-incremental-benchmark branch from 529923d to 33f0f95 Compare June 16, 2025 13:11
@xzfc
xzfc requested review from IvanPleshkov and generall June 20, 2025 13:22
@xzfc
xzfc merged commit f46a8ff into dev Jun 20, 2025
@xzfc
xzfc deleted the hnsw-incremental-benchmark branch June 20, 2025 14:10
@xzfc

xzfc commented Jun 30, 2025

Copy link
Copy Markdown
Member Author

Note: this benchmark accepts datasets in the npy/float32 format. Not all datasets are in this format, so I use these scripts to download and convert some datasets:

Makefile

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 $@

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants