Repository navigation
Portable SIMD for hasAll and hasAny on integer arrays - #123420
Algunenano merged 9 commits into
Conversation
The AVX2/SSE kernels `sliceHasImplAnyAllImplInt8/16/32/64` are `NO_INLINE` and take the null maps as runtime pointers. Before ClickHouse#116239 they were only called with `nullptr` null maps, and the ThinLTO build folded the null-map handling away. Since ClickHouse#116239 Nullable arrays reach the same instantiation with real null maps, so the null-mask loads and masking stay in the inner loop for every array, and `hasAll` on non-Nullable integer arrays became 16-60% slower in the amd performance tests. Add a `with_null_maps` template parameter to the kernels and dispatch to the `false` instantiation when both null maps are absent, so the null-map-free kernel no longer depends on interprocedural constant propagation. Nullable arrays keep using the current code. The analysis and patch come from ClickHouse#123380. Closes ClickHouse#123380 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review of the same tree (0 blocker, 0 major).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-11:20261002-051100 |
|
Workflow [PR], commit [7ba2505] Summary: ✅
AI ReviewSummaryThis PR replaces the x86-only integer Findings
Performance & Safety
Final Verdict
|
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes13 object files changed (+219.46 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units51 translation units recompiled, 352 s compile time in total, 51 of them have a recent master baseline. |
Algunenano
left a comment
There was a problem hiding this comment.
I don't think this x86 branches should exist to begin with. We can use a generic kernel instead which will both be faster and benefit other architectures. I'll try to push it here
|
Agreed, a generic kernel is the better shape. I'll leave the branch to you and won't push to it. Two things that may help:
|
The AVX2/SSE kernels only covered `hasAll` on x86. They are replaced with code written with clang vector extensions, which compiles to SSE/AVX2 on x86 and to NEON on AArch64: - `sliceContains` searches one value in blocks of 128 bytes with one test per block. It serves `hasAny` and `hasAll` for all integer types. - `sliceHasAllBytes` keeps the SSE algorithm for `hasAll` on 1-byte elements: 16 values against all 16 rotations of 16 elements of `first`. Null elements of `first` are replaced with a non-null element of `first` instead of masking each rotation. - `hasNull` ORs the whole null map instead of a scalar loop with an early exit, which took a fifth of `hasAll` on `Nullable` arrays without nulls. Compared with the previous kernels, `has_all.xml` is up to 1.77x faster with no regressions, `hasAny` is 5x to 15x faster, and `hasAll` on `Nullable` arrays is up to 1.69x faster. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
I pushed a commit on top of this branch (422ca55) that replaces the AVX2/SSE What changed in
Local results on x86 (Ryzen 9 7950X3D,
Correctness: a differential test of the kernels against a scalar reference under ASan/UBSan (2 million random cases, all 8 integer types, The NEON code has been checked only in the generated assembly so far, not run. @groeneai could you review the change and run the tests and performance comparisons on your machine as well, including on ARM if you have one? Please also update the PR description if you agree with the approach, since it no longer describes the change. Additional performance cases<test>
<substitutions>
<substitution>
<name>array_type</name>
<values>
<value>Int8</value>
<value>Int16</value>
<value>Int32</value>
<value>Int64</value>
</values>
</substitution>
</substitutions>
<!-- `subset` is drawn independently of `set`, so most values are missing. -->
<create_query>CREATE TABLE missing_small_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>CREATE TABLE missing_medium_{array_type} (set Array({array_type}), subset Array({array_type})) ENGINE = MergeTree ORDER BY tuple()</create_query>
<!-- Nullable arrays where one value in 64 is null; `subset` is drawn from `set`, so all values are found. -->
<create_query>CREATE TABLE nullable_found_small_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
<create_query>CREATE TABLE nullable_found_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
<!-- Nullable arrays with nulls only in `set`; `subset` is drawn independently, so most values are missing. -->
<create_query>CREATE TABLE nullable_missing_medium_{array_type} (set Array(Nullable({array_type})), subset Array(Nullable({array_type}))) ENGINE = MergeTree ORDER BY tuple()</create_query>
<fill_query>INSERT INTO missing_small_{array_type} SELECT groupArraySample(5000)(rand64(1)), groupArraySample(500)(rand64(2)) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
<fill_query>INSERT INTO missing_medium_{array_type} SELECT groupArraySample(50000)(rand64(1)), groupArraySample(5000)(rand64(2)) FROM numbers(25000000) GROUP BY number % 50000</fill_query>
<fill_query>INSERT INTO nullable_found_small_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(500)(rand64(1))) FROM numbers(10000000) GROUP BY number % 5000</fill_query>
<fill_query>INSERT INTO nullable_found_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(50000)(rand64(1))), arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(5000)(rand64(1))) FROM numbers(25000000) GROUP BY number % 50000</fill_query>
<fill_query>INSERT INTO nullable_missing_medium_{array_type} SELECT arrayMap(v -> if(v % 64 = 0, NULL, v), groupArraySample(50000)(rand64(1))), arrayMap(v -> toNullable(v), groupArraySample(5000)(rand64(2))) FROM numbers(25000000) GROUP BY number % 50000</fill_query>
<query>SELECT hasAll(set, subset) FROM missing_small_{array_type} FORMAT Null</query>
<query>SELECT hasAll(set, subset) FROM missing_medium_{array_type} FORMAT Null</query>
<query>SELECT hasAny(set, subset) FROM missing_small_{array_type} FORMAT Null</query>
<query>SELECT hasAny(set, subset) FROM missing_medium_{array_type} FORMAT Null</query>
<query>SELECT hasAll(set, subset) FROM nullable_found_small_{array_type} FORMAT Null</query>
<query>SELECT hasAll(set, subset) FROM nullable_found_medium_{array_type} FORMAT Null</query>
<query>SELECT hasAll(set, subset) FROM nullable_missing_medium_{array_type} FORMAT Null</query>
<query>SELECT hasAny(set, subset) FROM nullable_missing_medium_{array_type} FORMAT Null</query>
<drop_query>DROP TABLE IF EXISTS missing_small_{array_type}</drop_query>
<drop_query>DROP TABLE IF EXISTS missing_medium_{array_type}</drop_query>
<drop_query>DROP TABLE IF EXISTS nullable_found_small_{array_type}</drop_query>
<drop_query>DROP TABLE IF EXISTS nullable_found_medium_{array_type}</drop_query>
<drop_query>DROP TABLE IF EXISTS nullable_missing_medium_{array_type}</drop_query>
</test> |
|
Measurements of 422ca55 on ARM (Neoverse-V3, 48 cores, clang 22.1.8, RelWithDebInfo), against the previous head of this PR (860e473), which runs the scalar loop on ARM. Both servers were pinned to the same cores; All 44 queries are faster, from 1.08x to 9.87x, with p ≤ 2e-6 for each. The related stateless tests pass (3 runs each), and the randomized
Additional cases (the XML from my previous comment):
The smallest gains are on |
The 16 comparison masks were folded into one accumulator with 16 dependent unsigned maximums. AArch64 kept that chain in order, so each block of 16 elements waited for 16 `umax` latencies. Combining them pairwise makes the chain 4 levels deep; the compiler turns the tree into `orr` and keeps a single `umax` into the accumulator. On Neoverse-V3, 1-byte `hasAll` is 1.24x to 2.26x faster. On Zen 4 it is unchanged, because x86 already split the chain in two. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 I pushed 4f4be82 on top of the previous commit. In the 1-byte Results with
x86 is essentially unchanged because it already split the chain in two. The two small x86 differences are within what I saw between builds that differ only in code layout: in the same run, Against #116224 on ARM, 1-byte Both the randomized I also tried sending 1-byte |
…arrays `hasNull` ORed the whole null map, so `hasAny` became linear in the array length even when both arrays start with a null and the result is already known. It now tests 64 bytes at a time with whole-vector ORs and returns at the first block that has a null, which keeps the loop vectorized. The new test checks `hasAll` and `hasAny` on Int8, UInt8, Int16, Int32, Int64 and UInt64 arrays, `Nullable` and not, against a reference that checks each element with `has`. Lengths cross the 16-element groups and 128-byte blocks of the vectorized search, and nulls are placed in neither, either or both arrays, including a first array of only nulls. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 I pushed dd49f49, which addresses both points from the AI review.
Coverage. The new test
The test passes 3 times in a row under the runner's random settings. The build before this PR's changes gives byte-identical output. |
|
I read through the header and agree with the approach; I have no code comments. I measured 422ca55, before your two later commits. Setup: Intel Xeon 6975P-C, ThinLTO release builds, four servers up at the same time on identical data: master (bbba881), the previous head (860e473), and 422ca55 twice for an A/A floor. 7 rounds, Performance:
Correctness, all on 422ca55:
I have no ARM machine, so no ARM timings from me. The description you wrote matches the change, so I left it as is. |
|
Re-measured on dd49f49 (15 rounds; the A/A difference was within 3% on every query this time): That table has 50k rows of 500-element The kernel harness (x86-64-v3, ASan/UBSan, AArch64 under QEMU) and the |
Ergus
left a comment
There was a problem hiding this comment.
Could we add a performance test for the new fast path?
The reported speedup numbers in a comment are not committed and has_all.xml only covers non-Nullable hasAll, so a potential later regression in the hasAny or null-map paths could pass unnoticed.
| countIf(hasAny(x, y)) AS any_true, countIf(hasAny(x, y) != arrayExists(v -> has(x, v), y)) AS any_mismatches | ||
| FROM (SELECT CAST(arrayMap(v -> assumeNotNull(v), a), 'Array(Int8)') AS x, CAST(arrayMap(v -> assumeNotNull(v), b), 'Array(Int8)') AS y FROM arrays); | ||
|
|
||
| SELECT 'Int8', 'mixed', count(), |
There was a problem hiding this comment.
I think that this mixed test does not test really mixed paths cause FunctionArrayHasAllAny casts both arguments to their least common supertype. So Array(Nullable(Int8)) with Array(Int8) reaches the kernel with a null map on both sides.
So "Mixed" reruns the same code path as the "Nullable" rows, with no nulls in the second array, which null_mode 0/1 already covers.
There was a problem hiding this comment.
Right. executeImpl casts both arguments to their least common supertype (hasAllAny.h#L66-L71), and it is the only caller of the hasAll/hasAny kernels, so no query reaches them with a null map on one side only. The mixed rows add only that cast on top of the Nullable path. Without them the remaining 12 rows still match the reference on dd49f49 and on the previous head, and dropping them is part of what I asked about in #123420 (comment).
`has_all.xml` only covers `hasAll` on arrays without null maps. The new test measures `hasAny` with values that are never found (disjoint value ranges, so Int8 and Int16 scan the whole first array too), and `hasAll` and `hasAny` on `Nullable` arrays with one null in 64. Table sizes keep every query under the 2 s single-run limit of the performance check on the reference build as well. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`FunctionArrayHasAllAny` casts both arguments to their least common supertype, so a `Nullable` first array with a non-`Nullable` second array reaches the kernel with null maps on both sides: the mixed rows ran the same path as the `Nullable` rows. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@Ergus agreed,
I ran it with @Algunenano the branch is yours: should I push this as a test-only commit, together with dropping the mixed rows of 05318 (see Ergus's inline comment), or would you rather add it yourself?
|
|
Checked locally with clang 22:
If you want, I can push it on top of dd49f49, together with the perf test from my previous comment. Patchdiff --git a/src/Functions/GatherUtils/sliceHasImplAnyAll.h b/src/Functions/GatherUtils/sliceHasImplAnyAll.h
index fc0ff009c9e3c..918db01449400 100644
--- a/src/Functions/GatherUtils/sliceHasImplAnyAll.h
+++ b/src/Functions/GatherUtils/sliceHasImplAnyAll.h
@@ -37,6 +37,21 @@ ALWAYS_INLINE bool allLanesSet(Mask mask)
return __builtin_reduce_and(mask) == ~0ULL;
}
+/// All ones in the lanes that are not zero. Converting to `bool` lanes is `!= 0`; a comparison would depend on
+/// `-faltivec-src-compat` on PowerPC.
+template <typename Vector>
+ALWAYS_INLINE Vector nonZeroLanes(Vector vector)
+{
+ using Lanes = bool __attribute__((ext_vector_type(__builtin_vectorelements(Vector))));
+ return -__builtin_convertvector(__builtin_convertvector(vector, Lanes), Vector);
+}
+
+template <typename Vector>
+ALWAYS_INLINE Vector equalLanes(Vector lhs, Vector rhs)
+{
+ return ~nonZeroLanes(lhs ^ rhs);
+}
+
inline ALWAYS_INLINE bool hasNull(const UInt8 * null_map, size_t null_map_size)
{
if (null_map == nullptr)
@@ -88,7 +103,7 @@ ALWAYS_INLINE bool sliceContains(const NumericArraySlice<T> & slice, const UInt8
{
Vector elements;
memcpy(&elements, slice.data + begin + offset, sizeof(elements));
- auto equal = elements == needle;
+ auto equal = equalLanes(elements, needle);
if constexpr (has_null_map)
{
NullBytes nulls;
@@ -183,7 +198,8 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
{
NullBytes nulls;
memcpy(&nulls, first_null_map + begin, sizeof(nulls));
- elements = nulls == 0 ? elements : fillers;
+ const auto null_lanes = reinterpret_cast<Vector>(nonZeroLanes(nulls));
+ elements = (elements & ~null_lanes) | (fillers & null_lanes);
}
/// The comparison masks are combined with an unsigned maximum, which is an OR for lanes that are 0 or 0xFF. With
/// `|`, LLVM merged the 16 masks into booleans and rebuilt the bytes from them in every iteration (`psllw` and
@@ -192,7 +208,7 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
Bytes hits[lanes];
[&]<size_t... shift>(std::index_sequence<shift...>) ALWAYS_INLINE
{
- ((hits[shift] = reinterpret_cast<Bytes>(values == rotateLanes<shift>(elements, lane_indices))), ...);
+ ((hits[shift] = reinterpret_cast<Bytes>(equalLanes(values, rotateLanes<shift>(elements, lane_indices)))), ...);
}(lane_indices);
/// Combined as a tree: a chain of 16 dependent maximums limited AArch64 to one per `umax` latency.
for (size_t width = lanes / 2; width > 0; width /= 2)
@@ -214,7 +230,7 @@ bool sliceHasAllBytes(const NumericArraySlice<T> & first, const NumericArraySlic
{
NullBytes nulls;
memcpy(&nulls, second_null_map + begin, sizeof(nulls));
- found = reinterpret_cast<SearchMask<16>>(nulls != 0);
+ found = reinterpret_cast<SearchMask<16>>(nonZeroLanes(nulls));
}
size_t i = 0; |
|
@groeneai Yes please, push the tests and the fixx for ppc |
On PowerPC the result type of a vector comparison depends on `-faltivec-src-compat`, which made the ppc64le build fail with `-Wdeprecated-altivec-src-compat` at the four comparisons in `sliceHasImplAnyAll.h`. Each one is replaced by a conversion to `bool` lanes, which is the same `!= 0` per lane and has a fixed type, as in 22a9797 and 6b892bd. The generated code is unchanged on x86-64 and AArch64. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…or search A null map can hold any nonzero value for NULL. Without short-circuit evaluation, `if(cond, NULL, x)` uses its `UInt8` condition as the null map, so `arrayMap(i -> if(i % 3, NULL, i), ...)` has null bytes of 2. The vector search subtracted one from each null byte to build a mask, which left the lowest bits set for a byte of 2, so `hasAny` and `hasAll` found a value that is only present as NULL. For lanes wider than one byte the subtraction is kept, and the test of each block ignores the low byte of every lane, the only one a null lane can keep. On x86-64-v3 this adds one broadcast outside the loop, and a benchmark of full scans with a null map is unchanged for every width. One-byte lanes have no other byte, so they are compared with zero, which costs the same as the subtraction there. Converting the null bytes to `bool` first was correct but made x86 narrow the 8-byte comparison results again, 22-42% slower in that benchmark for 2-, 4- and 8-byte lanes. `05318` gets the `if` case for the six integer types; before this change it returns 42 wrong results out of 128 for each of them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1565ac9 to
2bb342d
Compare
|
Pushed:
SELECT hasAny(arrayMap(x -> if(x % 3, NULL, toInt64(x)), arrayMap(x -> toUInt8(x), materialize(range(64)))), [toInt64(2)])
SETTINGS short_circuit_function_evaluation = 'disable'For lanes wider than one byte I kept the subtraction, and the per-block test now ignores the low byte of each lane. Their inner loop is unchanged; on x86-64-v3 the only addition is one broadcast outside the loop. 1-byte lanes compare with zero instead. Converting the null bytes to
|
CI finish ledger - 2bb342dEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20261010-003008 |
…nels-without-null-maps
| } | ||
| } | ||
| } | ||
| const bool has = sliceContains<has_first_null_map>(first, first_null_map, second.data[i]); |
There was a problem hiding this comment.
This multi-byte hasAll path now probes first separately for every element of second, so the old batched-needle behavior disappears for 16-bit arrays. In the PR's own perf discussion, this is still the one reproducible regression: nullable_found_medium_Int16 stays 11%-15% slower than both master and the previous head (543 ms vs 482/484 ms; see #123420 (comment)).
For a Performance Improvement PR that is still an unresolved contract violation, not just noise. Please either restore a grouped hasAll path for 16-bit integer arrays here, or rerun the benchmark on the current head and narrow the PR's performance claims if this slowdown is an accepted tradeoff.
Algunenano
left a comment
There was a problem hiding this comment.
Even if some corner case is slightly slower we don't mind. The net result is extremely positive and removes intrinsics
Closes: #123380
Related: #116239
Related: #116224
Since #116239,
hasAllon non-Nullableinteger arrays was 16-60% slower on x86, because the AVX2/SSE kernels kept the null-map handling in their inner loops.This PR replaces those x86-only kernels with code written with clang vector extensions, which compiles to SSE/AVX2 on x86 and NEON on AArch64:
hasAllandhasAnyon all integer types search each value in blocks of 128 bytes with one mask test per block.hasAllon 1-byte elements compares 16 values against the 16 rotations of 16 elements, as the previous SSE kernel did, and exits when all 16 are found.Measured with
perf.pyagainst the previous kernels on Zen 4, and against the previous scalar code on Neoverse-V3, withhas_all.xmland extra cases for missing values,Nullablearrays andhasAny:has_all.xmlup to 1.77x faster,hasAny5x to 15x faster,hasAllonNullablearrays up to 1.69x faster, no query slower.hasAllup to 2.26x faster again after the latest commit.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
hasAllandhasAnyon integer arrays use SIMD on both x86 and ARM, includingNullablearrays andhasAny, which previously used a scalar loop.hasAnyis up to 15x faster, andhasAllbecomes several times faster on ARM.Workflow [PR]
Sync PR [sync-upstream/pr/123420]
Version info
26.10.1.2259-master(included in26.10and later)