Skip to content

Support 2^N * 9 dimensions in randomHadamardTransform without padding - #110910

Merged
alexey-milovidov merged 7 commits into
masterfrom
hadamard-1152-dht
Jul 19, 2026
Merged

alexey-milovidov merged 7 commits into
masterfrom
hadamard-1152-dht

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 17, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not For Changelog

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

randomHadamardTransform now transforms vectors whose length is 2^N * 9 (for example 1152 = 128 * 9, common in some embedding models) exactly, without zero-padding to the next power of two, so the output keeps the input dimension.


randomHadamardTransform already avoids zero-padding for lengths 2^k * m with m in {12, 20} by applying the exact Kronecker product H_(2^k) (x) H_m, where H_m is a Paley +/-1 Hadamard matrix. That does not cover the common 2^N * 9 family (e.g. 1152 = 128 * 9), because order 9 has no +/-1 Hadamard matrix — those exist only for orders 1, 2, and multiples of 4 — so such inputs were padded (1152 -> 2048).

This PR adds an exact, non-padding path for length = 2^k * 9. The order-9 small factor is a real orthogonal Discrete Hartley Transform matrix C_9 with entries cas(2*pi*i*j/9) = cos(...) + sin(...). The DHT matrix is real, symmetric, and self-inverse up to scale (C^T C = 9 * I), so it is orthogonal up to the 1/sqrt(m) factor — exactly the unnormalized +/-1 Hadamard convention already used here, so the existing final 1/sqrt(k) scaling makes the whole transform norm-preserving with no extra bookkeeping. It is applied as the exact Kronecker product H_(2^k) (x) C_9: a dense float mat-vec per 9-element block followed by the cross-block fast Walsh-Hadamard transform.

Notes:

  • The C_9 block uses float multiplies (a +/-1 sign-flip kernel is impossible at order 9) and a scalar cross-block FWHT (the NEON block kernel needs the lane count to be a multiple of 4, which 9 is not), so the DHT path is kernel-independent — verified bit-for-bit between the scalar and NEON kernels.
  • The exact per-coordinate output was cross-checked against an independent NumPy model (splitmix64 signs, DHT-9, cross-block FWHT, 1/sqrt(k) scale).

New test: 04512_random_hadamard_transform_hartley_9.

Version info

  • Merged into: 26.7.1.1193 (included in 26.7 and later)

randomHadamardTransform already avoids zero-padding for lengths 2^k * m with
m in {12, 20} by applying the exact Kronecker product H_(2^k) (x) H_m, where
H_m is a Paley +-1 Hadamard matrix. That does not cover the common 2^N * 9
family (e.g. 1152 = 128 * 9, used by some embedding models), because order 9
has no +-1 Hadamard matrix -- those exist only for orders 1, 2, and multiples
of 4 -- so such inputs were padded (1152 -> 2048).

Add an exact, non-padding path for length = 2^k * 9. The order-9 small factor
is a real orthogonal Discrete Hartley Transform matrix C_9 with entries
cas(2*pi*i*j/9) = cos(...) + sin(...). The DHT matrix is real, symmetric, and
self-inverse up to scale (C^T C = 9 * I), so it is orthogonal up to the
1/sqrt(m) factor -- exactly the unnormalized +-1 Hadamard convention already
used here, so the final 1/sqrt(k) scaling makes the whole transform
norm-preserving with no extra bookkeeping. It is applied as the exact Kronecker
product H_(2^k) (x) C_9: a dense float mat-vec per 9-element block followed by
the cross-block fast Walsh-Hadamard transform. This keeps the input dimension
instead of growing to the next power of two.

The C_9 block uses float multiplies (a +-1 sign-flip kernel is impossible at
order 9) and a scalar cross-block FWHT (the NEON block kernel needs the lane
count to be a multiple of 4, which 9 is not), so the DHT path is
kernel-independent -- verified bit-for-bit between the scalar and NEON kernels.

The exact per-coordinate output was cross-checked against an independent NumPy
model (splitmix64 signs, DHT-9, cross-block FWHT, 1/sqrt(k) scale).

Add test 04512_random_hadamard_transform_hartley_9 and update the docs.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 17, 2026, 7:33 PM

# Conflicts:
#	src/Functions/randomHadamardTransform.cpp
@clickhouse-gh

clickhouse-gh Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f1be4f1]

Summary: ✅


AI Review

Summary

This PR adds an exact order-9 Hartley path for randomHadamardTransform, keeps the vector-search codecs on their old padded projection via an explicit wrapper, and adds focused regression coverage for both the codec guard and the truncated-SRHT fallback. The new math path and the codec compatibility guard look internally consistent, but the SQL function change is still a documented backward-incompatible contract change for 2^k * 9 inputs.

PR Metadata
  • The Changelog category should be Backward Incompatible Change, not Improvement. On master, every non-{12,20} exact length was explicitly documented and implemented as zero-padded; this PR changes randomHadamardTransform on 2^k * 9 inputs to return the input length for the full transform and to throw ARGUMENT_OUT_OF_BOUND for output_dims > length that previously worked against the padded length. The current Changelog entry also omits the old behavior and any migration guidance.
    Replacement category: Backward Incompatible Change
    Replacement entry: randomHadamardTransform now applies an exact order-9 Hartley transform for 2^N * 9 vectors instead of zero-padding them to the next power of two. Full transforms now return the input length, and calls that previously requested output_dims above that input length for these dimensions now throw ARGUMENT_OUT_OF_BOUND.
Findings

❌ Blockers

  • [src/Common/HadamardTransform.h:112-123, src/Functions/randomHadamardTransform.cpp:194-215] [dismissed by author -- https://github.com/Support 2^N * 9 dimensions in randomHadamardTransform without padding #110910#discussion_r3607209561] Adding m = 9 to kroneckerFactorFor changes the existing user-visible contract for randomHadamardTransform, not just an internal optimization. The pre-PR implementation and docs explicitly said every non-{12,20} exact length was zero-padded, so 2^k * 9 queries previously returned the padded power-of-two length and accepted output_dims up to that padded size. After this change, the same inputs return length for the full transform or throw once output_dims > length. That can silently change result shape or start failing existing queries/views on upgrade. Suggested fix: keep the old padded behavior by default and add the exact Hartley path behind an explicit opt-in / compatibility setting, or otherwise preserve the padded contract for existing 2^k * 9 callers.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Preserve the old padded contract for 2^k * 9 inputs by default, or gate the new exact Hartley behavior behind an opt-in / compatibility mechanism.
  • If the behavior change remains intentional, update the PR metadata to Backward Incompatible Change and spell out the old/new output length and output_dims semantics.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 18, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The two red stress checks are both unrelated to this PR (which only touches randomHadamardTransform, HadamardTransform.h, VectorQuantizer.cpp, docs, and one stateless test — no query-plan / serialization code):

  • Stress test (arm_debug) — Hung check failed, possible deadlock found: the server hit MEMORY_LIMIT_EXCEEDED and stopped responding. Known flaky, tracked in Hung check failed, possible deadlock found #107941.
  • Stress test (arm_release) — Logical error: ReadFromMergeTree step is expected to be created by readFromParts: this fires in ReadFromMergeTree::deserialize (src/Processors/QueryPlan/ReadFromMergeTree.cpp:5468), part of the multistage distributed queries feature (Multi-stage distributed queries #106020, which has a revert/re-land history). It is a distributed query-plan deserialization path this PR does not touch. It is a first-ever occurrence in 60 days of CIDB history and has no tracking issue yet.

@groeneai, could you investigate the ReadFromMergeTree step is expected to be created by readFromParts logical error and open a tracking issue / fix in a separate PR? Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110910&sha=51e6b0ddc85e666b2fcfacc3238134aeba30e55c&name_0=PR&name_1=Stress%20test%20%28arm_release%29

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Tracking issue: #110927.

CIDB confirms your read: this signature has exactly one occurrence in 60 days, only on this branch's Stress test (arm_release) run (commit 51e6b0d), never on master, and unrelated to the PR diff.

Root cause: in ReadFromMergeTree::deserialize the distributed_read_bucket_count > 0 branch (ReadFromMergeTree.cpp:5468) dynamic_casts the readFromParts result to ReadFromMergeTree * and asserts it is non-null. But MergeTreeDataSelectExecutor::readFromParts returns a null step for an empty non-stream read (parts->empty() && !query_info.isStream(), MergeTreeDataSelectExecutor.cpp:1833). The bucketed plan is serialized on the coordinator while parts exist, so the bucket count is written into the step; by the time a worker deserializes it, that worker's local snapshot can be empty (parts merged/dropped under the stress churn) and readFromParts returns {}, so the assertion fires instead of producing a valid empty read.

Fix direction: treat the null step in the bucketed branch as a valid empty read (return an empty step carrying the serialized header, like the existing ctx.skipping short-circuit) rather than a logical error. A fix PR will follow on the issue.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix PR: #110929 (Closes #110927).

One refinement from the initial direction above: returning a ReadNothingStep (or any short-circuit that skips the read entirely) would bypass the divergence check in initializePipeline, so a worker whose snapshot is empty because a coordinator-selected part diverged would silently emit 0 rows instead of the designed retry. Instead the PR builds a real empty ReadFromMergeTree step for the bucketed read, so initializePipeline still decides at runtime: NullSource for a genuinely empty bucket, retryable NO_SUCH_DATA_PART on divergence. Reproduced both directions with a new failpoint.

Comment thread src/Common/VectorQuantizer.cpp Resolved
… a regression test

The AI review (clickhouse-gh bot, "Request changes") asked for a focused
regression proving the `Quantized(..., 1152)` codec keeps its old projection
now that the shared `HadamardTransform::kroneckerFactorFor` helper knows the
order-9 Hartley factor. `VectorQuantizer.cpp`'s `hadamardFactorFor` wrapper
deliberately filters that factor down to `SmallFactorKind::Hadamard`, so a
1152 = 128 * 9 vector stays on the "zero-pad to 2048" projection instead of
the exact order-9 Hartley path used by `randomHadamardTransform`. Switching it
would silently rewrite every already-stored `Quantized(..., 1152)` code.

The existing codec coverage (`02354_vector_search_quantize_codec_kronecker`,
a 96 = 8 * 12 exact-Hadamard case) cannot detect this: a plain encode/query
round-trip agrees whether both sides pad or both take Hartley. The new test
`02354_vector_search_quantize_codec_hartley_guard` instead pins an invariant
that distinguishes the two paths. For the padded path, encoding a 1152-dim
vector produces exactly the same structured projection (same seed, same
working dimension 2048, same FWHT) as encoding that vector zero-padded to
2048 dims, so the 1152 / 8 = 144 packed `rabitq` sign bytes must be
byte-identical to the leading 144 sign bytes of the 2048-dim code. The exact
Hartley path would produce different signs and break this equality. The
comparison is between two codes produced by the same binary, so it is robust
to per-platform floating-point differences (no absolute byte values pinned).

Verified end to end: the test passes on the current code; patching
`hadamardFactorFor` to return `kroneckerFactorFor` directly (the exact
refactor the guard prevents) makes the test fail, and the codec's Hadamard-only
kernel then throws `INCORRECT_DATA` on the order-9 factor.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 3 commits July 18, 2026 16:18
The `signs_match_padded_2048` check read `vec.quantized` through a
`(SELECT id, vec FROM ...)` subquery. The `.quantized` subcolumn does not
survive that subquery boundary under the old analyzer, so the query failed
with `Unknown column: vec.quantized` (`UNKNOWN_IDENTIFIER`), exactly as the
`code_length_1152` query on the line above (which reads the subcolumn directly
from the table) does not.

Read `vec.quantized` directly from each table and compare the per-id codes with
an `ALL INNER JOIN` plus `min`, which also removes the dependence on
`groupArray` preserving the subquery ordering. The invariant is unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The exact order-9 Hartley small factor `C_9` is orthogonal, so the full
transform stays norm-preserving, but its rows do not have the uniform leverage
of a `+-1` Hadamard matrix. A truncated prefix of `C_9` rows is therefore a
position-biased projection instead of a valid Johnson-Lindenstrauss / SRHT one:
for `length = 18`, `output_dims = 2` a one-hot input on lane `1` keeps squared
norm `~1.49` while lane `8` keeps only `~0.51`, and the diagonal sign only flips
signs so it cannot average that out. The `1/sqrt(output_dims)` scaling that the
function documents as norm-preserving-in-expectation only holds for the flat
`+-1` factors.

So the exact `C_9` path is now kept only for the full transform; a genuine
truncation (`output_dims < length`) of the `2^k * 9` family falls back to the
zero-padded power-of-two FWHT, whose `+-1` rows do have uniform leverage. The
`+-1` Hadamard Kronecker factors (`m` in {12, 20}) are unaffected, and an
`output_dims` above the input length still throws `ARGUMENT_OUT_OF_BOUND` in
every case (consistent with the exact `2^k * 12` and `2^k * 20` paths).

The docs (embedded and `array-functions.mdx`) are updated to match, and a new
test `04611_random_hadamard_transform_hartley_truncation` pins the invariant:
every one-hot basis vector of a length-18 input, projected to `output_dims = 2`,
has the same squared norm.

Addresses the review at `randomHadamardTransform.cpp:219`.

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

clickhouse-gh Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.10% 86.10% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 78.20% 78.20% +0.00%

Changed lines: Changed C/C++ lines covered: 95/95 (100.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR only touches randomHadamardTransform and the vector-search quantization codec (plus docs and tests); none of the flagged ClickBench queries (Q4, Q15, Q30, Q31) execute that code, so neither the ~-20% swings on Q4/Q15 nor the ~+16-17% swings on Q30/Q31 can be a real effect of this change. All four deltas sit within master's current variance band and were correctly suppressed as no_change / not_sure. No performance action is needed for this PR.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 268 315 +17.3% <0.0001 The +17.3% delta is off-path: nothing in Q30 runs the randomHadamardTransform / quantization codec changed here. It falls within master's variance band and stays not_sure.
⚠️ 31 not_sure 345 400 +15.9% <0.0001 Q31 exercises none of the changed code; the +15.9% delta is within the baseline envelope and correctly left as not_sure rather than a regression.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 935ce18f-769e-4724-8b97-629026889d16
  • MIRAI run: e043f4d8-03ef-4fda-b61f-d847bb62c3c1
  • PR check IDs:
    • clickbench_277989_1784427574
    • clickbench_277995_1784427574
    • clickbench_278006_1784427573
    • tpch_adapted_1_official_278012_1784427573
    • tpch_adapted_1_official_278023_1784427573
    • tpch_adapted_1_official_278043_1784427573

@alexey-milovidov

Copy link
Copy Markdown
Member Author

This function was added in 26.7, so no problem with compatibility.

@alexey-milovidov alexey-milovidov self-assigned this Jul 19, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

Fine.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 19, 2026
Merged via the queue into master with commit 78af896 Jul 19, 2026
351 of 352 checks passed
@alexey-milovidov
alexey-milovidov deleted the hadamard-1152-dht branch July 19, 2026 16:47
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 19, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Support 2^N * 9 dimensions in randomHadamardTransform without padding

This branch was successfully deployed

1 active deployment
staging - docs — f1be4f15 Deployed Jul 18, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

3 participants