Repository navigation
Conversation
|
Hi @alexey-milovidov @rschu1ze, I'm working on "LeanNN Indexing feature" from this internship 2025/2026 list #87836 . I've opened this ticket with a proposed approach. Would appreciate any feedback on whether the direction makes sense! |
|
Workflow [PR], commit [f59b8ad] Summary: ❌
|
6fe6987 to
194aa15
Compare
|
Hi @shankar-iyer Thank you for taking on this issue! I'm still actively working on the implementation and making updates to address CI checes! |
| LoggerPtr logger = getLogger("VectorSimilarityIndex"); | ||
| LOG_TRACE(logger, "Starting hub node pruning. Index size before pruning: {}", index->size()); | ||
|
|
||
| /// Step 1: Identify hub nodes via search-based sampling |
There was a problem hiding this comment.
Would the new code better fit into usearch?
There was a problem hiding this comment.
@rschu1ze @shankar-iyer Thanks for reviewing this PR! I really appreciated!
I checked the USearch codebase, and there's no public API to access individual node connectivity or visit counts. The existing APIs (stats(), iterators, etc...) only provide aggregate statistics or node keys, not graph structure
The current approach in this PR uses search results as a proxy for hub nodes, which works without USearch changes. It basically is the technique-02 as mentioned in the doc / issue
b2157ca to
2b7faf8
Compare
2b7faf8 to
e9e7bae
Compare
e9e7bae to
4b880cb
Compare
| - `<quantization>` controls the quantization of the vectors in the proximity graph. Possible values are `f64`, `f32`, `f16`, `bf16`, `i8`, or `b1`. The default value is `bf16`. Note that this parameter does not affect the representation of the vectors in the underlying column. | ||
| - `<hnsw_max_connections_per_layer>` controls the number of neighbors per graph node, also known as HNSW hyperparameter `M`. The default value is `32`. Value `0` means using the default value. | ||
| - `<hnsw_candidate_list_size_for_construction>` controls the size of the dynamic candidate list during construction of the HNSW graph, also known as HNSW hyperparameter `ef_construction`. The default value is `128`. Value `0` means using the default value. | ||
| - `<leann_params>` specifies LeaNN optimization parameters. Use `'enable_hub_pruning'` or `'true'` to enable hub node pruning, which reduces index size by approximately 50% while maintaining search quality. Use an empty string or `'false'` to disable (default). Hub node pruning identifies and retains only highly connected "hub" nodes during index construction, resulting in a smaller index with minimal recall loss. |
There was a problem hiding this comment.
Instead of passing a binary on/off parameter, is it possible to pass a numeric parameter that controls the aggressiveness of pruning?
There was a problem hiding this comment.
I switched the implementation to a numeric hub_pruning_ratio (from 0.0 to1.0) to control pruning aggressiveness. Accepts numeric values like '0.3' or '0.5' to set the ratio of nodes to keep, with 'true'/'enable_hub_pruning' defaulting to 0.5 for backward compatibility. The pruning logic uses target_hub_nodes = index->size() * hub_pruning_ratio to tune the size/recall trade-off.
| /// Check number and type of arguments | ||
| if (!has_three_args && !has_six_args) | ||
| throw Exception(ErrorCodes::INCORRECT_QUERY, "Vector similarity index must have three or six arguments"); | ||
| if (!has_three_args && !has_six_args && !has_seven_args) |
There was a problem hiding this comment.
I think that we shoud not artificially distinguish the cases of six and seven passed arguments. We should only accept seven arguments.
There was a problem hiding this comment.
The index now only accepts 3 arguments (basic) or 7 arguments (with all optional parameters including LeaNN). If you specify quantization and HNSW parameters, the 7th argument (hub_pruning_ratio) is now required
| { | ||
| size_t start = (row == 0) ? 0 : column_array_offsets[row - 1]; | ||
| size_t end = column_array_offsets[row]; | ||
| stored_vectors.emplace_back(data.begin() + start, data.begin() + end); |
There was a problem hiding this comment.
When and how is the data in stored_vectors released?
There was a problem hiding this comment.
Released in getGranuleAndReset() at line 492 via stored_vectors.clear(). Vectors accumulate during update() calls, are used for hub pruning if enabled, then cleared immediately after the granule is created. Memory is released via RAII when the inner vectors are destroyed.
| namespace | ||
| { | ||
|
|
||
| /// Perform hub node pruning on the HNSW graph (LeaNN Technique 2). |
There was a problem hiding this comment.
Let's include this URL: https://arxiv.org/pdf/2506.08276 . There is also no "technique 2" (this was my numbering in unum-cloud/USearch#662), you can instead mention "Section 5" of the paper.
|
|
||
| /// Perform hub node pruning on the HNSW graph (LeaNN Technique 2). | ||
| /// Hub nodes are highly connected nodes that span wide areas of the vector space. | ||
| /// This function identifies and keeps only hub nodes, reducing graph size by ~50% with minimal recall loss. |
There was a problem hiding this comment.
The statement about "minimal recall loss" must be proven by an experiment, please :-)
|
|
||
| /// Step 1: Identify hub nodes via search-based sampling | ||
| /// Perform multiple random searches and count how often each node is visited | ||
| const size_t num_samples = std::min(static_cast<size_t>(100), index->size()); /// Sample up to 100 random queries |
There was a problem hiding this comment.
The sample size is ideally passed as a parameter from SQL.
There was a problem hiding this comment.
Made sample_size configurable via SQL parameter.
The 7th argument now supports key-value format like 'ratio=0.5,sample_size=200' to set both the pruning ratio and sample size. Backward compatibility is maintained - simple numeric values or boolean strings still work as before. Default sample_size is 100 if not specified.
| const size_t num_samples = std::min(static_cast<size_t>(100), index->size()); /// Sample up to 100 random queries | ||
| std::unordered_map<USearchIndex::vector_key_t, size_t> node_visit_counts; | ||
|
|
||
| /// Use a subset of stored vectors as random query vectors |
There was a problem hiding this comment.
I think the sampling method of using only inserted values will distort results. Samplig with true random vectors will be much better. Could you please calculate the minimum and maximum for each dimension and create N random vectors for sampling based on that? This will also have the advantage that we don't need to buffer all original vectors.
There was a problem hiding this comment.
Related to that, it will be even better if useearch had an API (or you could add one) which would allow to return the N most connected nodes directly. In the end, sampling is a crutch to do that.
There was a problem hiding this comment.
Switched to random vectors for sampling. The code calculates min/max bounds per dimension from stored vectors and generates random query vectors within those bounds. This avoids distortion from using only inserted values and improves sampling accuracy.
| unum::usearch::index_limits_t limits(roundUpToPowerOfTwoOrZero(hub_node_keys.size()), max_thread_pool_size); | ||
| pruned_index->reserve(limits); | ||
|
|
||
| /// Add hub nodes to new index |
There was a problem hiding this comment.
Below is copypasta of existing code :-(
There was a problem hiding this comment.
Thanks! I’ve refactored the common index build logic into the helpers reserveIndexForSize and runBuildIndexTasks and now reuse them in both the normal build path and performHubPruning!
… parameters" This reverts commit 38219f2.
|
Thanks @zex-hyd . We'll discuss internally if we like to go forward with this contribution or not. |
Thank you @rschu1ze! I appreciate you taking the time to review this. Happy to provide clarification or make adjustments as needed. |
|
@zex-hyd We thought a bit about this:
I'd therefore would close this PR - thanks a lot again for your effort. |
|
Thank you @rschu1ze for the thoughtful evaluation, clear explanation, and the helpful references. I understand the decision to focus on established solutions with proven best practices! Either way, this was a valuable learning experience. And I'll take a look at the SPANN and friends resources you linked. One more question here: Are there any existing issues or design work related to these approaches (SPANN and friends) where I could contribute? I am happy to explore how they might fit into ClickHouse's vector search roadmap! |
|
https://turbopuffer.com/blog/ann-v3 has a quite cool SPANN implementation. |
|
It's an interesting pull request. Maybe something else will be happy to review? |
|
Thank you @alexey-milovidov for reopening this! Happy to If the team ultimately decides LeaNN isn't the right direction, |
|
|
||
| runner.enqueueAndKeepTrack([&pruned_index, &vector, new_key] | ||
| { | ||
| auto result = pruned_index->add(new_key, vector.data()); |
There was a problem hiding this comment.
Hey @zex-hyd Thank you so much for your interests in helping vector search in ClickHouse!
I agree with Robert's point here : #94545 (comment)
Looking at the logic here, are you re-constructing a new graph containing only the original hub nodes shortlisted in hub_node_keys ? So if the ratio is 0.50, then 50% of the original documents/vectors are no longer reachable and will never appear in results? I think LeaNN's idea was to : serialize/persist all edges of the hub nodes (e.g 2% are hub nodes) and serialize/persist only very few edges of the non-hub nodes. But the graph connectivity is preserved, the hub nodes can still be used to navigate to the non-hub nodes.
There was a problem hiding this comment.
Thank you @shankar-iyer for catching this.
I've re-examined the LeaNN paper (section 5 ) and confirmed that the correct Technique 2 is edge pruning: keeping all nodes in the graph while limiting hub nodes to M edges and non-hub nodes to m edges. My current implementation does node removal instead - only keeping ~50% of hub nodes and discarding the rest.
Also after checking USearch's API, it doesn't expose per-node graph manipulation - the neighbor structure is completely internal.
If we wanted to implement proper edge pruning without modifying USearch, we'd need to build a custom HNSW graph implementation in ClickHouse with native control over the adjacency structure. That would be a substantial undertaking though, essentially replacing USearch for this index type.
Given this constraint and @rschu1ze's point about SPANN being the better long-term direction. DO you think a custom graph implementation would be valuable for ClickHouse's roadmap.
What do you think makes most sense?
Thanks for the thorough review - learned a lot from this!
There was a problem hiding this comment.
Let's go directly for SPANN. Microsoft has an implementation. It looks quite complex though and it seems easier to re-implement it by ourselves. The original paper uses hierarchical balanced clustering but I think we can start with simple sampling and see how far this gets us (i.e. iterate incrementally from there). There are also other implementations of SPANN on GitHub, please search for them for inspiration.
|
I will be working on the SPANN as expected here, and will continue to make changes on the same PR here!! |
This implements LeaNN hub node pruning for vector similarity indexes to reduce index size by ~50% with minimal recall loss.
Related issue: #94544
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add hub node pruning for vector similarity indexes. Enable with 7th argument 'enable_hub_pruning' to reduce index size by approximately 50% while maintaining search quality.
Documentation entry for user-facing changes
Documentation will be added for the new 7th argument to vector_similarity index type.
Motivation: Hub node pruning reduces vector similarity index storage requirements by ~50% while maintaining search quality, useful for large-scale vector search applications where storage is a concern.
Parameters: Add a 7th argument to
vector_similarityindex type. Use'enable_hub_pruning'or'true'to enable hub node pruning, or empty string/'false'to disable (default).Example use:
Implementation
Implements Technique 2 from LeaNN paper for hub node pruning. When enabled, the index construction identifies hub nodes (highly connected nodes spanning wide areas) and rebuilds the graph with only these nodes, reducing index size by ~50% with minimal recall loss.
Hub nodes are identified via search-based sampling during construction. The code performs random searches to find frequently visited nodes, selects the top 50% as hub nodes, then rebuilds the index. Since USearch doesn't expose graph structure directly, this is implemented on the ClickHouse side.
The code adds a
LeaNNParamsstruct withenable_hub_pruningflag and implementsperformHubPruning()using search-based sampling. Vectors are stored during construction when hub pruning is enabled. The 7th argument is parsed and validated invectorSimilarityIndexCreator()andvectorSimilarityIndexValidator().FILE_FORMAT_VERSIONis incremented to 2.