Skip to content

Initial support for running vector similarity searches from analyzer - #71545

Merged
rschu1ze merged 13 commits into
ClickHouse:masterfrom
rschu1ze:vec-sim-idx-analyzer
Dec 16, 2024
Merged

rschu1ze merged 13 commits into
ClickHouse:masterfrom
rschu1ze:vec-sim-idx-analyzer

Conversation

@rschu1ze

@rschu1ze rschu1ze commented Nov 6, 2024 •

Copy link
Copy Markdown
Member

The vector similarity index is a special secondary index which speeds up queries of the form

SELECT [...]
FROM tab, [...]
ORDER BY distance_function(vec, reference_vec), [...]
LIMIT N

where

  • distance_function is function 'L2Distance' or 'cosineDistance',
  • vec is a column of tab (*),
  • reference_vec is a literal of type Array(Float32/Float64)

(see here for more details).

Previously, the index analyzed the query AST and extracted distance_function, vec and reference_vec from it (this was done by the code in src/Storages/MergeTree/VectorSimilarityCondition.h, deleted in this PR). As this approach did not work with the analyzer, this PR re-implements the logic as an optimization pass (--> src/Processors/QueryPlan/Optimizations/useVectorSearch.cpp). A new struct VectorSearchParameters is added to ReadFromMergeTree which contains all necessary data to perform a vector search.

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Enable analyzer support for vector search

@robot-clickhouse robot-clickhouse added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 6, 2024
@robot-ch-test-poll4

robot-ch-test-poll4 commented Nov 6, 2024 •

Copy link
Copy Markdown
Contributor

This is an automated comment for commit b34f28a with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Check nameDescriptionStatus
BuildsThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Successful checks
Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help✅ success
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integration tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success

@rschu1ze rschu1ze added the do not test disable testing on pull request label Nov 7, 2024
@novikd novikd self-assigned this Nov 7, 2024
This code is extremely shameful, don't look at it.

Only goal of this PR is to demonstrate that the analyzer is able to see
vector similarity indexes:

ip-10-19-83-181.eu-central-1.compute.internal :) explain plan indexes=1 SELECT id, vec, L2Distance(vec, [0.0, 2.0])
FROM tab
ORDER BY L2Distance(vec, [0.0, 2.0])
LIMIT 3 settings enable_analyzer = 1

EXPLAIN indexes = 1
SELECT
    id,
    vec,
    L2Distance(vec, [0., 2.])
FROM tab
ORDER BY L2Distance(vec, [0., 2.]) ASC
LIMIT 3
SETTINGS enable_analyzer = 1

Query id: 086df46e-2e27-4342-a47c-6900762a7c8c

    ┌─explain─────────────────────────────────────────────────────────────────────────────────────────┐
 1. │ Expression (Project names)                                                                      │
 2. │   Limit (preliminary LIMIT (without OFFSET))                                                    │
 3. │     Sorting (Sorting for ORDER BY)                                                              │
 4. │       Expression ((Before ORDER BY + (Projection + Change column names to column identifiers))) │
 5. │         ReadFromMergeTree (default.tab)                                                         │
 6. │         Indexes:                                                                                │
 7. │           PrimaryKey                                                                            │
 8. │             Condition: true                                                                     │
 9. │             Parts: 1/1                                                                          │
10. │             Granules: 1/1                                                                       │
11. │           Skip                                                                                  │
12. │             Name: idx                                                                           │
13. │             Description: vector_similarity GRANULARITY 100000000                                │
14. │             Parts: 1/1                                                                          │
15. │             Granules: 1/1                                                                       │
    └─────────────────────────────────────────────────────────────────────────────────────────────────┘

15 rows in set. Elapsed: 0.007 sec.
@rschu1ze
rschu1ze force-pushed the vec-sim-idx-analyzer branch from fa63535 to 20bc3fe Compare November 22, 2024 10:48
@rschu1ze rschu1ze changed the title *wip* Initial Analyzer support for vector similarity search Initial Analyzer support for vector similarity search Nov 24, 2024
@rschu1ze rschu1ze changed the title Initial Analyzer support for vector similarity search Initial analyzer support for vector similarity search Nov 24, 2024
@rschu1ze
rschu1ze marked this pull request as ready for review November 24, 2024 21:50
@rschu1ze rschu1ze changed the title Initial analyzer support for vector similarity search Initial support for running vector similarity searches from analyzer Nov 25, 2024
@rschu1ze
rschu1ze force-pushed the vec-sim-idx-analyzer branch from 006422f to dfa29b1 Compare November 25, 2024 20:04
@rschu1ze
rschu1ze force-pushed the vec-sim-idx-analyzer branch from 7d3ec87 to b8a9c5b Compare November 25, 2024 21:01
@rschu1ze rschu1ze removed the do not test disable testing on pull request label Nov 25, 2024
@rschu1ze

Copy link
Copy Markdown
Member Author

@novikd This PR is ready and the test failure is unrelated. Like to take a look? Thanks.

((parameters->distance_function == "L2Distance" && metric_kind == unum::usearch::metric_kind_t::l2sq_k)
|| (parameters->distance_function == "cosineDistance" && metric_kind == unum::usearch::metric_kind_t::cos_k));

if (distance_function_in_query_and_distance_function_in_index_match && (parameters->limit <= max_limit_for_ann_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.

I don't understand this condition. It differs from the previous one.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'll add a code comment!

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.

It's clear that we must match distance functions, but why do you check the limit here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added a code comment which explains the reason.

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.

For me, it's unclear why we compare the limits here in the alwaysUnknownOrTrue method. I think the limit should be checked when we try to apply plan optimization.

@novikd novikd left a comment

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.

LGTM

((parameters->distance_function == "L2Distance" && metric_kind == unum::usearch::metric_kind_t::l2sq_k)
|| (parameters->distance_function == "cosineDistance" && metric_kind == unum::usearch::metric_kind_t::cos_k));

if (distance_function_in_query_and_distance_function_in_index_match && (parameters->limit <= max_limit_for_ann_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.

For me, it's unclear why we compare the limits here in the alwaysUnknownOrTrue method. I think the limit should be checked when we try to apply plan optimization.

return updated_layers;

/// Extract N
size_t n = limit_step->getLimitForSorting();

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 limit should be checked somewhere here. We should not apply the optimization if n > max_limit_for_ann_queries.

@rschu1ze

Copy link
Copy Markdown
Member Author

@novikd Tnx, I'll merge for now (some people are waiting for this PR) and will follow-up separately.

@rschu1ze
rschu1ze enabled auto-merge December 16, 2024 14:55
@rschu1ze

Copy link
Copy Markdown
Member Author

clang-build: #73265

ClickHouse Stateless tests (msan) [3/4]

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

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants