Skip to content

Add hierarchicalKMeans and assignCentroid - #112309

Merged
shankar-iyer merged 38 commits into
ClickHouse:masterfrom
shankar-iyer:add_kmeans_and_assign_centroid
Sep 9, 2026
Merged

shankar-iyer merged 38 commits into
ClickHouse:masterfrom
shankar-iyer:add_kmeans_and_assign_centroid

Conversation

@shankar-iyer

@shankar-iyer shankar-iyer commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Adds functions for computing cluster centroids and assigning new vectors to clusters.

Ref : #112578

Changelog category

  • Experimental Feature

Changelog entry

  • Added hierarchicalKMeans() and assignCentroid() functions to support a framework for IVF style vector search .

Workflow [PR]
Sync PR [sync-upstream/pr/112309]

shankar-iyer and others added 2 commits July 26, 2026 16:04
Two building blocks for constructing an IVF vector index in SQL:

- hierarchicalKMeans(k[, branching, max_iter, sample_cap, seed])(vec):
  parametric aggregate that trains k centroids with hierarchical k-means
  over a bounded reservoir sample and returns Array(Array(Float32)). Used
  to build the coarse quantizer / centroids table.

- assignCentroid(vec, centroids | 'dict_name'): scalar returning the
  nearest-centroid id, from an inline constant Array(Array(Float32)) or a
  dictionary. Centroids are tiled so the centroid matrix is streamed once
  per block instead of once per vector.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@shankar-iyer
shankar-iyer marked this pull request as draft July 28, 2026 16:12
@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [d7efc7d]

Summary: ✅


AI Review

Summary

This PR adds experimental hierarchicalKMeans and assignCentroid primitives for SQL-side IVF quantization. Most of the earlier kernel and state-serialization bugs are fixed in the current head, but two correctness blockers remain: the dictionary form of assignCentroid is still missing the same dictionary-name plumbing that dictGet-style functions use across distributed and stored-expression surfaces, and hierarchicalKMeans still seeds every partial reservoir from the same PRNG state, so many-state aggregation does not produce a uniform sample.

Findings

❌ Blockers

  • [src/Functions/assignCentroid.cpp:370] assignCentroid(v, 'dict') still bypasses the analyzer/DDL plumbing that tracks dictionary names on other dictGet-style surfaces. functionIsDictGet and the visitors built on it still only treat argument 0 as a dictionary name, so this new argument-1 surface is not qualified against the initiator's current database on distributed queries and stored expressions do not record or rewrite their dictionary dependency for DROP / RENAME DICTIONARY. Suggested fix: wire assignCentroid into the same qualification/dependency/rename path with dictionary-name argument index 1, then add focused distributed and stored-expression regressions.
  • [src/AggregateFunctions/AggregateFunctionHierarchicalKMeans.cpp:1033] Every partial aggregate state still seeds its reservoir with mixSeed(seed, 0). Once aggregation fans out to multiple local or distributed states, their Algorithm R decisions become correlated instead of independent, so the merged reservoir is not a uniform sample of the union. The three-rows-per-side, sample_cap = 2 counterexample from the open thread still applies: both partial states always drop the same local position, which overweights subsets like {a1, b1}. Suggested fix: give each partial state an independent reservoir stream or switch to a mergeable priority-sampling scheme.
Tests
  • ⚠️ [tests/queries/0_stateless/02354_vector_search_assign_centroid.sql:65] The dictionary form now performs a dictGet-style access check, but there is still no negative RBAC regression. A small .sh test mirroring 04404_naive_bayes_access.sh would prove that users without dictGet on the dictionary are denied and that granting it makes the call succeed.
  • ⚠️ [tests/queries/0_stateless/02354_vector_search_hierarchical_kmeans.sql:54] The only transported / merged-state coverage still checks length(...) = 4, which would stay green if the reservoir merge regressed again. Add a focused merge regression where k = sample_cap and the result exposes the sampled rows directly, plus a both-sides-overflow case.
Final Verdict

Not ready. The remaining dictionary-name plumbing gap and the correlated reservoir seeding both still break the advertised behavior on real execution paths.

LLVM Coverage Report

Measured on commit d7efc7d.

Metric Baseline Current Δ
Lines 88.90% 88.90% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 672/781 (86.04%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Jul 28, 2026
shankar-iyer and others added 2 commits July 28, 2026 17:15
…signCentroid

Three CI failures on ClickHouse#112309:

* `Build (arm_tidy)`: `readability-use-std-min-max` on the `branching` clamp
  in `AggregateFunctionHierarchicalKMeans.cpp`. Use `std::max`; the adjacent
  `max_iter` clamp is converted the same way for consistency (equivalent for
  `size_t`).

* Style check `cpp`: `std::vector` is not allowed in `src/AggregateFunctions`
  and `src/Functions` because plain standard containers track memory through
  non-throwing methods of the `MemoryTracker`. Switch all of them to
  `VectorWithMemoryTracking`. These allocations are worth tracking properly:
  they scale with `sample_cap` (1M vectors by default) and with the centroid
  count `k`.

* Style check `various`: "Avoid holding a copy of ContextPtr in Functions".
  Replace the bare `ContextPtr` member of `FunctionAssignCentroid` with
  `FunctionDictHelper`, the pattern already used by the `dictGet` family in
  `FunctionsExternalDictionaries.h`. This also closes a gap: `assignCentroid`
  read a named dictionary without performing the `dictGet` access check, and
  `FunctionDictHelper::getDictionary` does it.

Note that the last point is a behaviour change - a user without `dictGet`
privileges on the dictionary now gets an access denied error.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Both functions validated their vector argument with `isFloat`, which accepts
`Float32`, `Float64` and `BFloat16`, but the kernels read the nested column as
`ColumnFloat32` via `assert_cast`. In a release build `assert_cast` is a plain
`static_cast`, so an `Array(Float64)` argument had its payload reinterpreted as
`Float32` and the functions silently returned wrong results; in a debug build
the same query raises a logical error exception.

This was easy to hit, because array literals are `Float64`: the documented
example `SELECT assignCentroid([1.0, 2.0], [[0.0, 0.0], [1.0, 2.0]])` returned
the wrong centroid id (2 instead of 1). The example is updated to CAST.

Tighten all four checks to `Float32` exactly:
* the vector argument of `assignCentroid`,
* the inline centroids argument of `assignCentroid`,
* the `vec` attribute of the dictionary form of `assignCentroid` - this one
  has to be checked while reading the dictionary, since the dictionary name is
  a runtime string and its attribute types are not known during analysis,
* the argument of `hierarchicalKMeans`.

The error messages now mention `Array(Float64)` as something to CAST.

This changes which arguments are accepted: queries that used to pass
`Array(Float64)` now get `ILLEGAL_TYPE_OF_ARGUMENT` instead of a wrong answer.

Related: ClickHouse#112309

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/assignCentroid.cpp Resolved
shankar-iyer and others added 6 commits July 31, 2026 14:02
Training ran entirely on one thread inside `insertResultInto` with scalar
`double` accumulation, which put a single global `hierarchicalKMeans(32768)`
over 1M x 768 vectors at roughly 16 minutes of wall clock on an idle 48-core
box. This makes it 13 seconds.

**`spherical` parameter.** A sixth optional parameter renormalizes the centroids
to unit length after every Lloyd update. With `||c|| = 1` the `||c||^2` term of
the argmin is constant, so `argmin ||x-c||^2 == argmax x.c == argmax cos(x, c)`
for any `||x||` - which means the existing L2 `assignCentroid` and an
`ORDER BY L2Distance` probe over the centroids become an exact cosine quantizer
with no change to either. Off by default; plain L2 is already equivalent when
the vectors are L2-normalized at ingest.

**SIMD.** The argmin, the k-means++ seeding pass and the mean accumulation moved
into `DECLARE_MULTITARGET_CODE` kernels dispatched at runtime to the widest
supported ISA. The centroid block is packed column-major (`ct[j * k + c]`), so
the inner loop over centroids is a contiguous FMA against a broadcast `x[j]` and
the accumulators stay in registers across the whole dimension loop. Dot products
now accumulate in float; `sums` stays `double`, where the precision is actually
needed. The kernels are written as plain contiguous loops so the `Default`
variant still auto-vectorizes where multitarget code is off, such as ARM.

**Multi-threading.** The recursion is now a breadth-first walk, because the two
available kinds of parallelism live in different regimes and must not nest: near
the root there are few nodes holding most of the points, so rows are split
across threads; deeper there are thousands of small nodes, so whole nodes run
concurrently. Each level picks exactly one regime, so a pooled task never waits
on sub-tasks from the same pool. Threads and pool come from
`max_build_vector_similarity_index_thread_pool_size` - training an IVF coarse
quantizer is the same kind of work as building a vector index, and sharing the
pool avoids oversubscription when several run at once. `KILL QUERY` is honored.

Results stay reproducible for a given seed. Each node derives its RNG seed from
its parent's seed and its child index rather than from a single stream threaded
through the walk, row ranges and output slots are fixed up front, and every
cross-thread reduction runs in thread-index order rather than completion order.
Verified: identical checksums at 1, 4, 16 and 48 threads.

Measured, k=1024 over 100k x 768 (training only, insert subtracted):

    before                  65.9 s
    after, 1 thread         18.1 s   (SIMD alone, 3.6x)
    after, 16 threads        1.34 s  (49x)

and k=32768 over 1M x 768: 19.6 s at 16 threads, 13.2 s at 48.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The per-tile scoring loop is the whole cost of `assignCentroid` on a large
centroid set, and it was compiled once at the translation unit's baseline ISA.
Move it into `DECLARE_MULTITARGET_CODE` and dispatch at runtime to the widest
ISA the CPU supports.

The loop structure is unchanged - it was already the right shape, with the tile
packed column-major so the inner loop over centroids is a contiguous FMA against
a broadcast `x[j]`. Two incidental cleanups fall out of extracting it: the
offsets array no longer has to be touched in the hot loop, because every row is
already validated to have exactly `dim` elements and therefore starts at
`row * dim`, and the running best score and id are held in registers for the
whole tile.

This is SIMD only, deliberately. `executeImpl` already runs concurrently on many
pipeline threads, one per block, so spawning threads inside it would only
oversubscribe.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The previous commit dispatched the scoring loop to wider SIMD but left it a
sequence of GEMVs: one vector at a time against the whole centroid tile. At
k=32768 x 768 that is ~100 MB of centroids streamed per vector, and it measured
2.6 ms per vector on one core.

Restructured into a register-blocked GEMM microkernel: 6 rows x 16 centroids,
with the 96 accumulators held in registers (12 YMM on AVX2, 6 ZMM on AVX-512)
for the whole dimension loop. Loop order is row-block outermost, so the block's
vectors stay in L1 while the centroid sub-blocks stream past, and the centroid
tile is read once per row block instead of once per row. The tile width is now
derived from `dim` to target L2 instead of being a fixed 1024, which was 3 MB at
dim=768 and half-empty at dim=128, and the tile is padded to a whole number of
16-centroid blocks (zero centroids with an infinite `cnorm`, which can never win
the argmin) so both inner extents are compile-time constants and no scalar
remainder loop is needed.

Worth recording that the obvious intermediate step is not the one that matters.
Blocking rows with the accumulators in an L1 scratch buffer - which is what the
tiling comment in the original code was reaching for - only moved 156 s to
124 s, because an L1-resident accumulator pays a load and a store per FMA and
tops out near a quarter of FP peak however well the tiling is arranged. Getting
the accumulators into registers is what unlocked the rest.

Measured, 60k vectors against 32768 centroids at dim=768, single thread:

    GEMV, SIMD-dispatched      156 s     (2.60 ms/vector)
    row-blocked via L1         124 s     (2.06 ms/vector)
    register-blocked GEMM       44.7 s   (0.74 ms/vector)

That is 67 GFLOP/s on one core, roughly 70% of AVX2 FMA peak. Assigning 10M
vectors over 48 threads goes from about 9 minutes to under 3.

Accumulation order per (row, centroid) is unchanged and the argmin is still
scanned in ascending centroid order, so results including tie-breaking are
bit-identical. Verified against a brute-force `argMin(cid, L2Distance(...))` at
row counts on both sides of the block size (1, 2, 5, 7, 1003, 4999) and with a
centroid count that exercises the padding.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`hierarchicalKMeans(32768)` on a 4M-vector LAION sample returned 32746, not
32768. `apportion` seeded every child with one leaf via `leaves(B, 1)`,
including children whose bucket came out empty, and `processTask` then skipped
those children - so their leaves were silently dropped. Lloyd reseeds empty
clusters while iterating, but the final bucketing pass runs against the
post-update centroids with no further reseed, so a centroid owning no points
still reaches `apportion`.

`apportion` now allocates only to children that own points, and never gives a
child more leaves than it has points, since a child can emit at most one
centroid per point. Anything those two rules displace is redistributed to
children with headroom, so the total is exactly `k` whenever the node holds at
least `k` points at all.

That alone introduces a non-termination case, which is worth spelling out: once
empty children are excluded, a node whose split puts every point in ONE bucket
hands that single child all `k` leaves, and the child is then identical to its
parent - the walk reproduces the same node forever. It is reachable on
degenerate input, such as a node whose vectors are all equal, where every
centroid collapses onto the same value. `processTask` now detects a split that
produced fewer than two non-empty buckets and emits a flat k-means at that node
instead of recursing. Past that check every child is strictly smaller than its
parent, which is what bounds the recursion.

Verified: `hierarchicalKMeans(32768)` over 300k vectors returns exactly 32768;
1000 leaves over data with 7 distinct vectors returns 1000; 50 leaves over
all-identical vectors returns 50; and k=500 over 100 points returns 100, which
is correct - k is capped by the point count. Determinism across 1/16/48 threads,
the `spherical` unit-norm contract and blob-recovery quality all unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Four `arm_tidy` errors from the register-blocked kernel:

* `readability-static-definition-in-anonymous-namespace` on `ROW_BLOCK` and
  `COL_BLOCK` - `static` is redundant at anonymous-namespace scope. Dropped it;
  they stay `constexpr`, which is what the kernel actually relies on (both
  extents must be compile-time constants so clang unrolls the inner loops and
  keeps the accumulators in registers).

* `modernize-loop-convert` on the two accumulator-zeroing loops. Replaced them
  with value-initialization (`Float32 acc[ROW_BLOCK][COL_BLOCK] = {}`) rather
  than range-based loops - it drops the loop entirely and reads better.

Verified the hot path did not regress: 60k vectors against 32768 centroids at
dim=768 on a single thread is 44.4 s, against 44.7 s before, and the kernel
still matches a brute-force `argMin(cid, L2Distance(...))` exactly at row counts
either side of the block size (1, 5, 7, 1003).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.40% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 56/600 (9.33%) · Uncovered code

Full report · Diff report

shankar-iyer and others added 4 commits August 2, 2026 15:53
Six issues raised on ClickHouse#112309:

* Empty input vectors. `Array(Float32)` permits `[]`, and `dim = 0` is also the
  "no rows yet" sentinel, so `hierarchicalKMeans(1)([])` divided by zero instead
  of failing cleanly. Rejected at `add`, and `deserialize` now validates the
  same invariant rather than trusting the state.

* The merge was not a uniform reservoir merge. It fixed each side's contribution
  to its expectation, which is deterministic: with `sample_cap = 1` and two
  one-row states the split was `floor(1 * 1 / 2) = 0`, so the left sample was
  always dropped. Replaced with a properly randomised merge - replay the smaller
  side through Algorithm R when it kept every row, otherwise choose each slot's
  origin per slot with probability equal to that side's share of the stream.

* The PRNG was not serialized, so a state crossing a distributed merge resumed
  from a default-constructed generator. Now round-tripped via
  `IO/Operators_pcg_random.h`, which required moving the reservoir generator
  from `pcg64` to `pcg32_fast`: only the latter has an in-tree serializer, and
  pcg's own stream operators cannot emit a 128-bit state here. 64-bit ranges use
  the same two-draw widening as `ReservoirSampler`. The training generator is
  never serialized and stays `pcg64`.

* Dictionary `cid` was narrowed from `UInt64` to the `UInt32` result, silently
  wrapping past `2^32 - 1` and returning the wrong id. Now rejected explicitly.

* `spherical = 1` did not actually guarantee `||c|| = 1`: `normalizeCentroids`
  skipped zero-norm centroids. Zero-norm inputs are rejected (cosine is
  undefined for a vector with no direction) and an exactly-cancelling cluster
  mean falls back to a fixed unit vector, so the invariant `assignCentroid`
  relies on now holds unconditionally.

* `is_order_dependent` was `false`, which is wrong - the `k >= n` path emits
  points in arrival order and Algorithm R consumes draws by stream position.
  Left as is, `removeRedundantSorting` could drop an upstream `ORDER BY` and
  silently change the trained centroids.

One thing the fixes surfaced: seeds must be hashed before use. pcg's `oneseq`
engines set state directly, so nearby seeds stay correlated for the first few
draws - seeds 1..40 all produced an even first output, which biased Algorithm
R's first keep/replace decision identically every time. Both the reservoir and
the tree root now seed through splitmix64; the reviewer's `cap = 1` case is
16/14 across seeds instead of 40/40.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Neither function had any test coverage, so nothing in CI guarded the behaviour
the recent fixes established.

`02354_vector_search_hierarchical_kmeans` covers exactly-k output (including k
capped by the point count), recovery of four separated blobs, determinism for a
fixed seed, the `spherical = 1` unit-norm contract, aggregate state round-trip
through serialization, and termination on degenerate input - data with only a
handful of distinct vectors, which previously either lost centroids or recursed
forever.

`02354_vector_search_assign_centroid` covers both the inline and dictionary
forms, agreement between them, lowest-id tie-breaking, and equality with a
brute-force `argMin(cid, L2Distance(...))`. The sizes are deliberate: 301
centroids is not a multiple of the GEMM kernel's 16-wide column block and 1003
rows is not a multiple of its 6-row block, so the padding lanes and the row
remainder are both exercised - a row count divisible by the block size would
leave the tail path untested, which is how it went unnoticed before.

Both files also assert the error paths: `Array(Float32)` required exactly on
every argument, empty and zero-norm vectors, ragged input, a non-constant
centroid argument, and the parameter validation.

Verified against a server (not just `clickhouse-local`) under default settings,
`max_threads` 1 and 2, and `max_block_size` 7 and 100 - the small block sizes
matter because they exercise the multi-block paths, dictionary matrix caching
across blocks and aggregate state merging, that a single-block run hides.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`clang-analyzer-core.DivideZero` on `rng() % limit` in `genRandom`. Every caller
passes a value it has just established is positive - `addVector` increments
`seen` immediately before the call, and `have_b` is `cap` on the only other path
- but none of that survives across the call boundary for the analyzer.

`ReservoirSampler.h:277` silences the identical warning with a `NOLINT`. Guarded
instead: a well-predicted compare is cheaper than reasoning about whether the
precondition can ever be violated, and it removes the divide-by-zero as a class
rather than asserting it away.

Also bounded the replay loop in the `seen <= cap` merge branch by the rows
actually held rather than by `seen`. The two are equal there - a side that never
exceeded the cap dropped nothing - but indexing a buffer by its own length is
the version that stays in bounds if that invariant ever changes.

Neither change alters behaviour: the cross-thread determinism checksum is
identical before and after, the reviewer's `cap = 1` merge case is still
randomised (10/6 over 16 seeds), and both stateless tests still match.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing d7efc7dd2 with master 602ce8d11 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

4 object files changed (+927.63 KiB total), 2 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/assignCentroid.cpp.o new 465.71 KiB +465.71 KiB
src/AggregateFunctions/CMakeFiles/clickhouse_aggregate_functions.dir/AggregateFunctionHierarchicalK… new 461.76 KiB +461.76 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

9 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/AggregateFunctions/AggregateFunctionHierarchicalKMeans.cpp: 5.9 s
  • src/Functions/assignCentroid.cpp: 5.2 s

Job report

…r merge

The previous fix randomised the merge but the fully-downsampled branch was still
not uniform, in two independent ways:

* Each destination slot picked its row from `other.samples` WITH replacement, so
  the same underlying row could land in two slots. A size-`cap` sample of the
  union can never contain a duplicate.
* Deciding each slot independently makes the per-side count binomial. With
  `cap = 2` and `seen = other.seen = 3` that gives P(both slots from `other`) =
  1/4, where a genuine sample of the six underlying rows requires the
  hypergeometric 1/5.

The count is now drawn hypergeometrically - `cap` items from the combined
`seen + other.seen` stream, of which `other.seen` belong to `other` - by urn
simulation, which is exact and needs no floating point since
`genRandom(remaining_total) < remaining_b` is precisely
`remaining_b / remaining_total`. Each side then contributes that many rows
WITHOUT replacement via partial Fisher-Yates, over the rows directly for our own
side and over an index array for `other`, which is const. Subsampling a uniform
sample uniformly is itself uniform, so the two halves compose into a uniform
sample of the union.

The draw costs O(cap) against the O(cap * dim) the row copying already costs.
`randomDouble` is gone with its only caller.

Verified over 1200 merges of two three-row states at `sample_cap = 2`: zero
results contained a repeated underlying row, and the side-count distribution was
0.1825 / 0.6258 / 0.1917. Chi-square is 3.59 against the hypergeometric
0.2 / 0.6 / 0.2 (df = 2, not rejected) and 76.20 against the binomial
0.25 / 0.5 / 0.25 (decisively rejected).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Functions/assignCentroid.cpp Resolved
Comment thread src/Functions/assignCentroid.cpp Resolved
@shankar-iyer
shankar-iyer marked this pull request as ready for review August 4, 2026 08:51
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 40 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: ce6dc066-6644-4ec2-b680-7c99a78d5186
  • MIRAI run: 39200605-a78a-4e30-9e89-fe97a8d622ec
  • PR check IDs:
    • clickbench_34489_1788936121
    • clickbench_34496_1788936121
    • clickbench_34503_1788936121
    • tpch_adapted_1_official_34513_1788936121
    • tpch_adapted_1_official_34528_1788936121
    • tpch_adapted_1_official_34561_1788936121

shankar-iyer and others added 2 commits August 18, 2026 15:05
Review round on ClickHouse#112309.

Both functions now accept `Array(Float64)` and `Array(BFloat16)` and convert to
the `Float32` the kernels use, instead of rejecting them. `assignCentroid([1.0,
2.0], [[0.0, 0.0], [1.0, 2.0]])` works now - array literals are `Array(Float64)`,
so requiring `Float32` meant the most natural way to call either function was an
error. `assignCentroid` converts once per block through `castColumn`; the
aggregate reads whichever float column it was handed and converts as it copies
into the reservoir, so `Float32` keeps its memcpy path. Verified `Float32` and
`Float64` inputs produce identical centroids.

Writing the requested tests for the aggregate's own parameters turned up two
gaps. `hierarchicalKMeans(4, -1)` was accepted outright: a negative literal is an
`Int64` field, and reading it as `UInt64` wrapped `branching` to 2^64 - 1. Float
and string parameters raised a bare `BAD_GET` from the field accessor. Parameters
are now read through one helper that rejects anything that is not a non-negative
integer and names the offending parameter.

Also from review:
  * `useDefaultImplementationForConstants` returns true - it only engages when
    every argument is constant, and the centroids stay a `ColumnConst` because of
    `getArgumentsThatAreAlwaysConstant`, which is what the matrix builder wants.
  * Dropped two unreachable `ILLEGAL_COLUMN` throws. The framework validates
    `getArgumentsThatAreAlwaysConstant` before the function runs, so a non-const
    centroid argument never reaches us; confirmed the error users see comes from
    there. `assert_cast` keeps the debug-build check.
  * `build()` gains a worked example of the packed layout for three centroids,
    and its comment no longer claims to run once per INSERT block - that is true
    only of the inline form, not the cached dictionary form.
  * Documented that the inline centroid id is the 0-based array position.
  * Said why the centroid matrix is a `shared_ptr`: the dictionary form returns
    the cached matrix, which another thread may swap.
  * Dropped the `HIERARCHICAL_KMEANS` thread name and reused
    `MERGETREE_VECTOR_SIM_INDEX`. Training shares that pool, so the extra entry
    in a common header bought nothing. `setThreadName.h` is untouched again.
  * Tests: `cents` -> `centroids`, k-capped-by-rows reuses `blobs` instead of its
    own table, and the GEMM jargon and two unclear comments are rewritten.

And three findings from the review bot:
  * `deserialize` only bounded the stored row count from above. `merge` treats
    `seen > sample_cap` as proof that the side holds exactly `sample_cap` rows and
    indexes on that basis, so a state claiming `seen = cap + 1` while storing one
    row walked off the end of `samples`. It now re-establishes the full
    `have == min(seen, sample_cap)` invariant.
  * `deserialize` also skipped the `spherical = 1` zero-norm check that `add`
    applies, so a transported state could carry a zero vector into training.
  * The documented output cap said "distinct points"; it is the row count -
    repeated points still yield k centroids.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@shankar-iyer

Copy link
Copy Markdown
Member Author

@rschu1ze Fixed the comments.

Please also check #112309 (comment)

Comment thread src/Functions/assignCentroid.cpp Resolved
shankar-iyer and others added 2 commits August 19, 2026 00:40
Three review-bot findings on
ClickHouse#112309.

Adding Float64/BFloat16 support introduced a per-row heap allocation in `add`:
every input row built a `VectorWithMemoryTracking` to stage the converted
vector, including rows the reservoir was about to discard. The reservoir now
decides the destination slot first (`reserveSlot`) and the caller writes into it
second, so `Float32` keeps its memcpy, the other widths convert straight into
the slot with no buffer, and a discarded row copies nothing at all.

Measured over three runs each, single-threaded, `k = 2` so training is trivial:

    dim=128, 2M rows, all kept        2.561 s -> 2.483 s
    dim=768, 500k rows, all kept      5.199 s -> 5.136 s
    dim=768, 500k rows, 499k dropped  1.709 s -> 1.619 s

So 1-5%, not the dominant cost the report suggested - jemalloc's thread cache
makes a 3 KB allocation cheap. Worth keeping anyway: it is strictly less work in
the hottest loop of the ingest path, and it is a regression I introduced.

The other two findings are one bug in two places, and it is real. Finiteness was
not sufficient: the scoring math is `Float32`, so a finite coordinate above
`sqrt(FLT_MAX)` squares to infinity, `score = cnorm - 2 * dot` becomes NaN, no
`score < best` comparison is ever true, and the row silently takes the fallback
id. Confirmed: `assignCentroid([2e19], [[0.0], [2e19]])` returned `0` when the
exact match was centroid 1, with the onset between 1e19 and 2e19. Training
degrades the same way, though the visible symptom differs from the report - the
centroids stay finite, but every point collapses into one cluster, so the
numbers look plausible and the clustering is meaningless.

Rejecting rather than widening the accumulators. `double` in the inner FMA loop
would halve the SIMD lanes and give back most of the GEMM speedup, to protect
coordinates around 1e19 that no embedding produces. The bound is checked in the
finiteness pass that already reads every coordinate, so it costs one compare:
`|x| <= sqrt(FLT_MAX / (4 * dim))`, which keeps the sum of squares, the dot
product and their difference finite. At dim = 768 that is ~3.3e17. Applied to
probes, to inline and dictionary centroids, and to training input and
transported states.

Verified the reservoir rewrite changes no behaviour: all three float widths
still train, `Float32` and `Float64` still produce identical centroids, and the
cross-thread determinism checksum is unchanged at 4088.667 for 1 and 48 threads.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The parameter tests only exercised `k` for all three bad types, plus a
negative `branching` and `sample_cap`. `max_iter`, `seed` and `spherical`
had no bad-type test at all, and `NULL` was untested everywhere.

All of these already reject with `BAD_ARGUMENTS` - every position goes
through the same integer check - but the coverage was uneven, so add the
missing cases.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread src/Functions/assignCentroid.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Sep 4, 2026
GROUP BY p.id
);

SELECT '-- the dictionary form returns the dictionary cid, not the row position';

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.

assignCentroid adds a dictionary-backed surface behind dictGet, but this test file still never proves the RBAC contract. Similar dictionary-backed user functions already carry a focused access regression here; for example, see tests/queries/0_stateless/04404_naive_bayes_access.sh.

Without a negative test, moving or bypassing the FunctionDictHelper check in src/Functions/assignCentroid.cpp would not fail CI even though this function full-reads the dictionary and returns ids derived from it. Please add a small .sh test that shows a user without dictGet gets ACCESS_DENIED, and the same query succeeds after GRANT dictGet.

SELECT '-- empty input produces no centroids';
SELECT length(hierarchicalKMeans(4)(v)) FROM (SELECT [1.0, 2.0]::Array(Float32) AS v FROM numbers(0));

SELECT '-- the aggregate state round-trips through serialization';

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 is the only coverage for the transported / merged-state path, but it asserts only length(hierarchicalKMeansMerge(...)) = 4. That would stay green even if HierarchicalKMeansData::merge regressed back to the earlier wrong-reservoir branches, because a broken sample still produces four centroids.

Please add a branch-specific regression for the merge logic itself. A practical shape here is a small case with distinct source rows and k = sample_cap, so the k >= n fast path returns the sampled rows verbatim; then a both-sides-overflow regression that reintroduces duplicate sampling or a one-sided-overflow replay bug shows up directly in the result instead of being hidden behind a length check.

shankar-iyer and others added 3 commits September 8, 2026 15:06
The `Docs examples` job executes the structured examples of every entity
against a real server, and the only example of `hierarchicalKMeans` read
from a table `sample` that does not exist:

  AggregateFunction/hierarchicalKMeans#0  [error]
    | SELECT length(hierarchicalKMeans(256)(vec)) FROM sample
    ! Code: 60. DB::Exception: Unknown table expression identifier 'sample'. (UNKNOWN_TABLE)

Replace it with two self-contained examples that also document their
response, so the runner checks the output and not just that the query
parses. The second one trains four well-separated clusters, whose
centroids are exact and therefore stable across thread counts and across
the aggregate-state merge.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112309&sha=f290168051d2f41264ccb4ebae2eb24c693b2b50&name_0=PR&name_1=Docs%20examples
Related: ClickHouse#112309

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…nCentroid

The generated reference pages come from these `FunctionDocumentation`
blocks, and they described a narrower contract than the code implements.

`hierarchicalKMeans` advertised only `Array(Float32)` for `vec`, while
the constructor accepts any float width (`isFloat`, so also
`Array(Float64)` and `Array(BFloat16)`) and converts to the `Float32`
the kernels use. Its `parameters` field was empty, so none of the six
positional parameters was described. Document `k`, `branching`,
`max_iter`, `sample_cap`, `seed` and `spherical` with their defaults and
the bounds the constructor enforces, and pass `parameters` to the
`FunctionDocumentation` constructor instead of `{}`.

`assignCentroid` advertised only `Array(Array(Float32))` or `String` for
the second argument, though `isCentroidsArray` accepts any float width
there too. Document that the argument must be constant, and spell out
the dictionary schema the dictionary form requires: `cid` of an unsigned
integer type that fits `UInt32`, and `vec` of type `Array(Float32)`.

Also drop a stale comment in `hierarchicalKMeans` claiming `Float32` is
required exactly, which contradicted the comment and the code directly
below it, and wrap the type and attribute names in the two descriptions
in inline code.

Related: ClickHouse#112309

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
/// Shared, not owned: the dictionary form hands back the cached matrix, which another thread may
/// swap, so the refcount is what keeps this one alive for the duration of the call.
std::shared_ptr<const CentroidMatrix> matrix;
if (isString(arguments[1].type))

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.

assignCentroid needs the same dictionary-name plumbing that dictGet and naiveBayesClassifier already have, but this new surface is invisible to all of those helpers because its dictionary name lives in argument 1, not argument 0.

Today functionIsDictGet only feeds arg-0 handling in resolveFunction.cpp, AddDefaultDatabaseVisitor.h, DDLLoadingDependencyVisitor.cpp, DDLDependencyVisitor.cpp, and DDLRenamingVisitor.cpp, so assignCentroid(v, 'my_dict') is shipped to remote shards unqualified and stored expressions never record or rewrite their dependency on the dictionary.

That makes the feature behave incorrectly on real surfaces: a Distributed query can resolve the dictionary against the shard's current database instead of the initiator's, and a table/view default using assignCentroid(..., 'dict') will not block or follow DROP / RENAME DICTIONARY. Please wire the second argument into the same qualification/dependency/rename path and add the distributed/dependency regressions.

@rschu1ze rschu1ze 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 overall, thanks. I think we need to de-AI the code when we make it non-experimental. That 2-3 hours going over the code comments and variable names will be worth the effort.

"Trains up to `k` cluster centroids from the aggregated vectors using hierarchical k-means and returns "
"them as `Array(Array(Float32))`. Fewer than `k` are returned only when the input has fewer than `k` rows, "
"since a row can yield at most one centroid; repeated points still yield `k`. Distance is squared L2; "
"pass `spherical = 1` to "

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.

"cosineDistance" would be a more fitting parameter name.

"cosine/inner-product quantizer.";
FunctionDocumentation::Syntax syntax = "hierarchicalKMeans(k[, branching[, max_iter[, sample_cap[, seed[, spherical]]]]])(vec)";
FunctionDocumentation::Arguments arguments = {
{"vec", "Vector to cluster. Every row must have the same dimension, and every coordinate must be finite. "

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.

"Vectors to cluster" (plural)

{"seed", "Optional. Seed of the reservoir sampling and of the k-means++ initialization. A given seed makes "
"training reproducible for a given input order. Default value: 0.", {"UInt*"}},
{"spherical", "Optional. Set to 1 to renormalize the centroids to unit length after every iteration, which makes "
"them an exact cosine/inner-product quantizer. Zero-norm input vectors are then rejected, because "

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.

"rejected" means ignored?

EDIT: Yes, we throw an exception

void serialize(ConstAggregateDataPtr __restrict place, WriteBuffer & buf, std::optional<size_t>) const override
{
const auto & d = data(place);
writeBinary(d.dim, buf);

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.

writeVarUInt here and in the next line as well?

writeVarUInt(d.samples.size(), buf);
buf.write(reinterpret_cast<const char *>(d.samples.data()), d.samples.size() * sizeof(Float));

/// The reservoir is only uniform if the PRNG keeps advancing across the serialization boundary. Without

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.

Not clear what the comment says but l. 1107-1109 is okay.

/// Pack row-major centroids into the column-major layout `assignRows` wants, and their squared norms.
void packCentroids(const Float * rows, size_t k, size_t d, Float * ct, Float * cnorm)
{
for (size_t c = 0; c < k; ++c)

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.

Cosmetic: we are generally using way too short variable names, hard to keep track of the cs, ds, dims, js, s, cts, etc.

const Float * pts, size_t n, size_t d, const Float * ct, const Float * cnorm, size_t k,
UInt32 * assign, Float * best_out)
{
#if USE_MULTITARGET_CODE

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.

We live in an ARM world today, feel free to drop the x86 vectorization.

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.

Yes, but let's retain it.

Comment thread src/Functions/assignCentroid.cpp Outdated
namespace
{

/// Register-blocking shape: 6 x 16 accumulators is 12 YMM registers on AVX2 (of 16), leaving the rest for

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.

Premature optimization?

Comment thread src/Functions/assignCentroid.cpp Outdated

DECLARE_MULTITARGET_CODE(

/// Score n rows against ONE packed tile of width centroids, keeping the running best score/id per row.

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.

(A simpler but readable version of the code is generally preferred. The same problem must be solvable by brute force).

const Float32 * pack, const Float32 * cnorm_tile, const UInt32 * ids_tile,
size_t width, Float32 * best_score, UInt32 * res)
{
#if USE_MULTITARGET_CODE

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.

Please see my comment about x86 in the other cpp file

/// Hash the seed rather than feeding it in raw. pcg's `oneseq` engines set state directly, so nearby
/// seeds stay correlated for the first few draws - seeds 1..40 all produced an even first output,
/// which biased Algorithm R's very first keep/replace decision the same way every time.
data(place).rng.seed(mixSeed(seed, 0));

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.

Every partial aggregate state seeds its reservoir PRNG from the exact same stream here, so parallel / distributed aggregation still breaks the advertised "uniform sample of the input stream" contract even though merge itself is now fixed.

Concrete trace: take sample_cap = 2 and two partial states that each see three rows, [a1, a2, a3] and [b1, b2, b3]. Both local reservoirs call genRandom(3) from the same initial rng state, so they always drop the same local position. The event "a1 survives local sampling" and "b1 survives local sampling" therefore has probability 2/3 jointly here, not (2/3)^2. After merge, the final subset {a1, b1} then appears with probability 3/5 * 2/3 * 1/4 = 1/10, but a true size-2 reservoir sample of six rows should give 1 / C(6, 2) = 1/15.

So the current code is still unbiased only in the single-state case. Each partial state needs an independent reservoir stream (or the reservoir needs a mergeable priority-sampling scheme) before the sample is actually uniform under normal many-state aggregation.

The previous commit dropped the `const UInt64 d = dim;` alias in
`HierarchicalKMeansData::merge` so the function could use the `UInt32`
member directly. That turned `static_cast<UInt32>(d)`, which used to
narrow from `UInt64`, into a cast of a value that is already `UInt32`,
and `readability-redundant-casting` rejects it:

  AggregateFunctionHierarchicalKMeans.cpp:871:55: error: redundant explicit
  casting to the same type 'UInt32' (aka 'unsigned int') as the
  sub-expression, remove this casting
  [readability-redundant-casting,-warnings-as-errors]

Drop both casts. No behaviour change.

Verified with `clang-tidy-21 -p build` on both files of the pull request:
no diagnostics. Re-inserting one cast reproduces the error above, so the
clean run is not clang-tidy skipping the file.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=112309&sha=51be328f3edf98375c21d43eb2a1562379bc9219&name_0=PR
Related: ClickHouse#112309

Co-Authored-By: Claude Opus 5 <[email protected]>
@shankar-iyer
shankar-iyer added this pull request to the merge queue Sep 9, 2026
Merged via the queue into ClickHouse:master with commit c08a0f3 Sep 9, 2026
175 checks passed
@shankar-iyer
shankar-iyer deleted the add_kmeans_and_assign_centroid branch September 9, 2026 11:43
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 9, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

@shankar-iyer @rschu1ze — ClickGap found the following in this PR:

Close anything that's wrong or already addressed.

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

Labels

comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). pr-experimental Experimental Feature 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.

5 participants