Skip to content

Implement LeaNN hub node pruning for vector similarity index - #94545

Closed
zex-hyd wants to merge 33 commits into
ClickHouse:masterfrom
zex-hyd:feature/leann-hub-pruning
Closed

zex-hyd wants to merge 33 commits into
ClickHouse:masterfrom
zex-hyd:feature/leann-hub-pruning

Conversation

@zex-hyd

@zex-hyd zex-hyd commented Jan 18, 2026 •

Copy link
Copy Markdown

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

  • New Feature

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 is written (mandatory for new features)

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_similarity index type. Use 'enable_hub_pruning' or 'true' to enable hub node pruning, or empty string/'false' to disable (default).

Example use:

CREATE TABLE table
(
  vectors Array(Float32),
  INDEX idx vectors TYPE vector_similarity('hnsw', 'L2Distance', 128, 'bf16', 32, 128, 'enable_hub_pruning')
)
ENGINE = MergeTree
ORDER BY id;

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 LeaNNParams struct with enable_hub_pruning flag and implements performHubPruning() using search-based sampling. Vectors are stored during construction when hub pruning is enabled. The 7th argument is parsed and validated in vectorSimilarityIndexCreator() and vectorSimilarityIndexValidator(). FILE_FORMAT_VERSION is incremented to 2.

@zex-hyd

zex-hyd commented Jan 18, 2026 •

Copy link
Copy Markdown
Author

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!
Relevant Link:
unum-cloud/USearch#662
#94544

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Jan 18, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jan 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f59b8ad]

Summary: ❌

job_name test_name status info comment
Fast test failure
02995_new_settings_history FAIL cidb
Build (arm_tidy) failure
Build ClickHouse failure cidb
Docs check dropped
Build (amd_debug) dropped
Build (amd_asan) dropped
Build (amd_tsan) dropped
Build (amd_msan) dropped
Build (amd_ubsan) dropped
Build (amd_binary) dropped
Build (arm_asan) dropped

@zex-hyd
zex-hyd force-pushed the feature/leann-hub-pruning branch from 6fe6987 to 194aa15 Compare January 18, 2026 23:44
@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jan 18, 2026
@shankar-iyer shankar-iyer self-assigned this Jan 19, 2026
@zex-hyd

zex-hyd commented Jan 19, 2026

Copy link
Copy Markdown
Author

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!

Comment thread PR_DESCRIPTION.md Resolved
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would the new code better fit into usearch?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@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

@zex-hyd
zex-hyd force-pushed the feature/leann-hub-pruning branch 2 times, most recently from b2157ca to 2b7faf8 Compare January 19, 2026 19:42
@zex-hyd
zex-hyd force-pushed the feature/leann-hub-pruning branch from 2b7faf8 to e9e7bae Compare January 19, 2026 19:53
@zex-hyd
zex-hyd force-pushed the feature/leann-hub-pruning branch from e9e7bae to 4b880cb Compare January 19, 2026 19:57
- `<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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Instead of passing a binary on/off parameter, is it possible to pass a numeric parameter that controls the aggressiveness of pruning?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think that we shoud not artificially distinguish the cases of six and seven passed arguments. We should only accept seven arguments.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

When and how is the data in stored_vectors released?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Comment gets updated!


/// 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The sample size is ideally passed as a parameter from SQL.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Below is copypasta of existing code :-(

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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!

@rschu1ze

Copy link
Copy Markdown
Member

Thanks @zex-hyd . We'll discuss internally if we like to go forward with this contribution or not.

@zex-hyd

zex-hyd commented Jan 24, 2026

Copy link
Copy Markdown
Author

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.
For this PR, please let me know if there's any additional information or changes while the team discusses.

Happy to provide clarification or make adjustments as needed.

@rschu1ze

rschu1ze commented Feb 2, 2026 •

Copy link
Copy Markdown
Member

@zex-hyd We thought a bit about this:

  1. I haven't seen LeaNN implemented elsewhere, so users will not be familiar with it,
  2. Related to that, there are no best practices which settings (pruning ratio) to select,
  3. Pruning goes only so far when it comes to space saving, the real solution for large indexes will be SPANN and friends.

I'd therefore would close this PR - thanks a lot again for your effort.

@rschu1ze rschu1ze closed this Feb 2, 2026
@zex-hyd

zex-hyd commented Feb 2, 2026 •

Copy link
Copy Markdown
Author

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!

@rschu1ze

rschu1ze commented Feb 2, 2026

Copy link
Copy Markdown
Member

@alexey-milovidov

Copy link
Copy Markdown
Member

It's an interesting pull request. Maybe something else will be happy to review?

@zex-hyd

zex-hyd commented Feb 3, 2026

Copy link
Copy Markdown
Author

Thank you @alexey-milovidov for reopening this! Happy to
address any additional feedback or review from clickhouse.

If the team ultimately decides LeaNN isn't the right direction,
I'd also be interested in exploring the SPANN approach
@rschu1ze mentioned - happy to open a design issue or
prototype PR for that if it would be helpful!!


runner.enqueueAndKeepTrack([&pruned_index, &vector, new_key]
{
auto result = pruned_index->add(new_key, vector.data());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@zex-hyd zex-hyd Feb 3, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

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!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@zex-hyd

zex-hyd commented Apr 5, 2026 •

Copy link
Copy Markdown
Author

I will be working on the SPANN as expected here, and will continue to make changes on the same PR here!!

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

Labels

can be tested Allows running workflows for external contributors pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants