Skip to content

Vectorize sum and avg of Decimal32, Decimal64, Decimal128, Int128 and UInt128 - #126134

Closed
raimannma wants to merge 16 commits into
ClickHouse:masterfrom
raimannma:sum-decimal-simd
Closed

raimannma wants to merge 16 commits into
ClickHouse:masterfrom
raimannma:sum-decimal-simd

Conversation

@raimannma

@raimannma raimannma commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

sum and avg of Decimal32, Decimal64 and Decimal128 accumulate into a Decimal128, and of Int128 and UInt128 into the argument type; the batch loops added every row through wide::integer<128>, which never vectorizes. The new sumIntoInt128 splits the values at bit 32 and sums the parts in 64-bit lanes written with clang vector extensions, so one portable implementation compiles to SSE, AVX2, AVX-512 and NEON. Results are bit-identical, including the wrap-around modulo 2^128. It applies to aggregation without keys, including -If, Nullable arguments, sumWithOverflow of 128-bit types and avg of DateTime64; ranges shorter than one vector step (e.g. from window frames) are added without the vector part.

Single-threaded over 20 million rows (Memory table): sum of Decimal32 6.7x, Decimal64 5x, Decimal128 3x, Int128 8.1x faster, sumIf(Int128) 5.8x; UInt128 was already cheap and is unchanged end to end.

Changelog category (leave one):

  • Performance Improvement

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

Up to 8x faster sum and avg (also with -If and over Nullable) of Decimal32, Decimal64, Decimal128, DateTime64 and Int128 values when aggregating without GROUP BY.


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

`sum` and `avg` of all these types accumulate into a `Decimal128`, and the
batch loops of `AggregateFunctionSumData` added every row through
`wide::integer<128>` (and, without LTO, an out-of-line `addOverflow` call),
which never vectorizes.

The new `sumIntoDecimal128` splits every value at bit 32 and sums the parts in
64-bit lanes written with clang vector extensions, so the same code compiles
to SSE, AVX2, AVX-512 and NEON. A lane cannot overflow within 2^32 rows; the
lanes are combined into the 128-bit result after each chunk. The result is
bit-identical, including the wrap-around of `Decimal128`. It is used for
aggregation without keys (`addMany`, `addManyConditional`, `addManyNotNull`),
so it covers `sum`, `avg`, their `-If` forms, `Nullable` arguments and
`avg` of `DateTime64` / `Time64`.

Single-threaded `SELECT sum(x)` over 50 million rows in a `Memory` table:
2.8x to 8.3x faster depending on type and mode. The kernel is 15x to 120x
faster than the previous loop in microbenchmarks on Zen 5, Alder Lake,
Haswell and Zen 2.
Comparing byte vectors gives a vector of `char`, which is unsigned on ARM and
s390x, so the masks were converted to 255 instead of all ones and the
conditional paths (`-If`, `Nullable`) kept only the low byte of every value.
Widen the flags to 64-bit lanes before comparing them.
Vector comparisons are deprecated for AltiVec vectors, so the PowerPC build
failed with `-Wdeprecated-altivec-src-compat`. Derive the masks from the sign
bit of `flag - 1` or `-flag` instead, which does not depend on the element
type of comparison results either. LLVM still emits the same byte comparisons
on x86.
@clickhouse-gh clickhouse-gh Bot added the comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). label Oct 15, 2026
Window frames and ranges of equal keys call the batch path with a few rows,
for which zeroing, reducing and recombining the vector lanes cost more than the
old scalar loop. The vector loop now only runs over whole steps, and the
remaining rows are added to an `unsigned __int128` directly, which also
replaces the three per-type scalar tails. The vector loop is unrolled four
times explicitly, because the compiler does not do it reliably.
`sum`, `sumWithOverflow` and `avg` of `Int128` and `UInt128` accumulate in
the argument type, and the batch loops added every row through
`wide::integer<128>`. Modulo 2^128, signed and unsigned values are added the
same way as `Decimal128`, so the vectorized kernel is reused: it is renamed to
`sumIntoInt128`, returns the 128-bit result, and accepts `Int128` and
`UInt128` values too.
Its steps are narrow (a sign extension and an addition), and with four steps
in flight the sum over large ranges was about 20% slower than before the
short-range change.
The tail has fewer rows than one step, but the compiler unrolled and
vectorized it into code that never runs and a larger stack frame; disable
that. Also drop casts through `__int128`: converting a signed value to
`unsigned __int128` already sign-extends.
`sumWithOverflow` takes the same path as `sum` here, and the full-range values already wrap around.
clang-tidy (`cppcoreguidelines-init-variables`) rejected the variable assigned in two branches.
@raimannma raimannma changed the title Vectorize sum and avg of Decimal32, Decimal64 and Decimal128 Vectorize sum and avg of Decimal32, Decimal64, Decimal128, Int128 and UInt128 Oct 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bd1a570]

Summary: ✅


AI Review

Summary

PR #126134 vectorizes batch sum and avg accumulation for decimal and 128-bit integer inputs, including conditional and nullable inputs. No actionable findings in head bd1a5704694a213da9549c838739d1775ade5c85. The supplied performance measurements and focused regression coverage support the change.

Missing context / blind spots
  • ⚠️ Local execution was unavailable because this workspace has no ClickHouse build or Clang toolchain. Both added regression tests pass in the current Fast test report; independent execution on other architectures remains unverified.
Final Verdict

Status: ✅ Approve. No required changes.

@clickhouse-gh clickhouse-gh Bot added pr-performance Pull request with some performance improvements external Author is not a member of the ClickHouse organization labels Oct 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

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.

Compile time of recompiled translation units

11 translation units recompiled, 57 s compile time in total, 11 of them have a recent master baseline.

Median compile-time ratio to the baselines is ×1.07 (machine-speed difference or a change affecting every TU); per-TU deltas below are relative to that ratio.
The matched translation units cost +4.8 s (+9%) in total before that adjustment.

Job report

@raimannma raimannma closed this Nov 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-aggregate-functions Aggregate function implementations (sum, avg, count, quantile, combinators, etc.). external Author is not a member of the ClickHouse organization pr-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants