Repository navigation
Quantization CODECs for vector columns and 2-stage retrieval - #108565
Conversation
Introduce a `Quantize(method, dimensions[, bits])` column codec for dense vector columns (`Array(Float32)` and friends). At the byte level it is a no-op (the full-precision data is stored verbatim, like `NONE`, so `isNone` is true); its presence makes `SerializationQuantizedVector` write a compact, data-independent quantized companion stream alongside the floats, exposed as the readable subcolumn `<column>.quantized` of type `FixedString(N)`. This replaces declaring an explicit `MATERIALIZED` codes column: a single column now carries two streams (full precision + quantized codes). A new query-plan optimization `optimizeVectorSearchWithQuantizedCodes` rewrites `ORDER BY L2Distance(vec, ref) LIMIT k` into a two-stage shortlist-then-rescore: it ranks cheaply over the `vec.quantized` codes (reading only the small subcolumn), then rescores the shortlist against the full-precision `vec`, which the existing lazy-materialization pass defers to the shortlisted rows only. Details: - `CompressionCodecQuantize` (method byte `0x9d`) carries the quantization parameters and round-trips through `SHOW CREATE`. - `SerializationQuantizedVector` adds a `QuantizedCodes` substream; the codes are written only into on-disk parts, never into Native transport streams (which reconstruct a plain `Array(Float32)` from the type name). - The codec is attached to the column's own type instance in `ColumnsDescription`; `IMergeTreeReader::getSerializationInPart` honors the custom serialization that the part's plain columns list cannot represent. - `quantizeEncode` and `quantizeDistance` scalar functions expose the kernels. Tests `04365_quantize_codec` and `04366_quantize_codec_planner`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Mark `CompressionCodecQuantize` as experimental (`isExperimental() == true`) so that using `CODEC(Quantize(...))` requires the existing `allow_experimental_codecs` setting, consistent with how other not-yet-stable codecs are gated. Reusing the established setting avoids introducing a new one. The two stateless tests now set `allow_experimental_codecs = 1`, and `04365_quantize_codec` additionally asserts that the codec is rejected with `BAD_ARGUMENTS` when the setting is off. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add an `int8` method to the quantized vector search codec. It applies the existing 3-round structured random rotation, normalizes each vector to unit L2 and scales by `sqrt(dimensions)` so coordinates are approximately `N(0, 1)`, then quantizes each coordinate with a 256-level Gaussian Lloyd-Max scalar quantizer. The per-vector layout is one `Int8` code per coordinate followed by the 4-byte original L2 norm. The distance estimator is asymmetric (the query is kept full precision) and mirrors the `e8` reconstruction. The Lloyd-Max tables and the scalar `quantize`/`dequantize` are extracted into a new shared header `Common/LloydMaxQuantizer.h` and reused by both the existing `quantizeBFloat16ToInt8` function and the new method, avoiding duplication. `quantizeBFloat16ToInt8` behavior is unchanged. Drop `b1` and `b1_projected`: `rabitq` produces a bit-for-bit identical sign code plus an unbiased cosine estimator, so it strictly dominates them. Their dispatch, the `signPack`/`hammingDistance` helpers, and the `b1_code` query field are removed. Remaining methods: `turboquant`, `rabitq`, `e8`, `int8`. Add `tests/queries/0_stateless/04409_quantize_codec_int8.sql`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…r-of-two dims
Extract the (randomized) Hadamard transform kernels from
`Functions/randomHadamardTransform.cpp` into a new shared header
`Common/HadamardTransform.h` (the scalar fast Walsh-Hadamard transform, the
exact Kronecker transform `H_{2^k} (x) H_m` via the Paley construction, and the
NEON variants). `randomHadamardTransform` now consumes the header unchanged.
Route the structured random projection behind the quantized vector search
codecs (`Common/VectorQuantization.cpp`) through the same kernel. It keeps the
existing 3-round sign-flip rotation, but the Hadamard step now uses the exact
Kronecker transform for dimensions of the form `2^k * m` with m in {12, 20}
(e.g. 384, 768, 1536, 3072, 2560) instead of zero-padding to the next power of
two. This removes the padding work and the geometry distortion for those common
embedding dimensions. The random sign generation is unchanged, so codes for
power-of-two dimensions are bit-identical to before; only the listed
non-power-of-two dimensions change.
Add `tests/queries/0_stateless/04410_quantize_codec_kronecker.sql` exercising a
Kronecker dimension (96 = 8 * 12).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add an Ice Lake (`VPOPCNTDQ`) kernel `raBitQNumeratorICELAKE` for the rabitq bit-sliced dot product: each 512-bit chunk of the 1-bit sign code is AND-ed with the query bit-planes and popcounted with `_mm512_popcnt_epi64`, counting eight 64-bit lanes per instruction instead of one 64-bit word at a time. Integer popcount sums are order-independent and the counts feed the same `raBitQNumeratorFromCounts`, so the result is identical to the scalar kernel. Dispatch is decided once per query via `isArchSupported(TargetArch::x86_64_icelake)` (stored on the prepared `Query`) and threaded into the per-code distance, so the hot scan has no per-vector CPU detection. `turboquant`, whose estimator is two rabitq sign-code dot products, benefits as well. Builds without AVX-512 keep the scalar path (the kernel is guarded by `USE_MULTITARGET_CODE`). Add `tests/queries/0_stateless/04411_quantize_codec_rabitq_simd.sql` at dimension 1024 (132-byte codes), which runs the 64-byte SIMD main loop and checks the search stays exact under a full-coverage shortlist, keeps high recall, and self-matches. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add `VectorQuantization::validateParams`, called from the codec's argument parsing, so bad `Quantize(...)` parameters are rejected at CREATE TABLE with a clear `ILLEGAL_CODEC_PARAMETER` instead of producing wrong codes or exhausting memory later: - `turboquant`, `rabitq` and `e8` pack codes 8 coordinates to the byte, so they now require `dimensions` to be a multiple of 8 (previously a non-multiple silently dropped the tail coordinates). `int8` still accepts any dimension. - `e8` now requires `bits` in [1, 16]; it builds a 2^bits codebook, so an unbounded value would otherwise exhaust memory at first insert/query. This replaces the previous ad-hoc checks (supported method, dimensions > 0, non-empty code) with the single centralized helper. Also drop the stale `b1`/`b1_projected` mention from the `VectorQuantization.h` method list. Add `tests/queries/0_stateless/04412_quantize_codec_invalid_params.sql` covering the rejected configurations and the accepted non-multiple-of-8 `int8` case. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Move the six `Quantize` codec tests under the `02354_vector_search_quantize_codec` prefix so they group with the other `02354_vector_search_*` tests: 04365_quantize_codec -> 02354_vector_search_quantize_codec 04366_quantize_codec_planner -> 02354_vector_search_quantize_codec_planner 04409_quantize_codec_int8 -> 02354_vector_search_quantize_codec_int8 04410_quantize_codec_kronecker -> 02354_vector_search_quantize_codec_kronecker 04411_quantize_codec_rabitq_simd -> 02354_vector_search_quantize_codec_rabitq_simd 04412_quantize_codec_invalid_params-> 02354_vector_search_quantize_codec_invalid_params Pure rename; the test contents are unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test harness randomizes `query_plan_max_limit_for_lazy_materialization` and `query_plan_optimize_lazy_materialization`. The shortlist size of the two-stage vector search is `k * vector_search_index_fetch_multiplier` clamped to `query_plan_max_limit_for_lazy_materialization`, so a randomized small value shrinks the shortlist and turns the full-coverage "exact" checks (and the high-recall check) approximate; a randomized-off `query_plan_optimize_lazy_materialization` also removes the `LazilyReadFromMergeTree` step the planner test asserts. Pin both settings in the affected tests so the results are deterministic. Verified stable across repeated randomized `clickhouse-test` runs.
|
Workflow [PR], commit [4e43b97] Summary: ✅
AI ReviewSummaryThis PR adds the experimental PR Metadata
Findings❌ Blockers
💡 Nits
Final Verdict
|
…le check The `std::vector<float>` buffers in `quantizeEncode`/`quantizeDistance` (the per-row encode buffer, the query buffer, and the `readVectorRow` out-parameter) are flagged by the `src/Functions` std-container style check. Switch them to `VectorWithMemoryTracking<float>` (a `std::vector` with the memory-tracking allocator), so these per-query allocations count against the query memory limit. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`cppcoreguidelines-init-variables` (a warnings-as-error tidy check) flagged the uninitialized `size_t index` in `LloydMax::quantize`. It is always assigned before use, but initialize it to 0 to satisfy the check. The initializer was present in the original `quantizeBFloat16ToInt8` code and got dropped when the quantizer was extracted into the shared header. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`readability-inconsistent-declaration-parameter-name` (a warnings-as-error tidy check) flagged `SerializationQuantizedVector::encodeCodes`, whose declaration named the third parameter `limit` while the definition uses `count` (the caller resolves limit==0/overflow into a concrete row count before calling). Rename the declaration to `count` to match. Also fix the same inconsistency on `VectorQuantization::distance`, whose declaration named the prepared query `query` while the definition (and its body) use `q`. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… functions
The data-independent quantizers (rabitq/turboquant/e8/int8) do not adapt to the
data and give poor recall on real datasets like SIFT (turboquant 2-bit reached
only ~0.27 recall@10 at fetch=10; e8 ~random). Product Quantization with a
trained codebook is the standard answer.
Add `Common/ProductQuantization.{h,cpp}`: per-subspace Lloyd k-means
(`trainCodebook`), `encode`, and an asymmetric-distance-computation
`Query`/`prepareQuery`/`distance` (per-subspace query-to-centroid LUT, summed
per code), modelled on the e8 ADC kernel in `VectorQuantization.cpp`.
Add SQL functions `pqTrain(samples, dimensions, m, nbits)` (k-means over a
sample set), `pqEncode(vec, codebook, …)`, and `pqDistance(code, codebook,
query, …)` for ad-hoc PQ and to prove recall before wiring PQ into the codec.
Proof on SIFT1M (PQ16x8, 16 bytes/vector): two-stage recall@10 = 0.98 at
fetch_multiplier=10 (vs 0.27 for turboquant at 36 bytes), 1.00 at fetch=50.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Wire trained Product Quantization into the `Quantize` codec as a new method:
`CODEC(Quantize('pq', dimensions, nbits, m))`.
- `ISerialization`: new `Substream::PQCodebook` (named subcolumn `<col>.pq_codebook`).
- `CompressionCodecQuantize`: `QuantizeCodecParams.m`; the parser accepts a 4th
argument; `pq` is validated via `ProductQuantization::validateParams`.
- `SerializationQuantizedVector`: for `pq`, a `SerializeStatePQ` trains a codebook
from the part's first block (k-means, capped at 100k vectors), encodes the codes
granule-aligned with it (so the existing two-stage planner + lazy-materialization
read path is reused), and writes the codebook once per part at the Suffix to the
`pq_codebook` substream. The data-independent methods keep their stateless path.
Native-format guard retained (codes/codebook never go to transport). Merges
retrain naturally (fresh writer/state on the merged stream).
Verified on SIFT1M (PQ16x8): stored codes + stored codebook give two-stage
recall@10 = 1.0; the existing rabitq/int8 tests still pass. The per-row read of
`<col>.pq_codebook` (broadcast of the one-per-part value) and the planner wiring
follow in the next change.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Complete the read path for the trained Product Quantization (`pq`) method of the `Quantize` codec so that `ORDER BY L2Distance(vec, ref) LIMIT k` over a `pq`-quantized column auto-rewrites into the two-stage shortlist + rescore. - `SerializationQuantizedVector`: add `SerializationPQCodebook`, a read serialization for the per-part `pq_codebook` subcolumn. The codebook is one value per part; a scan asks for one value per row. It reads exactly one value and returns a `ColumnConst` broadcast to `limit` rows - O(1) memory, and the distance function sees the codebook as a per-block constant. Created via the serialization pool so it carries a stable hash. - `productQuantization`: `pqDistance` accepts the codebook as a per-block `ColumnConst` (the planner path) in addition to a query-level constant, drops the codebook from `getArgumentsThatAreAlwaysConstant`, and guards the zero-row dry run. - `useVectorSearchWithQuantizedCodes`: for the `pq` method, also read and propagate the `<col>.pq_codebook` subcolumn up the filter chain and build `pqDistance(code, codebook, ref, dims, m, nbits, is_l2)` instead of `quantizeDistance`. Verified end-to-end on SIFT 50k (PQ16x8): the planner produces the shortlist with `pqDistance`, and recall@10 via the rewrite is 0.876 / 0.969 / 0.998 / 1.000 at fetch_multiplier 2 / 4 / 10 / 50 (vs ~0.27 for data-independent turboquant 2-bit). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Cover the `pq` (Product Quantization) method of the `Quantize` column codec: - `02354_vector_search_quantize_codec_pq`: codec round-trips through SHOW CREATE; the codes (`vec.quantized`, `FixedString(m)`) and the per-part codebook (`vec.pq_codebook`, `FixedString(2^nbits * dimensions * 4)`) subcolumns are readable; the full-precision vectors round-trip; the planner rewrites `ORDER BY L2Distance LIMIT` into a `pqDistance` shortlist + lazy rescore; and at full shortlist coverage the path reproduces the exact brute-force top-k (unfiltered, filtered, and nearest-is-self). - `02354_vector_search_quantize_codec_pq_merge`: two parts train two codebooks; `OPTIMIZE FINAL` retrains a single codebook on the merged data, and the two-stage search stays exact against it. - `02354_vector_search_quantize_codec_pq_invalid_params`: DDL-time validation (the 4-argument form is required for `pq` and rejected for other methods; `dimensions` must be a multiple of `m`; `nbits` in [1, 16]). The lazy-materialization settings the harness randomizes are pinned so the full-coverage exact checks stay exact. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`pqEncode` required its codebook argument to be a query constant, so the documented form `pqEncode(vec, pqTrain(...), ...)` failed with `ILLEGAL_COLUMN` (the `pqTrain` result is not constant-folded) - the same issue already fixed for `pqDistance`. Drop the codebook from `getArgumentsThatAreAlwaysConstant` (the shared `getCodebook` already accepts a const or a uniform full column) and guard the zero-row dry run. The `pqEncode`/`pqDistance` documentation examples now run. Add `02354_vector_search_pq_functions` covering `pqTrain`/`pqEncode`/`pqDistance` directly: codebook and code lengths (8-bit and >8-bit codes), zero self-distance for an exactly-reconstructed vector, distance ranking across two clusters, a column round-trip where each row's own code is its nearest, and `pqTrain` parameter validation. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reading the `pq` codebook subcolumn failed on parts with more than one granule with "Incorrect size of nested column in constructor of ColumnConst: 0, must be 1". The codebook is stored as a single value per part (written once at the suffix; every granule's mark points at it), but the broadcast read consumed the one-value stream on every granule, so after the first granule the stream was exhausted and the read produced an empty column. Read the codebook exactly once into the deserialize state and broadcast it as a `ColumnConst` to every granule (the per-part-dictionary pattern of `SerializationLowCardinality`). The state is created in `deserializeBinaryBulkStatePrefix` and re-established defensively on the first `deserializeBinaryBulkWithMultipleStreams` call (the reader keeps it across granules), so a state populated by an earlier pass cannot be misinterpreted. Add `02354_vector_search_quantize_codec_pq_multigranule` (30000 rows, a small `max_block_size` forcing many granule reads of the one-value codebook stream) - the prior tests used single-granule parts and missed this. Also two style-check fixes in the M1 files: drop the unused `ErrorCodes::INCORRECT_DATA` in `ProductQuantization.cpp`, and avoid a raw `std::vector` local in `productQuantization.cpp` by copying the trained codebook straight from the (callee-owned) return value. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`02354_vector_search_quantize_codec_pq_multigranule` failed in the Fast test with `MEMORY_LIMIT_EXCEEDED` (4.69 GiB > 4.66 GiB): the full-coverage check used `vector_search_index_fetch_multiplier = 30000` over 30000 rows, so the shortlist covered the whole part and carried the 65536-byte per-part codebook `ColumnConst` into the rescore sort, materializing ~2 GiB. Keep the test genuinely multi-granule but small: `index_granularity = 1024` with 10000 rows (~10 granules) still exercises the per-granule codebook read, and the full-coverage shortlist (`fetch_multiplier = 1000` * `LIMIT 10` = 10000 rows) now peaks well under 1 GiB (verified passing under a 2 GiB `max_memory_usage` cap). All assertions and the reference are unchanged in meaning. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
@groeneai do we have tests here for negative cases, like if we are trying to write vectors of wrong dimensions or other similar error scenarios |
|
@egor-click Negative-case coverage today is at DDL/parameter-validation and ALTER level; the write path (wrong-dimension inserts) is enforced in code but has no dedicated test. Covered by dedicated tests:
Not covered - the exact case you named (inserting a vector whose length != declared If it is worth closing that gap, I can add a small stateless test for the wrong-length insert plus the non-Array and unsupported-type cases. |
yes please, add this and bunch of other negative cases that would make sense having also i am thinking about what if someone tries to use full precision vector that is actually less precise than quantized, do we have test covering this case? |
|
On the precision question: the quantized code is always derived from the stored vector, so it cannot be more precise than the full-precision column - that ordering cannot arise for the same vector. What matters for correctness is that the codes path only builds a shortlist and then rescores those candidates by the exact distance over the stored full-precision vectors, so the final top-k is exact. Each method test ( The closest testable form of what you describe is not exercised: every two-stage test stores Negative cases I will add (write path, common to all methods, currently untested):
I will open a stateless-test PR and link it here. |
|
Opened #111084 with the negative-case tests. It covers:
|
Cover the Quantized(...) codec error surface (feature added in ClickHouse#108565), requested by egor-click: - 02354_vector_search_quantize_codec_negative.sql: DDL-time ILLEGAL_COLUMN for non-Array and non-float-element columns, DDL-time BAD_ARGUMENTS for chaining with a compression codec, and write-time SIZES_OF_ARRAYS_DONT_MATCH for a vector length that differs from the declared dimensions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Cover the Quantized(...) codec error surface (feature added in ClickHouse#108565), requested by egor-click: - 02354_vector_search_quantize_codec_negative.sql: DDL-time ILLEGAL_COLUMN for non-Array and non-float-element columns, DDL-time BAD_ARGUMENTS for chaining with a compression codec, and write-time SIZES_OF_ARRAYS_DONT_MATCH for a vector length that differs from the declared dimensions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
`02354_vector_search_quantize_codec_pq_multigranule` failed in the Fast test with `MEMORY_LIMIT_EXCEEDED` (4.69 GiB > 4.66 GiB): the full-coverage check used `vector_search_index_fetch_multiplier = 30000` over 30000 rows, so the shortlist covered the whole part and carried the 65536-byte per-part codebook `ColumnConst` into the rescore sort, materializing ~2 GiB. Keep the test genuinely multi-granule but small: `index_granularity = 1024` with 10000 rows (~10 granules) still exercises the per-granule codebook read, and the full-coverage shortlist (`fetch_multiplier = 1000` * `LIMIT 10` = 10000 rows) now peaks well under 1 GiB (verified passing under a 2 GiB `max_memory_usage` cap). All assertions and the reference are unchanged in meaning. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reading the `quantized` / `pq_codebook` companion subcolumns of a `Quantize`-coded column failed after the table or part metadata was reloaded (DETACH/ATTACH, server restart, DatabaseReplicated): `length(vec.quantized)` returned 0, and the `pq` codebook path could segfault. The part's plain columns list cannot represent the codec's custom serialization, so after a reload the reader fell back to recomputing the subcolumn from the (empty) parent column or treated it as missing. Two reader paths needed honoring the storage type's custom serialization directly: - `IMergeTreeReader::getSerializationInPart` (Wide): it rebuilt the serialization from the part's `SerializationInfo`, which re-wrapped the custom serialization with the recorded kind stack and discarded the companion streams. Take the (unwrapped) custom serialization from the storage type instead - a Quantize column is always dense, so the kind stack does not apply. - `MergeTreeReaderCompact` (Compact): subcolumn presence was decided from the part's plain column type, which has no custom subcolumns, so the subcolumn was treated as missing. Decide presence from the requested column's storage type when it carries a custom serialization. Verified DETACH/ATTACH round-trips now read the codes and codebook correctly for both Wide and Compact parts (int8 and pq). CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
The AST fuzzer crashed `pqTrain` with `std::length_error`: `pqTrain([[...]], -9223372036854775807, 3, 1)`. The huge `dimensions` passed `validateParams` (it happened to be divisible by `m`), then `codebookFloats = 2^nbits * dimensions` overflowed `size_t` and a later `resize(num_samples * dimensions)` threw `std::length_error`, surfacing as a logical error. Cap `dimensions` in `ProductQuantization::validateParams` (shared by the codec and the `pqTrain`/`pqEncode`/`pqDistance` functions) at 2^20 - far above any real embedding - so the derived sizes cannot overflow and the error is a clean `BAD_ARGUMENTS` exception instead. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
- 01222_system_codecs: add the `Quantize` codec row and bump the codec count, now
that the codec is registered in system.codecs.
- 02354_vector_search_quantize_codec_{int8,pq,planner}: tag `no-parallel-replicas`.
These assert the two-stage codes rewrite fires (`quantized shortlist` in the
plan), but that optimization is deliberately disabled under parallel replicas,
so the plan-shape check cannot hold there (the query still returns exact
results in that case).
CI: ClickHouse#108565
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…zation The previous fix keyed the part-reader's custom-serialization handling on `IDataType::getCustomSerialization() != nullptr`, which is far too broad - it matches any type carrying a `DataTypeCustomDesc` (e.g. `Bool`). For such columns it bypassed the part's `SerializationInfo`, discarding the recorded Default/Sparse kind stack, which corrupted reads of unrelated sparse columns (Fast test: "Cannot read all data in MergeTreeReaderCompact" while reading a sparse column). Restrict the special-casing to exactly `SerializationQuantizedVector` (the only serialization that exposes companion subcolumns absent from columns.txt), via a `typeid` check, matching the existing guard in `ColumnsDescription`. Ordinary columns - including sparse ones - again take the normal info-based path. `getSerializationInPart` (Wide) and `MergeTreeReaderCompact` both adjusted. Verified: Quantize reattach still works (Wide+Compact, int8+pq), the full Quantize codec suite passes, and the sparse-column read regression is gone. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address automated review findings on the quantization functions: - `quantizeEncode`/`quantizeDistance` now run the full `VectorQuantization:: validateParams` (method, dimension bounds + multiple-of-8, bits range) before any size arithmetic. Previously e.g. `quantizeEncode([1.,0.], 'rabitq', 2, 0)` was accepted and the bit-packed kernel wrote out of bounds. - `VectorQuantization::validateParams` caps `dimensions` (matching `ProductQuantization::validateParams`) so an absurd value can no longer overflow `bytesPerVector`/the padded projection size. - `rabitq` and `turboquant` now clamp their estimated cosine to [-1, 1] before returning `1 - cosine`, so the public `cosineDistance` stays in [0, 2] (the unbiased estimators can fall outside the valid range), matching `e8`/`int8`. - `pqTrain` rejects an empty sample set instead of fabricating an all-zero codebook that looks like a successful training. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Two correctness guards on the two-stage vector-search rewrite, per automated review: - Bail out when the outer `LimitStep` has `WITH TIES` or `alwaysReadTillEnd` (totals / exact_rows_before_limit): the inserted shortlist `LimitStep` carries neither, so rows tied with the boundary distance or needed for read-to-end could be dropped before the original limit. - Bail out when the distance `ExpressionStep` contains an `arrayJoin`: it expands rows before the sort/limit, so splicing the shortlist limit below it would cut rows before the expansion and change the result cardinality. CI: ClickHouse#108565 Co-Authored-By: Claude Opus 4.8 <[email protected]>
Remove the `e8` lattice quantizer: empirically it was the weakest method here
(near-random on SIFT; only usable at very high bits, where it is still dominated
by trained `pq`), it assumes unit-normalized input (a silent footgun otherwise),
and it is by far the most complex code in the set. This drops the E8 lattice
codebook, ADC query and SIMD distance kernel.
Add `mrl` (Matryoshka Representation Learning) instead: it stores only the
leading `leading_dimensions` of the vector - the prefix that MRL-trained
embeddings concentrate their signal in - as the shortlist code, in one of two
formats:
- int8 with a per-vector symmetric scale (code = leading_dimensions + 4 bytes),
- bfloat16 (code = leading_dimensions * 2 bytes).
The shortlist distance is computed on the dequantized prefix (L2 or cosine); the
full-precision vector is kept for the exact rescore as with the other methods.
No training, no rotation - just a truncation, which is the standard MRL adaptive
-retrieval shortcut.
Syntax: `Quantize('mrl', dimensions, leading_dimensions, 'int8'|'bf16')`. This is
sugar that folds the format into the canonical method name (`mrl_int8` /
`mrl_bf16`, with the prefix length in the existing `bits` slot), so the
serialization, planner and distance paths use it like any other data-independent
method with no extra plumbing.
CI: ClickHouse#108565
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…configs Two config-sensitive failures of the `Quantize(...)` codec tests, seen in the CI reports for ClickHouse#108565 : 1. Old-analyzer config: `02354_vector_search_quantize_codec_{pq,int8,planner,mrl}` asserted the plan contains `LazilyReadFromMergeTree`, but lazy materialization is an analyzer-only query-plan optimization - even a plain `ORDER BY distance LIMIT` query does not produce the lazy read under the old analyzer, so the `has_lazy_read` assertion was 0. Pin `SET enable_analyzer = 1` in these tests (matching the sibling `02354_vector_search_rescoring*` / `02354_vector_search_lazy_materialization` tests), which overrides the old-analyzer CI default for the session. 2. ParallelReplicas config: `02354_vector_search_quantize_codec_invalid_params` and `..._pq_invalid_params` read `length(vec.quantized)`, but the quantized companion subcolumn is not read on the parallel-replicas path (it comes back empty, so the length is 0). Tag them `no-parallel-replicas`, consistent with the other quantize-codec tests that read the subcolumn. Verified locally: with a client `enable_analyzer=0` default an in-session `SET enable_analyzer = 1` restores the lazy read; and the other quantize-codec tests that read the subcolumn (`...codec`, `...kronecker`, `...pq_merge`, `...pq_multigranule`, `...rabitq_simd`) pass under parallel replicas, so they are correctly left untagged. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…bound pq training buffer Two fixes from the PR ClickHouse#108565 inline review: - `ReadFromMergeTree::addReadColumn` pulls the `Quantize` companion subcolumn (`<column>.quantized` / `<column>.pq_codebook`) into the read after query analysis. A PREWHERE / row-level-filter `ActionsDAG` only outputs the columns it was built with, so the added subcolumn was dropped after PREWHERE and the quantized-vector-search shortlist had no codes to rank. Pass the added column through those DAGs (adding it as an input when it is not one yet), mirroring `restorePrewhereInputs`. Adds a regression test exercising the PREWHERE path. - `SerializationQuantizedVector::trainCodebook` materialized up to `min(count, 100000) * dimensions` floats. A large `dimensions` (representable within the FixedString codebook limit) could reserve tens of GiB. Bound the training sample by a 256 MiB byte budget in addition to the vector-count cap. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ant end-to-end test Two items from the PR ClickHouse#108565 AI review / CI report (https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108565&sha=latest&name_0=PR): - The `arm_fuzzers` build failed to link with `undefined symbol: DB::createInternalFunctionPQDistanceResolver()` (and the analogous `createInternalFunctionQuantizeDistanceResolver`), referenced from the `useVectorSearchWithQuantizedCodes` optimizer. Internalizing these functions removed their `REGISTER_FUNCTION`, which was the hard reference that forced their objects to link; they are now pulled only across the `clickhouse_functions` -> `dbms` archive boundary, which the fuzzer link drops. Move `productQuantization.cpp` and `vectorQuantization.cpp` into `DBMS_FUNCTIONS` so they compile into `dbms` alongside their sole caller, exactly as `FunctionTopKFilter.cpp` (an analogous internal-only optimizer function) does. - `turboquant` had no end-to-end regression, only DDL-level coverage. Add `02354_vector_search_quantize_codec_turboquant` (modelled on the `rabitq` / `int8` tests): code length, exact top-k under a full-coverage shortlist, a high-recall shortlist, and self-match. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… a companion subcolumn Addresses AI-review comment on PR ClickHouse#108565 (ClickHouse#108565 (comment)). ClickHouse lets a physical dotted column shadow a subcolumn (`ColumnsDescription::tryGetColumn` returns the physical column first). A schema that declares both a `Quantize(...)` column `vec` and a physical column named `vec.quantized` (or `vec.pq_codebook` for `pq`) would make the quantized-vector- search rewrite resolve the physical column instead of the companion codes subcolumn - silently ranking the shortlist on unrelated bytes when the widths match, or throwing `__quantizeDistance` when they do not. The rewrite now detects a physical column occupying either companion name and leaves the query on the exact path - the same fall-back-to-exact it already takes wherever it cannot apply cleanly - so results stay correct. Adds `02354_vector_search_quantize_codec_shadowed_subcolumn` reproducing the silent- misbind schema (a `FixedString(12)` matching the 12-byte int8 code) and asserting the plan has no quantized shortlist and results equal the exact top-k. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…s; rename __pqDistance Addresses maintainer review requests on PR ClickHouse#108565: - Rename the user-facing (and internal) method names for readability: `pq` -> `product` and `mrl` -> `prefix`, including the folded `prefix_int8`/`prefix_bf16`, the codec parser, serialization, planner, `choosePartFormat`, error messages, comments, the stateless tests, and the docs. (The docs note `prefix` suits Matryoshka embeddings.) - `VectorQuantizer`/`ProductQuantizer` `createEncoder` and `prepareQuery` now return `unique_ptr` instead of `shared_ptr`, since the encoder/query are stateful single-owner objects. The types stay opaque (defined in the .cpp), so a small out-of-line custom deleter is used to hold them by `unique_ptr` through the header. - Rename the internal SQL function `__pqDistance` -> `__productQuantizationDistance`. All 02354_vector_search_quantize_codec_* tests pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…or-codec Quantization CODECs for vector columns and 2-stage retrieval
The Quantized('product', ...) codec fixed here is an experimental feature
(allow_experimental_codecs) added this cycle in ClickHouse#108565 and not present in
any released version, so this is not a stable-release bug fix. The Bugfix
Validation gate additionally requires a regression test that fails on master
HEAD without the fix, but the failure is scheduling/prefetch dependent under
concurrency and does not reproduce deterministically from a single stateless
query. Empty commit to re-run CI after the changelog category change.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds quantization support for vectors. Vector columns can now store full precision values and quantized values. When enabled via the
vector_search_use_quantized_codessetting (off by default, so the default remains exact KNN), the optimizer performs a 2-stage vector search - first get candidates using fast search on the quantized companion stream (less I/O and CPU-optimized distance computation) and then rescore/rerank using the full-precision vectors in the second stage.Adds the following methods for the
Quantize(...)vector column codecChangelog category
Changelog entry
Quantize(...)vector codec family and an opt-in two-stage approximate vector-search rewrite over quantized companion streams.