Skip to content

Change default x86 build target from x86-64-v2 (SSE4.2) to x86-64-v3 (AVX2) - #90043

Merged
Algunenano merged 117 commits into
ClickHouse:masterfrom
Algunenano:x86v3
May 13, 2026
Merged

Algunenano merged 117 commits into
ClickHouse:masterfrom
Algunenano:x86v3

Conversation

@Algunenano

@Algunenano Algunenano commented Nov 14, 2025 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Backward Incompatible Change

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

This change was reverted

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

The default ClickHouse binary for x86 Linux now requires AVX2 (x86-64-v3). CPUs without AVX2 support will fail with an "Illegal instruction" error. For systems without AVX2, use the compatibility build (amd64compat) available at https://builds.clickhouse.com/master/amd64compat/clickhouse. The install script (curl https://clickhouse.com/ | sh) automatically detects CPU capabilities and downloads the appropriate build.

Closes #99172

Version info

  • Merged into: 26.5.1.594

@Algunenano Algunenano self-assigned this Nov 14, 2025
@clickhouse-gh

clickhouse-gh Bot commented Nov 14, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [66f976d]

Summary: ❌

job_name test_name status info comment
Performance Comparison (amd_release, master_head, 4/6) FAIL
agg_functions_min_max_any #79::old FAIL query history IGNORED
agg_functions_min_max_any #79::new FAIL query history IGNORED
avg_serialization #0::old FAIL query history IGNORED
avg_serialization #0::new FAIL query history IGNORED
bigint_formatting #6::old FAIL query history IGNORED
bigint_formatting #6::new FAIL query history IGNORED
join_used_flags #0::old FAIL query history IGNORED
join_used_flags #0::new FAIL query history IGNORED
random_string #3::old FAIL query history IGNORED
random_string #3::new FAIL query history IGNORED
8 more test cases not shown

AI Review

Summary

This PR changes the default x86 Linux target from x86-64-v2 to x86-64-v3 (AVX2) and removes related v2/v3 runtime-dispatch paths across the touched performance code. The live issue is in PR metadata: the changelog classification still does not match the backward-incompatible runtime requirement change.

PR Metadata

⚠️ Changelog category is currently Performance Improvement, but this PR changes the minimum CPU requirements for default amd64 binaries. That is a backward-incompatible user-facing change and should be categorized accordingly.

⚠️ Changelog entry still contains a TODO line (TODO: Change to Breaking Change after the CI is ok), which is not acceptable final changelog text.

Exact replacement:

### Changelog category (leave one):
- Backward Incompatible Change

### Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Default Linux `amd64` binaries now require `x86-64-v3` (`AVX2`+). Hosts without `AVX2` should use the `amd64compat` build; the installer auto-detects CPU capabilities and selects the compatibility artifact when needed.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Change Changelog category to Backward Incompatible Change.
  2. Remove the TODO and keep a final user-facing Changelog entry.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Nov 14, 2025
@Algunenano

Copy link
Copy Markdown
Member Author

It shows both improvements and regressions in some cases. I'll keep it open to review it in depth and see if we can introduce dynamic dispatching where it benefits

@Algunenano

Copy link
Copy Markdown
Member Author

Merged with master after a few of the improvements have been introduced via dynamic dispatch. I'll keep investigating other speed ups

@Algunenano

Algunenano commented Dec 2, 2025 •

Copy link
Copy Markdown
Member Author

Next to investigate is memcpy: We use our own, which is optimized for SSE4.2 and does 128 bit copies. AVX2 does 256 bit copies, and AVX512 would allow us to copy 512 bit per instruction. There was quite a bit of work done to introduce our own (#21520).

Some ideas:

Something that did not work: Prefetching

@Algunenano

Copy link
Copy Markdown
Member Author

I tried different alternatives for memcpy but keeping our currently implementation seems the best option so far

Algunenano and others added 3 commits February 20, 2026 18:54
In `range.cpp` `executeConstStartStep` and `iota.cpp` `iota`/`iotaWithStep`,
replace `start + idx * step` with an accumulator `value += step`. This avoids
per-element multiplies (e.g. `pmaddubsw` for UInt8) that cause the compiler to
choose a high auto-vectorization threshold (128 bytes for AVX2 vs 32 for SSE),
making the vectorized path unreachable for short arrays.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@nickitat

Copy link
Copy Markdown
Member

Idk, if this could be useful for you or not. Afaik, the most conservative way to enable AVX2 would be to set -mprefer-vector-width=128 and +allow-light-256-bit (this article has more details). And yes, in the AVX2 context, it should be relevant only to older Intel chips, and if we're determined to enable, we should do so without crutches.

@Algunenano

Copy link
Copy Markdown
Member Author

We currently use the default tuning for x86-64-v3 in clang which contains a bunch of tunings, including +allow-light-256-bit. But for example, when using dynamic dispatch for v4+ we had to add no-prefer-256-bit because the performance was noticeably worse in some cases, mostly because older Intel might need it but newer AMD became worse. It might be tricky to find one specific set up that works best for everything.

@rschu1ze

Copy link
Copy Markdown
Member

The cleanest approach is to assume a processor without throttling, therefore we won't need crutches (prefer-vector-width=128, allow-light-256-bit, no-prefer-256-bit etc.). ClickHouse Cloud runs on ARM anyways.

On x86-64-v3 (AVX2), the compiler semi-vectorizes the `UInt64`->`Float32`
conversion loop using `vpand`/`vpsrlq`/`vpor`/`vblendvpd` for unsigned
fixup, scalar `vcvtsi2ss` with extract/insert, and `vblendvps` for
conditional selection. This ~20-instruction sequence per 4 elements is
slower than simple scalar code (~5 instructions per element with
perfectly-predicted branches), because there is no AVX2 vector instruction
for int64->float conversion (only AVX-512 has `vcvtqq2ps`).

Move the `UInt64`->`Float32` specialization out of the `__aarch64__` guard
and add `_Pragma("clang loop vectorize(disable)")` on x86 to generate
clean scalar code with VEX encoding and 8x unrolling.

Benchmark: `sum(toFloat32(number))` goes from ~9% regression to ~20%
improvement on v3 vs v2.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

Most of the regressions should be covered now. The remaining red tests that I see are all within or at threshold. For example, bigint_arithm query 7 is +18.9% with threshold 18.9% and when testing locally v3 is slightly faster. I'll do another round of pure performance test before switching to check the whole CI.

The default x86 build now requires x86-64-v3 (AVX2). Update the install
script to check for `avx2` instead of `sse4_2` in `/proc/cpuinfo`, falling
back to the `amd64compat` build on older hardware.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@Algunenano

Copy link
Copy Markdown
Member Author

Performance test noise analysis

The performance comparison reports show elevated thresholds and a high number of borderline regressions. This is expected and not indicative of real regressions.

Root cause of the noise: this PR compares a v2 (SSE4.2) baseline against a v3 (AVX2) build. Unlike normal PRs where both old and new binaries share the same ISA target and produce nearly identical machine code, here the two binaries have fundamentally different code generation — different instructions, different vectorization decisions, different instruction scheduling. The perf test alternates between old and new binary runs, and the different ISA targets leave different residual state in CPU caches, branch predictors, etc. This causes variable performance deltas between runs, leading to high variance and high thresholds.

Statistical summary (AMD shards, sha 8ba3244):

  • 2090 queries tested
  • 314 improvements above threshold vs 104 regressions above threshold (3:1 ratio)
  • 87 of 104 regressions are within 2% of their threshold — consistent with the expected ~5% false positive rate
  • Only 2 regressions significantly exceed their threshold, both on queries with very small absolute times (<12ms) where variance is inherently high

Local verification: all CI-reported regressions were benchmarked locally (master binary from CI vs local v3 build). None showed real regressions:

  • not(toFloat32(number)) — reported at +40.4% in CI, locally identical (~0.17s on both)
  • sum(toFloat32(number)) — v3 is faster after the vectorize(disable) fix
  • sumKahan(toNullable(toFloat32(number))) — same speed
  • kostikConsistentHash, number % 10 GROUP BY, intDiv(toInt256), decimal aggregates — all same speed or v3 faster

Note: the sum(toFloat32(number)) query [4] did not run in the latest CI execution, so the fix for that specific query cannot be confirmed from CI yet. A re-run should pick it up.

This noise will disappear once v3 becomes the baseline — future PRs will compare v3 vs v3, restoring normal threshold levels.

@Algunenano

Copy link
Copy Markdown
Member Author

@rschu1ze @nickitat The PR is finally ready for review

Some notes:

  • We use vzeroupper which, for calling small functions using AVX2, is bad for performance (more instructions, larger binary, less i-cache hits...). On the other hand, not using it on Intel would show huge degradations in performance because switching between AVX and SSE has large penalties. AMD would be fine, better in fact, without it. I opted out for the lesser evil

  • There were some large regressions in some functions that I was unable to fix with directives or minor code changes. For now we fallback to compiling those files with v2 instead. In the future I'd like to remove them by doing larger refactors, or breaking the files to reduce its scope. I'd rather not do this in this PR, as there are plenty of "minor" changes already.

  • Due to vzeroupper, code size increases, different code layout, etc., there are a bunch of functions where there might be a small degradation. I've addressed all that the performance tests have shown, focusing on anything that isn't flaky in master and showed 10+% change in CI. I've analyzed all of them on a Intel(R) Xeon(R) Platinum 8488C (EC2 C7i instances), matching what the CI runs.

Current performance report: https://pastila.nl/?00da47bb/5185028c8a271967d39877b08c189567#IQymHLWEeKoq+EhoEfv/iQ==GCM

Summary for 11e6269:

  • Improvements: 52 queries (broad arithmetic / date-time / string / aggregation wins).
  • Regressions: 7 flagged → 6 previously discarded as binary-layout/timing/master-flake noise → 1 (uniq_stored #1) fixed by 66f976d53eb.
  • Variance: 50 unstable — mostly known master-flakes or shard wobble; no new actionable signal.
  • *Net real regressions on AMD: 0.

We can keep iterating more, but at this point I think it's safe to review and merge.

@clickhouse-gh

clickhouse-gh Bot commented May 12, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 92.10% +1.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 95.28% (726/762) | lost baseline coverage: 25 line(s) · Uncovered code

Full report · Diff report

@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.

@Algunenano I actually reviewed an earlier state of the PR (also approved) and then the incremental commits you pushed since. Looks all good to me. Thanks for this PR!

@Algunenano

Copy link
Copy Markdown
Member Author

I've verified and checked locally the latest report and out of the regressions:

@Algunenano I actually reviewed an earlier state of the PR (also approved) and then the incremental commits you pushed since. Looks all good to me. Thanks for this PR!

Thanks a lot. Merging

@Algunenano Algunenano added pr-backward-incompatible Pull request with backwards incompatible changes and removed pr-performance Pull request with some performance improvements labels May 13, 2026
@Algunenano
Algunenano enabled auto-merge May 13, 2026 08:18
@Algunenano
Algunenano added this pull request to the merge queue May 13, 2026
Merged via the queue into ClickHouse:master with commit e21a84e May 13, 2026
322 of 326 checks passed
@Algunenano
Algunenano deleted the x86v3 branch May 13, 2026 08:52
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 13, 2026
Algunenano added a commit to Algunenano/ClickHouse that referenced this pull request May 15, 2026
…6-64-v3 (AVX2)"

This reverts PR ClickHouse#90043 (merge commit e21a84e) due to performance
regressions observed in the MSan build.

Note: a post-merge follow-up commit (9df07df, "Pass nm/ar/objcopy
paths from CMake to localize_rust_c_symbols.sh") added an `NM_PATH`
lookup in `cmake/tools.cmake` for the now-removed
`cmake/localize_rust_c_symbols.sh` helper. The lookup is left in place
by this revert; it is unused but harmless and can be cleaned up
separately.
alexey-milovidov added a commit that referenced this pull request May 19, 2026
PR #90043 set the default x86 build target to x86-64-v3 (AVX2); PR #104971
reverted it in the same release range. Neither change is visible in the
26.5 release, so per the edit-changelog skill rule both entries are
removed.
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 25, 2026
src/Functions/FunctionsRandom.cpp had exactly one dispatch test,
"#if !defined(__AVX2__)", with no #elif and no __aarch64__ anywhere in the
file. Every non-AVX2 target therefore took the scalar arm: four
LinearCongruentialGenerator chains at 16 bytes per iteration. x86 takes the
AVX2 arm (16 chains as four UInt64x4, 128 bytes per iteration) by default,
since ClickHouse#90043 made x86-64-v3 the default x86 target. randomFixedString(10)
over 100M rows is 1.5359x slower on ARM than on AMD as a result, recomputed
from performance-CI history.

RandImpl::execute is the single random-byte source for rand, rand64,
randConstant, randomString, randomFixedString, generateUUIDv4,
generateUUIDv7 and dateTimeToUUIDv7, so one arm reaches all of them.

The reason this was never simply vectorised on ARM is architectural:
AArch64 NEON has no 64-bit-lane integer multiply, so the LCG recurrence
cannot be vectorised there. Confirmed at instruction level with clang-22
under the project's ARM flags: uint64x2 * uint64x2 becomes extract both
lanes to GPRs, scalar multiply, reinsert, while uint32x4 * uint32x4 is a
single mul v0.4s. x86 has the same architectural hole but LLVM auto-emits
the three-partial-product decomposition, which is why the AVX2 arm can
write a portable "gens * a + c". Measuring loop-body instructions per
generated byte, every LCG-preserving vector design for ARM is slower than
today's scalar arm: 0.46x for the portable 64x64 decomposition at both two
and four 64-bit lanes (16 GPR/vector transfers per iteration), 0.93x for a
split-state (lo32, hi32) form. Widening the scalar chain count is not the
portable answer either, since it regresses a shipped configuration:
x86-64-v2 goes from 13.85 to 10.56 GB/s at eight chains, 0.76x.

So the generator has to change on ARM and it has to use a different
execution unit. This adds an additive
"#elif defined(__aarch64__) && defined(__ARM_FEATURE_AES)" arm holding ARS,
reduced-round AES in counter mode, from Salmon et al., "Parallel Random
Numbers: As Easy as 1, 2, 3", SC'11: five AES rounds per 16-byte block,
eight counter blocks in flight to cover AES latency, and round keys drawn
from a Weyl sequence so there is no key schedule inside the loop.
AESE/AESMC issue on the cryptographic pipe rather than competing for the
integer multiply unit.

The gating needs no runtime dispatch. cmake/cpu_features.cmake:53 passes
-march=armv8.2-a+simd+crypto+dotprod+ssbs+rcpc+bf16 for the AArch64 server
profile and clang defines __ARM_FEATURE_AES under those flags; under the
compat profile (NO_ARMV81_OR_HIGHER, -march=armv8+crc at :20) it does not,
so that build keeps the scalar arm. Both measured.

x86 is unaffected by construction: the new arm is inserted before the
existing two, so their bodies are untouched and each x86 build still selects
the arm it selects today. Verified rather than asserted. RandImpl::execute
assembly is byte-identical pre-fix and post-fix at -march=x86-64-v3 (the
AVX2 arm, 30 vpmuludq), at -march=x86-64-v2 (the scalar arm), on ppc64le,
and on the AArch64 compat profile; only the AArch64 server profile changes,
from 16 mul and 4 madd with zero cryptographic instructions to 45 aese and
36 aesmc, which is five rounds times eight blocks plus five for the tail.
Whole-translation-unit assembly on the four unchanged targets differs only
in debug line tables and is identical once those are stripped.

The generated stream changes on AArch64. That is not a new property: the
scalar and AVX2 arms already produce different sequences from each other,
using a different chain count, a different subset of the seed array and a
different bit selection. rand declares isDeterministic() == false and is
reseeded from randomSeed() on every call, so no caller may depend on the
exact sequence.

Correctness of the new arm was checked on an ARM binary under
qemu-aarch64-static, running the same eight-block interleaved loop, with a
liveness control beside each assertion: the overwrite past size peaks at
exactly PADDING_FOR_SIMD - 1 = 63 bytes and never exceeds it, size == 0
writes nothing, two complementary pre-fills agree on every byte in
[0, size) for sizes 1 to 600, and the four-byte randConstant call yields 64
distinct values across 64 seeds. Distribution over 64 MiB against the
scalar arm: byte-histogram chi-square 200.2 against 280.8 for 255 degrees of
freedom, worst per-bit deviation 0.000324 against 0.000237, 16-bit-word
chi-square 65647.9 against 65655.6 for 65535 degrees of freedom. A negative
control of the same output with the top bit of each byte cleared is rejected
by all three statistics, so the screen discriminates. UBSAN with
-fno-sanitize-recover=all is clean. Throughput was never read from qemu,
which interprets each SIMD operation.

Two documentation defects are corrected alongside. rand.cpp, rand64.cpp and
FunctionsRandom.h described the generator as a linear congruential
generator, which is already imprecise given that the two existing arms
differ, and is untrue on the AArch64 server profile after this change; the
descriptions now name the property, that the generator is non-cryptographic
and predictable from its initial state, rather than the algorithm.
FunctionsRandom.h also documented the overwrite contract as 15 bytes, while
the AVX2 arm has required PADDING_FOR_SIMD - 1 = 63 since it was written.
Every call site is backed by a PaddedPODArray, whose pad_right is exactly
PADDING_FOR_SIMD - 1, so nothing was unsafe; the comment was wrong.

The design and the AArch64 A/B measurements in the linked issue are
egor-click's work. On a 32-core Neoverse-V2 he measured two independent
interleaved sessions of 21 runs per side: 29.86% and 30.12% wall-clock
reductions across the four affected performance-CI queries, plus rand()
1.1004x, rand64() 1.1561x and generateUUIDv4() 1.1241x out of sample. He
also discloses a 3.98% regression on small buffers, at max_block_size=64
where the six round keys and three seed derivations are not amortised, and
deliberately declines a size threshold for it on the grounds that a
size-conditional branch shaped around the benchmark that exposed the cost is
the wrong shape for this file.

Closes: ClickHouse#116077
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backward-incompatible Pull request with backwards incompatible changes pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

StringZilla ISA auto-detection mismatch causes build failure with X86_ARCH_LEVEL=4

6 participants