Skip to content

Use quantized vectors for fast KNN - #106629

Closed
shankar-iyer wants to merge 24 commits into
ClickHouse:masterfrom
shankar-iyer:fastknn-vector-similarity-index
Closed

shankar-iyer wants to merge 24 commits into
ClickHouse:masterfrom
shankar-iyer:fastknn-vector-similarity-index

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Jun 6, 2026 •

Copy link
Copy Markdown
Member

Add b1/b1_projected/TurboQuant/E8 quantization based flat indexes

Benchmark in progress at https://github.com/ClickHouse/ClickHouse/actions/workflows/vectorsearchstress.yml

Changelog category

  • New Feature

Changelog entry

  • TODO

shankar-iyer and others added 6 commits June 2, 2026 16:26
Add a `fastknn` method to the `vector_similarity` secondary index: a flat,
brute-force alternative to the HNSW (usearch) method. It stores binary-quantized
vectors as a contiguous matrix and answers queries by an exhaustive scan instead
of building an HNSW graph.

For `b1` (binary) quantization the scan computes Hamming distance over packed
bit-codes (`dim/8` bytes per vector) using usearch's `metric_punned_t` (AVX
popcount). Results are exact within the quantization and are intended to be
combined with rescoring against the full-precision column. No graph is built, so
there is no graph build cost and no graph storage overhead (which for binary
vectors would dwarf the vectors themselves).

The exhaustive scan is parallelized over a bounded, shared thread pool via a
`VectorSimilarityPoolExecutor` adapter feeding usearch's `exact_search_t`, because
the index-analysis phase only parallelizes across parts and a single large part
would otherwise scan single-threaded.

Usage: `vector_similarity('fastknn', 'cosineDistance', <dim>, 'b1', 0, 0)`

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tknn`

The `fastknn` flat scan was parallelized via usearch's `exact_search_t`, but for the
single-query case it was dominated (~96% of runtime, per profiling) by a single
shared `std::atomic` counter that `exact_search_t` increments once per vector,
contended across all scan threads - while the actual Hamming kernel was under 1%.
`exact_search_t` is tuned for many queries (substantial per-task work); with one
query the per-vector body is one tiny Hamming plus that atomic, so the atomic wins.

Replace it with a hand-rolled parallel scan: each thread computes distances into a
disjoint slice of the result buffer (no shared per-vector atomic), checks for query
cancellation once per 65536 vectors, then a `partial_sort` selects the top
candidates. The distance is still usearch's `metric_punned_t` (AVX popcount Hamming),
so results are unchanged; profiling now shows the Hamming kernel as the dominant cost.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add a `b1_projected` quantization to the flat `fastknn` method. It uses the same 1-bit
packed storage and AVX-popcount Hamming scan as `b1`, but multiplies each vector by a
fixed random projection before sign-binarizing (at index-build time, and the query at
search time). The projection makes the sign bits behave as random hyperplane hashes, so
Hamming becomes an (unbiased) estimate of the angle between vectors, whereas raw-sign
`b1` is a biased, data-dependent angle estimator.

On a synthetic 20k x 128 set, `b1_projected` reaches recall@10 = 100% at
`vector_search_index_fetch_multiplier = 10`, where raw-sign `b1` needs 50 - i.e. a 5x
smaller rescore shortlist for the same recall, at identical storage and scan cost. The
real benefit is data-dependent (largest for anisotropic embeddings) and should be
validated on real data.

The projection is a `d*d` Gaussian matrix regenerated deterministically from a fixed seed
(splitmix64 + Box-Muller), so it is identical at build and query time and is not stored.
The granule format is unchanged from `b1` (the codes are still packed sign bits). Usage:
`vector_similarity('fastknn', 'cosineDistance', <dim>, 'b1_projected', 0, 0)`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`b1_projected` previously applied a dense d*d Gaussian random projection to every
vector at index-build time. That is O(d*d) per vector (~590k multiply-adds at d=768)
and re-reads the ~2.3 MB matrix from memory for each vector, so building a
`b1_projected` index was ~d times slower than `b1` and almost entirely dominated by
this matrix-vector product (98% of build time in profiling).

Replace it with a fast structured random projection: three rounds of (deterministic
+-1 sign flip + in-place Walsh-Hadamard transform), zero-padding the dimension to the
next power of two. This is O(d log d) per vector with no stored matrix (just a few
small sign-flip diagonals, cache-resident), and the resulting sign bits still behave
as random-hyperplane hashes. It works for any dimension that is a multiple of 8 (384,
512, 768, 1024, 1536, 2048, 3072, ...).

Also parallelize the flat aggregator's build loop over the vector-index build thread
pool (each thread uses its own scratch buffer and writes disjoint code slots).

On 50k x 768, `b1_projected` build time drops from ~d times slower than `b1` to on par
with it, while recall is preserved (full recall@10 at
`vector_search_index_fetch_multiplier` = 10).

This changes the projection, so any existing `b1_projected` index must be rebuilt.

Also fix `-Wdouble-promotion` errors in the flat condition (float `index_fetch_multiplier`
mixed with double literals), matching the HNSW condition.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Basic coverage for the flat `fastknn` vector similarity index with both `b1` (raw-sign
binary) and `b1_projected` (random-projection + sign) quantization, reusing the 20
dbpedia vectors from `02354_vector_search_binary_quantization.sql`.

Asserts robust, rescoring-independent properties: a row is its own nearest neighbour
(self-retrieval), the query returns the requested number of rows, and the index is
actually used (via `EXPLAIN indexes = 1`).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@shankar-iyer
shankar-iyer marked this pull request as draft June 6, 2026 06:34
@shankar-iyer shankar-iyer changed the title Use quantized vectors for KNN Use quantized vectors for fast KNN Jun 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a74ca38]

Summary: ❌

job_name test_name status info comment
Fast test (arm_darwin) FAIL
01951_distributed_push_down_limit FAIL cidb
01952_optimize_distributed_group_by_sharding_key FAIL cidb
LLVM Coverage FAIL
Generate LLVM Coverage Diff Report FAIL cidb

AI Review

Summary

This PR adds an experimental fastknn method for vector_similarity indexes, with flat quantized scans for b1, b1_projected, turboquant, rabitq, and e8. The implementation has addressed many earlier storage-format and memory-safety concerns, but it still has one operational blocker in the new experimental gate, stale user-facing index documentation, and insufficient focused coverage for the new turboquant and rabitq estimators.

PR Metadata
  • 💡 Changelog category should be Experimental Feature, not New Feature, because fastknn is guarded by allow_experimental_fastknn_index.
  • 💡 Changelog entry is required and currently TODO. Suggested entry: Added experimental fastknn method for vector_similarity indexes with b1, b1_projected, turboquant, rabitq, and e8 quantization.
Missing context / blind spots
  • ⚠️ The PR description says the benchmark is still in progress. The performance contract for fastknn needs before/after benchmark results or a focused performance report before final approval.
Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:783] The new allow_experimental_fastknn_index gate runs while normalizing stored CREATE metadata, including ATTACH TABLE and startup metadata loading. A table created with allow_experimental_fastknn_index = 1 can become unloadable after restart or short ATTACH TABLE when the setting is back to its default 0.
    Suggested fix: restrict this check to fresh user creation, e.g. mode <= LoadingStrictnessLevel::CREATE, matching other experimental engines, and keep the ALTER ... ADD INDEX gate in MergeTreeData.

⚠️ Majors

  • [src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp:90] vector_similarity now accepts the user-facing fastknn method, but the structured Documentation registered in MergeTreeIndices.cpp still describes the index as HNSW-only and shows only hnsw syntax. Please update that documentation to include fastknn, its supported quantizations, and the important limits.
Tests
  • ⚠️ [tests/queries/0_stateless/02354_vector_search_fastknn_index.sql:81] turboquant coverage still relies on self-retrieval. Add a focused case with a known non-self ordering or distance, preferably with rescoring off, so the test fails if encodeTurboQuant or turboQuantDistanceFast is miswired.
  • ⚠️ [tests/queries/0_stateless/02354_vector_search_fastknn_index.sql:85] rabitq coverage also relies on self-retrieval. Add a focused case with a known non-self ordering or compare a small dataset against exact cosineDistance, so raBitQDistanceFast and the correction factor are actually exercised.
Final Verdict

Status: ❌ Block

Minimum required actions: fix the allow_experimental_fastknn_index gate so existing metadata can load, update the structured vector_similarity documentation, strengthen the turboquant and rabitq tests, replace the TODO changelog entry, and include performance evidence before taking the PR out of draft.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 6, 2026

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

`cppcoreguidelines-init-variables` flagged the uninitialized `file_version`, `dims`,
`bpv` and `count` locals read via `readIntBinary` in
`MergeTreeIndexGranuleVectorSimilarityFlat::deserializeBinary`. Initialize them to 0.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
/// The only indexing method currently supported by USearch
const std::set<String> methods = {"hnsw"};
/// Indexing methods: "hnsw" (usearch graph) and "fastknn" (flat brute-force scan over quantized codes)
const std::set<String> methods = {"hnsw", "fastknn"};

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.

Adding fastknn makes vector_similarity accept a new user-facing method, but the structured docs registered for this index type still describe it as HNSW-only and show only the hnsw syntax. That documentation is the source-level help for index types, so the new method is effectively undocumented and the syntax help is now stale.

Please update the vector_similarity Documentation entry to mention fastknn, b1, and b1_projected support and limits.

shankar-iyer and others added 2 commits June 7, 2026 16:15
Add a `turboquant` quantization to the flat `fastknn` method: TurboQuant-MSE at 2 bits
per coordinate. Like `b1_projected` it is data-oblivious - it applies the same fixed-seed
Walsh-Hadamard random projection (no sampling, no learned codebook, nothing stored beyond
the codes), then normalizes each projected vector to unit coordinate standard deviation and
applies the FIXED unit-Gaussian 4-level Lloyd-Max quantizer. That is 2 bits/coordinate
(`dim/4` bytes/vector vs `dim/8` for `b1`).

usearch has no 2-bit metric, so the scan is hand-rolled: it dequantizes the packed codes to
the fixed reconstruction levels and computes squared L2 (a shortlist distance), parallelized
over the build thread pool like the other flat paths, followed by rescoring. Requires
`cosineDistance` and a dimension that is a multiple of 4.

On a synthetic 20k x 128 set, `turboquant` reaches recall@10 = 100% at
`vector_search_index_fetch_multiplier` = 1, where `b1_projected` needs 10 and raw `b1` does
not reach it - the extra bit (coarse magnitude) at the cost of 2x the code-scan bytes.

Usage: `vector_similarity('fastknn', 'cosineDistance', <dim>, 'turboquant', 0, 0)`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extend 02354_vector_search_fastknn_index with a `turboquant` (2-bit) table alongside `b1`
and `b1_projected`: self-retrieval, row count, and index-usage assertions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
SELECT id FROM tab_proj ORDER BY cosineDistance(vec, (SELECT vec FROM tab_proj WHERE id = '<dbpedia:Honda>')) LIMIT 1;
SELECT id FROM tab_proj ORDER BY cosineDistance(vec, (SELECT vec FROM tab_proj WHERE id = '<dbpedia:Pizza>')) LIMIT 1;

SELECT '-- turboquant: nearest neighbour of a row is itself';

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.

The new turboquant path is only exercised with self-retrieval. That passes even if the 2-bit packing/dequantization distance is wired incorrectly, because the queried row's own code is still identical to itself.

Since turboquant adds a distinct projection, normalization, packing, and scoring path, please add a focused case where turboquant gives a known non-self ordering or distance so the test fails if encodeTurboQuant or turboQuantDistance is removed or miswired.

shankar-iyer and others added 5 commits June 8, 2026 00:04
The flat `turboquant` scan was a scalar per-coordinate loop (2-bit unpack + 4-level table lookup
+ squared difference), which profiling showed dominated query time (~98%) - it auto-vectorizes
poorly because of the per-coordinate variable shift and gather.

Add an AVX-512 kernel that processes 16 coordinates per iteration: the 16 codes of a chunk occupy
4 packed bytes and coordinate i sits at bit 2*i of that 32-bit word, so a single variable shift
(`srlv` by {0,2,...,30}) + mask yields the 16 indices, and `vpermps` gathers the 4 reconstruction
levels into 16 floats in one instruction; then `sub`/`fmadd` against the dequantized query. A scalar
tail handles `dim % 16`. It is runtime-dispatched via `isArchSupported(x86_64_v4)` (decided once per
query) with the scalar version as the fallback.

Correctness is unchanged (recall@10 identical to the scalar version), and the turboquant scan drops
from the dominant scalar loop to roughly the same ballpark as the `b1` Hamming scan.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Implement RaBitQ (Gao & Long, "RaBitQ", SIGMOD 2024) as a fourth
data-oblivious / no-codebook quantization for the flat `fastknn` method,
alongside `b1`, `b1_projected`, and `turboquant`.

Like `b1_projected`, each vector is randomly projected (the same fixed-seed
fast Walsh-Hadamard transform) and sign-binarized to 1 bit/coordinate. RaBitQ
additionally stores a per-vector correction factor `inv_factor = ||o||_2 / ||o||_1`
(over the unit rotated vector `o`), which turns the sign code into an UNBIASED
estimator of the cosine similarity rather than a plain SimHash angle estimate.

The query stays full precision - this is the asymmetric estimator:

    cos(o, q) ~= (sum_i s_i * q_i) * (1 / ||q||_2) * inv_factor

with `s_i = sign(o_i)` and `sum_i s_i * q_i = 2 * sum_{s_i = +1} q_i - sum_i q_i`.
The `1/sqrt(D)` and the global projection scale cancel in the ratio, and
`factor = sum_i |o_i| >= 1` so there is no division blow-up; self-similarity is
exactly 1. Because the sign code equals `b1_projected` bit-for-bit, the per-vector
storage is just `dim/8 + sizeof(float)` bytes.

The data half of the estimator (`sum_{s_i = +1} q_i`) is a mask-controlled sum:
the sign code is exactly an AVX-512 `__mmask16`, so an AVX-512 kernel accumulates
the selected query coordinates with `_mm512_mask_add_ps`, about as cheap as the
`b1` popcount. Runtime-dispatched via `isArchSupported(TargetArch::x86_64_v4)`,
with a scalar fallback.

`rabitq` is `fastknn`-only, requires `cosineDistance`, and a dimension that is a
multiple of 8. Extends the stateless test `02354_vector_search_fastknn_index` with
a `rabitq` table (self-retrieval, row count, index-usage). On the 20-vector dbpedia
sample, recall@5 (excluding self, vs exact cosine) matches the best of the existing
methods; a real recall margin over `b1_projected` still needs validation on a
larger dataset (LAION/SIFT).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… float dot product

The first `rabitq` implementation computed the asymmetric estimator's data term
`sum_i s_i * q_i` as a full-precision float masked sum over the query (one
`_mm512_mask_add_ps` per 16 coordinates). Although `rabitq` stores 1-bit codes like
`b1`, this made its scan cost like the multi-bit `turboquant` float scan rather than
like the cheap `b1` Hamming popcount - on a 100k x 1536 single-threaded scan it was
~27 ms (turboquant-class), versus ~4 ms for `b1`/`b1_projected`.

Switch to the bit-sliced scan that RaBitQ/BBQ actually use: the (rotated) query is
uniformly quantized to `RABITQ_QUERY_BITS` (= 4) bits and stored as one bit-plane per
bit. The data term then reduces to AND+popcount passes over the 1-bit data code:

    sum_{s_i=+1} q_i ~= delta * sum_j 2^j * popcount(code AND query_plane_j) + q_min * popcount(code)

`q_total = sum_i q_i` and `inv_qnorm = 1/||q||_2` still use the exact query, so only
the data-code inner product is approximate. On Ice Lake (VPOPCNTDQ available) the kernel
counts 8x 64-bit lanes per `_mm512_popcnt_epi64`, with a scalar `std::popcount` fallback
elsewhere; dispatched once per query via `isArchSupported(TargetArch::x86_64_icelake)`.

This puts the 1-bit `rabitq` scan back in the popcount regime: ~5 ms on the same 100k x
1536 benchmark (~1 ms over `b1`, ~5x faster than the previous kernel and than `turboquant`),
with recall unchanged (recall@5 = 0.80 on the 20-vector dbpedia sample, same as before).
The data code format is unchanged (still `dim/8` sign bits + a 4-byte factor); only the
query encoding and scan kernel change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nn` `turboquant` quantization

The previous `turboquant` was only "TurboQuant-flavored": a 2-bit MSE-optimal scalar
quantizer (correct levels) but with a SYMMETRIC estimator (both query and data quantized,
squared-L2 between dequantized levels). That estimator is biased for inner products / cosine,
which is not the published algorithm.

Replace it with the exact TurboQuant inner-product scheme (Zandieh et al., "TurboQuant",
arXiv:2504.19874): a two-stage `(b-1)`-bit MSE quantizer + 1-bit QJL (Quantized
Johnson-Lindenstrauss) transform on the residual, giving an UNBIASED, asymmetric estimator.
For the faithful 2-bit case that is 1-bit MSE + 1-bit QJL + a per-vector residual norm.

Encode (data `x`): rotate by `P1`, normalize the first `d` coordinates to unit; MSE signs
`s = sign(a)` with reconstruction `c0 * s`, `c0 = sqrt(2/pi)/sqrt(d)`; residual `r = a - c0*s`,
`gamma = ||r||`; QJL signs `z = sign(P2*r)` with a second independent projection `P2`. Layout:
`d/8` MSE sign bits + `d/8` QJL sign bits + a 4-byte `gamma` (`d/4 + sizeof(float)` total).

Estimator (asymmetric, query full precision, bit-sliced like `rabitq`), with `q1 = unit(P1*y)`:
  cos(y, x) ~= c0 * <q1, s> + k * gamma * <P2*q1, z>,   k = sqrt(pi/2) / (d * padded).
The `(d * padded)` in `k` (vs the paper's `sqrt(pi/2)/d`) accounts for our unnormalized
3-round Walsh-Hadamard projection, whose per-coordinate output variance is `padded^2 * ||v||^2`
rather than the unit-variance Gaussian the paper assumes.

Each `<.,.>` is the same AND+popcount sign dot as `rabitq` (reused via the shared
`raBitQNumerator*` kernels), so the scan stays in the popcount regime. On a 100k x 1536
single-threaded scan this is ~6 ms (two sign dots), versus ~27 ms for the old float-L2 scan -
about 4.5x faster - while becoming the faithful algorithm. Recall@5 on the 20-vector dbpedia
sample is unchanged (0.80). `turboquant` now requires the dimension to be a multiple of 8.

The on-disk code format changed (two 1-bit planes + gamma instead of 2-bit packed), so existing
`turboquant` `fastknn` indexes must be rebuilt; the feature is experimental/unreleased.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
SELECT id FROM tab_tq ORDER BY cosineDistance(vec, (SELECT vec FROM tab_tq WHERE id = '<dbpedia:Honda>')) LIMIT 1;
SELECT id FROM tab_tq ORDER BY cosineDistance(vec, (SELECT vec FROM tab_tq WHERE id = '<dbpedia:Pizza>')) LIMIT 1;

SELECT '-- rabitq: nearest neighbour of a row is itself';

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.

The new rabitq coverage only checks self-retrieval. That still passes if the rabitq correction factor, bit-sliced query, or raBitQDistanceFast scoring path is bypassed, because the queried row's own code is identical to itself.

Please add a focused case where rabitq has a known non-self ordering or distance, or compare a small dataset against exact cosineDistance, so the test fails if the rabitq estimator is not actually wired into search.

Address `-warnings-as-errors` clang-tidy findings in the `rabitq`/`turboquant`
quantization code:
- `bugprone-incorrect-roundings`: replace `static_cast<int>(x + 0.5f)` with
  `std::lround` in the RaBitQ query quantizer.
- `cppcoreguidelines-init-variables`: initialize `cw`, `pw`, `inv_factor`,
  `gamma`, and `dist` (the float scratch values overwritten by `memcpy` or
  per-branch assignment use `NAN` as a use-before-set sentinel).
- `modernize-use-std-numbers`: replace the literal pi with `std::numbers::pi`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ity index

Add a new `fastknn` quantization method, `e8`, that does product quantization
against the fixed E8 lattice instead of a trained (k-means) codebook. Because the
existing random rotation already makes each 8-dimensional sub-vector approximately
isotropic, the optimal quantizer is a fixed lattice known in closed form, so no
data-dependent training or codebook persistence is needed: the codebook is
regenerated deterministically from (dimensions, bits), exactly like the random
projection seed.

Each 8-dim block is snapped to its nearest E8 point via an O(d) decoder (round to
D8, fix parity, compare against the half-integer coset) and a hash lookup into a
deterministic truncated codebook. The scan estimates the asymmetric inner product
`<q_hat, x_hat>` through an ADC lookup table plus a stored per-vector norm, which
yields both `cosineDistance` and `L2Distance` (the other fastknn methods are
cosine-only).

The `bits` argument (fifth index parameter, 1..16) sets the codebook size
(`2^bits` points per block) and hence storage: 1 byte/block for bits <= 8 (e.g.
`dim/8 + 4` bytes/vector, same footprint as `rabitq`) and 2 bytes/block above. To
keep encoding fast at high bit counts, query points are scaled so a typical
sub-vector maps inside the fully-contained region of the truncated lattice and
clamped there, so the decode is guaranteed to hit a stored point and the
brute-force fallback over the codebook is avoided.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address `-warnings-as-errors` clang-tidy findings in the `e8` quantization code:
- `google-runtime-int`: replace `long long` with `Int64` in `nearestD8`,
  `e8Collect`, and `buildE8Codebook`.
- `modernize-loop-convert`: use a range-based for loop for the query clamp in
  `encodeE8`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The `e8` index build was pathologically slow at higher bit counts: building it
over 100k 1536-d vectors took ~30s at `bits=16` versus ~0.7s for `turboquant`
(and ~0.6s for `e8` at `bits=8`).

Profiling (built-in sampling profiler; `perf` is unavailable on this kernel) traced
essentially all of the time to the per-sub-vector `std::unordered_map::find` that
maps a decoded E8 lattice point to its codebook index. Disabling the brute-force
fallback changed nothing, but skipping the lookup entirely cut the build from ~30s
to ~1s. At `bits=16` the map holds 65536 node-allocated entries (~2.6 MB) and is
queried `M * num_vectors` times; under the parallel build every thread chases
scattered nodes and saturates memory, so each lookup costs ~1.5 us.

Replace the node-based `std::unordered_map` with ClickHouse's flat, open-addressing
`HashMap`. The contiguous layout removes the per-lookup pointer chase, bringing the
`bits=16` build to ~0.72s — on par with `turboquant` — with no change to the codes
produced (same keys and values, so recall is unchanged). `bits=8` stays fast (~0.6s)
and self-retrieval still returns the query vector as the top-1 neighbour.
shankar-iyer and others added 2 commits June 14, 2026 01:09
The e8 ADC scan was ~2x slower than rabitq/turboquant: per vector it sums M = dim/8
gathers into a float LUT, which doesn't vectorize (measured ~25ms vs ~14ms over 1M
1536-d vectors, scan-only; lowering `bits` to shrink the LUT did not help, confirming
the gather loop - not the cache - is the bottleneck).

Add a PQ fast-scan path (FAISS/ScaNN style) used when the codebook has <= 16 points
(`bits` <= 4): build an int8-quantized per-subquantizer LUT and scan 64 vectors at a
time with `_mm512_shuffle_epi8` (64 16-entry lookups per instruction), accumulating in
int16. Codes are transposed into sub-quantizer-major tiles in a scratch buffer, so
there is no on-disk format change; the existing float ADC remains the path for larger
`bits` and the non-Ice-Lake fallback.

The kernel is gated by `USE_MULTITARGET_CODE` + `isArchSupported(x86_64_icelake)`, like
the rabitq/turboquant kernels, so it only activates in a multitarget build.

Validated the vpshufb math against a scalar reference (0 mismatches, M in {8,192,200},
tail exercised) and compile-checked both the scalar and multitarget-on builds. Notably,
this caught and fixed a latent crash: `std::vector<__m512i>` drops the type's 64-byte
over-alignment, so storing a `__m512i` into it uses an aligned store on unaligned memory
and segfaults; the LUT is now broadcast inline instead.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address the AI review on the PR:

- Gate the experimental 'fastknn' method behind a new setting
  `allow_experimental_fastknn_index`, enforced at CREATE (InterpreterCreateQuery)
  and ALTER (MergeTreeData::checkAlterIsPossible), mirroring `enable_full_text_index`.
- Fix the 'e8' distance: clamp the ADC inner product to [-1, 1] in both the scalar
  and AVX-512 scans so cosineDistance stays in [0, 2] and L2Distance stays >= 0
  (the optimized plan sqrt's the L2 value; a negative value produced NaN). Also
  bounds-guard the per-vector code index against a corrupt codes blob.
- Reject finite Float64 inputs that are not representable as finite Float32 for the
  projection-based quantizations (data and reference vectors), so they cannot feed
  non-finite values into the projection / e8 integer casts.
- Persist `e8_bits` and validate the flat layout on load (dimensions, bytes per
  vector, count overflow, e8 layout, and that the persisted bits match the index);
  bump the flat FILE_FORMAT_VERSION.
- Enforce the UInt32 row-offset limit in the flat aggregator (mirrors hnsw).
- Reject 'b1_projected'/'turboquant'/'rabitq'/'e8' for the 'hnsw' method (the
  projection / codes are only implemented by the flat path).
- Cap the e8 (dimension, bits) combination so the per-query ADC table is bounded,
  and bound the process-wide E8 codebook cache.
- Replace the full per-vector `scored` array + partial_sort with bounded per-worker
  top-k heaps, so query scratch is O(num_threads * limit) instead of O(num_vectors).
- Check cancellation periodically inside the flat build loops.

Tests: add 02354_vector_search_fastknn_e8_and_validation (e8 cosineDistance and
L2Distance, the experimental gate, and validation/rejection boundaries); enable the
new setting in 02354_vector_search_fastknn_index.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.70% -0.10%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 760/925 (82.16%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 11 line(s) · Uncovered code

Full report · Diff report

shankar-iyer and others added 4 commits June 15, 2026 03:12
Follow-up to the earlier review fix, which only persisted/validated `e8_bits`
(the `e8`-vs-`e8` case). The flat granule did not record which quantization it was
built with, so a part built as one method could be scanned as another with the same
`bytes_per_vector` (e.g. on ATTACH of a part from a differently-quantized index):
`b1` scanned as `turboquant` reads the QJL plane and `gamma` past each `dim/8` code,
`e8` decoded as `rabitq`/`turboquant` returns garbage, and `b1` vs `b1_projected`
(identical layout) cannot be told apart by size alone.

Persist a `FlatQuantization` codec id with each granule (FILE_FORMAT_VERSION -> 3) and:
- on load, validate the id is known, that `e8_bits` is set iff the codec is `e8`, and
  that `bytes_per_vector` matches the layout implied by the codec (single source of
  truth `expectedFlatBytesPerVector`, also used by the aggregator);
- before scanning, validate the persisted codec matches the index's quantization
  (and, for `e8`, the bits), so a mismatched part fails instead of being misdecoded.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The fast-scan int8 LUT was scaled to keep the per-vector sum within int16
(`clamp_max = min(127, 32767 / M)`), but rounding could push a max entry over the
bound (e.g. M=512 rounds to 64, and 512*64 = 32768 > INT16_MAX), and for very large M
even an entry of 1 overflows. `_mm512_add_epi16` then wrapped, giving wrong distances
on Ice Lake only.

Accumulate the per-vector sum in int32 (four 16-lane registers for the block of 64)
instead of int16, which cannot overflow within the validator's `M * 2^bits` cap, and
scale the LUT to the full int8 range for better precision. Validated the SIMD result
against a scalar reference for M up to 1000 (0 mismatches).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The per-coordinate Float32 check on the input is not sufficient: the Walsh-Hadamard
rounds are unnormalized, so a finite (but large) Float32 input can still overflow to
Inf/NaN during the projection. The projection-based encoders/scans then feed `work`
into norms, `std::lround`, and integer casts (`e8`), which is undefined behaviour or
a garbage code rather than a deterministic error.

Validate that the projected coordinates are finite at the end of `applyRandomProjection`
(covers b1_projected/turboquant/rabitq/e8 on both the build and search paths). It is a
single linear pass over the used coordinates - cheap relative to the O(padded log padded)
transform - and only fires for extreme inputs.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Self-retrieval with rescoring on passes even if a quantization's scoring path is
bypassed, because the full-precision re-rank fixes the result. Add self-retrieval
queries with `vector_search_with_rescoring = 0` for b1, b1_projected, turboquant and
rabitq, so the result comes purely from the quantized estimator and the test fails if
a scoring path (e.g. raBitQDistanceFast / turboQuantDistanceFast) is not actually wired
into search. Self is the estimator extremum, so the expected row is deterministic and
independent of the scalar-vs-AVX kernel.
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "The text index feature is disabled. Enable the setting 'enable_full_text_index' to use it");

/// The 'fastknn' method of the vector similarity index is experimental; gate it behind a setting.
if (index_desc.type == "vector_similarity" && !settings[Setting::allow_experimental_fastknn_index])

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.

This gate runs while normalizing any stored CREATE metadata, including ATTACH TABLE and server startup (FORCE_ATTACH). A table created while allow_experimental_fastknn_index = 1 stores only the vector_similarity('fastknn', ...) definition; after restart or a short ATTACH TABLE with the setting back at its default 0, this check rejects the existing table metadata and the table cannot load.

Please restrict the setting check to fresh user creation, e.g. mode <= LoadingStrictnessLevel::CREATE, matching other experimental engines, and keep the ALTER ... ADD INDEX gate in MergeTreeData for new metadata changes.

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

Labels

pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants