Skip to content

Speed up variance and standard deviation over Decimal columns - #108648

Draft
nickitat wants to merge 26 commits into
masterfrom
scoped-fp-flags-stats
Draft

nickitat wants to merge 26 commits into
masterfrom
scoped-fp-flags-stats

Conversation

@nickitat

@nickitat nickitat commented Jun 26, 2026 •

Copy link
Copy Markdown
Member

The "simple" statistics aggregate functions got a vectorized accumulation path in #110461, but
only for non-Decimal arguments. A Decimal column stores unscaled integers - the scale belongs
to the data type, not the column - and the kernel has no way to apply it, so Decimal stayed on
the generic per-row loop, which additionally called the out-of-line convertFromDecimal once per
value.

varPop, varSamp, stddevPop and stddevSamp now take the vectorized path over Decimal too,
and the per-row conversion no longer re-derives the scale multiplier on every row.

Where the division goes comes down to what the accumulation loop can still hold. It already carries
sixteen lane accumulators, so anything else competing for vector registers spills them:

  • AArch64 has the room - 32 SIMD registers, and a conversion that works in place on the loaded
    vector: 40 packed ops, no calls, 6 stack accesses for Decimal64. So the division rides along
    inside the loop and nothing is copied.
  • x86-64 has 16 ymm and does not. Its fused loop spills every iteration and the vectorizer drops
    to a mix of two-wide and scalar glued with shuffles - 11 scalar vcvtsi2sd against 3 packed
    vcvtdq2pd, 14 in-loop stack accesses. So it converts into a cache-resident tile of 1024 first,
    at every width, including Decimal32, which does have a packed convert: 0.194s against 0.237s.
  • wide::integer has no conversion instruction at all and lowers to soft-float quad calls, which
    clobber the vector registers by calling convention - 102 calls and 291 stack accesses against 37 -
    so it takes the tile on either target. The calls still run once per element; the tile only keeps
    them out of a loop holding live accumulators, which was worth 0.950s against 1.004s on AArch64.

This does not change results. Both shapes accumulate into the same lanes and walk the input in the
same chunks, so they fold the moments at the same points. Compiling both on x86-64 and diffing the
raw bits of varPop, varSamp, stddevPop, skewPop and kurtPop over Decimal32, Decimal64
and Decimal128 gives identical output.

skewPop and kurtPop deliberately stay on the per-row path. They carry two more moments per
lane, and on AArch64 no lane count pays for that - against the per-row path, the best of 2, 4, 8
and 16 lanes is +7.2% at level 3 - while on x86-64 the whole gain for those two measured only
-7.2%. Not worth a regression on one target. The per-row path gives each moment its own dependency
chain, so the third and fourth cost it nothing: it measures the same at every level.

Measurements

From the CI performance comparison, 100M rows:

query AArch64 x86-64
varPop, varSamp, stddevPop over Decimal32 -6.3% -25.3%
varPop, varSamp, stddevPop over Decimal64 -2.2% -20.0%
varPop, varSamp, stddevPop over Decimal128 -52.7% -52.8%
skewPop, kurtPop over Decimal64 +0.6% parity
varPop over Float64 (control) 0.0% 0.0%

Decimal128 gains most, and mostly for a reason unrelated to the accumulation. convertFromDecimal
evaluates static_cast<Float64>(value) / static_cast<Float64>(scaleMultiplier<Int128>(scale)), so it
converts a 128-bit wide integer to double twice per row - once for the value and once to re-derive
a divisor that never changes. convertOne computes the divisor once, in the constructor. Measured on
varPop over Decimal128, 50M rows, single thread, on both targets: x86-64 goes 0.517s to 0.251s
with only the divisor hoisted and 0.214s with the vectorized path as well; AArch64 goes 1.980s to
0.961s and then 0.950s. So the hoisting is seven eighths of it on x86-64 and nearly all of it on
AArch64. For Decimal32 and Decimal64 the hoisting is worth nothing - isolated with varPopIf,
which stays on the per-row path, master and this branch measure 0.268s against 0.268s on x86-64 and
0.187s against 0.186s on AArch64 - so there the gain is entirely the vectorized path.

Isolating the kernel on a Graviton, 100M elements, best of nine, the shape that regressed AArch64
before this was fixed measures +38.9% against the per-row path, while the one used now measures
-9.1%. Its disassembly loads the column with ldp q and runs scvtf v.2d, fdiv v.2d,
fmul v.2d and fadd v.2d, with no store and reload of a buffer.

Scope

The batched path covers plain unary aggregation and the masked forms - the -If combinator and
Nullable arguments - for types narrower than 128 bits. Measured on AArch64, 50M rows, single
thread:

query master this PR
varPopIf over Decimal32 0.196s 0.180s
varPopIf over Decimal64 0.187s 0.173s
varPop over Nullable(Decimal64) 0.393s 0.324s
varPopIf over Decimal128 1.059s 0.553s
varPop over Nullable(Decimal128) 2.014s 1.098s

Wide decimals take the masked forms on the per-row path, the opposite of the unconditional case. A
tile is converted whole and masked afterwards, so it converts rows the flag then discards - fine
while the conversion is an instruction, but for wide::integer it is the dominant cost and doubling
it gave back everything the batching won, 0.554s to 1.033s on varPopIf over Decimal128. They
still gain there, from the hoisted divisor rather than the batching.

The two-argument kinds - covarPop, covarSamp, corr - and the higher moments stay on the
per-row path everywhere.

Coverage

00700_decimal_aggregates checks variance and stddev over Decimal but nothing checks the higher
moments, and the performance test never compares output, so 04695_decimal_skewness_kurtosis
covers skewPop, skewSamp, kurtPop and kurtSamp over Decimal32, Decimal64 and
Decimal128 at three row counts - spanning several whole tiles with a partial one left over,
below a single tile, and an exact multiple - and cross-checks each against the same values read as
Float64. 04696_decimal_variance_conditional does the same for the masked forms, including both
flags at once, an all-zero and an all-one mask.

Result change

One value in 00700_decimal_aggregates moves: varPop over the Decimal128 column is now 34
rather than 34.00000000000001. The partial sums accumulate less rounding error than the
sequential loop, so the result lands on the exact value.

Related: #110461

Changelog category (leave one):

  • Performance Improvement

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

varPop, varSamp, stddevPop and stddevSamp are now faster over Decimal and DateTime64 arguments. Plain aggregation is 20-25% faster for Decimal32 and Decimal64 on x86-64 and about twice as fast for Decimal128 on both x86-64 and AArch64. The -If combinator and Nullable arguments are faster too - around 8% for Decimal32 and Decimal64, 18% for Nullable(Decimal64) and about 45% for Decimal128.

@nickitat nickitat added pr-performance Pull request with some performance improvements ci-performance performance only labels Jun 26, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [19ce464]

Summary: ❌

job_name test_name status info comment
Stress test (arm_release) FAIL
S3_ERROR No such key thrown (see clickhouse-server.log or no_such_key_errors.txt) FAIL cidb
Stress test (arm_asan_ubsan) FAIL
Sanitizer (STID: 2064-22d0) FAIL cidb

AI Review

Summary

This PR speeds up the simple Decimal variance and standard-deviation aggregates by hoisting the Decimal scale divisor, adding batched accumulation paths for the level-2 one-argument cases, and extending the masked fast path to -If and Nullable for narrow Decimal widths. The core implementation and the earlier x86/AArch64 shape issues look addressed, but I still cannot approve because one of the new stateless tests still lacks an independent oracle for the width-specific conversion path it changes most, and the changelog text still promises a DateTime64 improvement that the aggregate factory does not expose.

Findings

💡 Nits

  • [src/AggregateFunctions/AggregateFunctionStatisticsSimple.h:477-480] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/108648#discussion_r3722741760] Performance Improvement is the right category, but the Changelog entry still overstates the user-visible scope by claiming DateTime64 speedups. createAggregateFunctionStatisticsUnary only reaches createWithDecimalType when isDecimal(data_type) is true, so DateTime64 still goes down the createWithNumericType branch and remains unsupported here. Replace the entry text with the same sentence minus the DateTime64 claim: `varPop`, `varSamp`, `stddevPop` and `stddevSamp` are now faster over `Decimal` arguments. Plain aggregation is 20-25% faster for `Decimal32` and `Decimal64` on x86-64 and about twice as fast for `Decimal128` on both x86-64 and AArch64. The `-If` combinator and `Nullable` arguments are faster too - around 8% for `Decimal32` and `Decimal64`, 18% for `Nullable(Decimal64)` and about 45% for `Decimal128`.
Tests
  • ⚠️ [tests/queries/0_stateless/04695_decimal_skewness_kurtosis.sql:27-31] The only independent oracle in the new high-moments regression test is the toFloat64(d64) comparison. skew* and kurt* over Decimal128 still run through the changed convertOne path, and Decimal32 still exercises a distinct width-specific conversion/codegen path on x86, so a width-specific regression can still be blessed by re-recording the .reference file. Add the same abs(fn(d128) - fn(toFloat64(d128))) check here, and ideally the d32 variant as well, so the new reference file proves correctness instead of only snapshotting it.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: extend 04695_decimal_skewness_kurtosis with an independent Float64 oracle for at least Decimal128, and fix the Changelog entry to remove the unsupported DateTime64 claim.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 34/42 (80.95%) · Uncovered code

Full report · Diff report

Structural alternative to the scoped-flag approach: override addBatchSinglePlace
for the common single-argument, unconditional case with a typed-pointer loop over
`unroll` independent partial moment states, then merge them. Breaking the
serial reduction dependency lets the per-row `m[1] += x; m[2] += x*x` loop
auto-vectorize without any FP flag.

Confirmed on AggregateFunctionSecondMoment.cpp (release, -march=x86-64-v3):
packed `vmulpd` 0 -> 8 and ~600 `ymm` registers now appear in the reduction
(4-wide SLP across the 4 partials) - vectorization the scoped
`-ffp-contract=fast`/`-freciprocal-math` could not achieve (those gave only
scalar FMA + fewer divides).

Summation order differs from a strict sequential sum (last-bit float
differences), but the result is deterministic across builds and platforms,
unlike the flag approach - and it is consistent with how `merge` already
tree-reduces partial states across blocks. Conditional aggregation and the
two-argument (covar/corr) kinds fall back to the scalar base loop.

WIP: the Decimal path still converts per element inside the loop; a follow-up
will bulk-convert Decimal columns to Float64 up front so that path vectorizes too.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@nickitat
nickitat force-pushed the scoped-fp-flags-stats branch from 1955835 to 3b4cb11 Compare June 29, 2026 15:40
…convert

Replaces the previous per-block partial-`VarMoments` array (which only
auto-vectorized 2-wide) with a struct-of-arrays lane layout that the compiler
turns into a 4-wide `ymm` reduction for `Float64`.

`addManyContiguous` accumulates into `W=4` independent lane accumulators
(`s1[W]`, `s2[W]`, ...) and folds them with an explicit, fixed-order horizontal
sum. Two subtleties were needed to actually get `ymm`:
  - the lanes must be local (a lambda capturing them, or storing them in the
    aggregate state, keeps them in memory and blocks SLP);
  - the fold must be an unrolled `s[0]+s[1]+s[2]+s[3]`, not a loop - a reduction
    loop forces the lane arrays to stay addressable and degrades the hot loop to
    128-bit.

For types that need a per-element conversion (integers, `Decimal`), the scalar
conversion (e.g. `Int64`/`Decimal` have no `vcvtqq2pd` at `x86-64-v3`) is
decoupled from the accumulation: a small cache-resident tile is converted to
`ResultType` first, then accumulated. Interleaving the two in one loop lets the
scalar convert block vectorization; the tiled form lets both passes run at full
throughput (e.g. Decimal64 ~2.4x faster than the inline-convert variant).

Measured single-thread (Granite Rapids, `-march=x86-64-v3`):
  - kernel itself ~3x (200M `Float64`, in-register);
  - aggregation-bound query (in-memory / several moments at once) -30% to -50%;
  - `Float64`/`Decimal` over a compressed `MergeTree` column ~ -5% (read-bound);
  - bandwidth-bound multi-thread scans: negligible.

The fast path covers only the unconditional single-argument case; conditional
aggregation (`if_argument_pos >= 0`) and the two-argument `covar`/`corr` kinds
keep the scalar base loop. Results are slightly more accurate than the old
sequential sum (partial sums reduce error) but, like all float aggregation in
ClickHouse, are no longer bit-identical across `max_block_size`/`max_threads`;
the "simple" variance is documented as numerically unstable. Updated the
exact-value references in `00700_decimal_aggregates` and `02833_std_alias`
(last-bit drift; one value is now the cleaner `34` instead of `34.00000000000001`)
and made `01278_variance_nonnegative` round so it keeps asserting the
non-negativity invariant without depending on last bits.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat
nickitat force-pushed the scoped-fp-flags-stats branch from 2c39c2b to ccef40f Compare June 29, 2026 17:59
…path

The variance/stddev aggregates were exercised by only three queries in
`decimal_aggregates` (two of them over 10M rows, too small to give a stable
signal), and there was no coverage at all for the `Float64`/`Float32`/integer
paths or for moment levels 3/4. This adds a focused test with one query per code
path of `AggregateFunctionVarianceSimple::addBatchSinglePlace`:

  - direct accumulation for `Float64`/`Float32`;
  - tiled convert for integers - `UInt32` (vectorized `int32->double`) and
    `Int64` (scalar convert);
  - tiled convert for `Decimal32`/`Decimal64`/`Decimal128`;
  - levels 2 (`varPop`/`varSamp`/`stddev`), 3 (`skewPop`), 4 (`kurtPop`).

Columns are typed (not cast in the query) so the only conversion measured is the
one inside the aggregate. ~300M rows in a `Memory` table keeps every query large
enough to be stable yet well under the 15s per-query limit (the slowest,
`Decimal128`, is ~1.5s parallel) and within the 35G memory budget. Local A/B vs
master showed -12% to -24% across the paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat
nickitat force-pushed the scoped-fp-flags-stats branch from a63f549 to c5e7a07 Compare June 29, 2026 21:02
…tecture

The previous version always staged integer/Decimal columns through a converted
tile. That helps on x86-64-v3 (no packed `int64 -> double`: `vcvtqq2pd` is
AVX-512 only), where decoupling the scalar conversion from a vectorized
accumulate is a win. But on AArch64, NEON `scvtf` converts `int64 -> double`
inline, so the tile's buffer round-trip is pure overhead - the ARM perf run
showed `Decimal32`/`Decimal64` `varPop` regressing +21%/+24% while every other
path improved.

Two changes:

  - Convert `Decimal -> Float64` inline (`value / 10^scale`) via a `convertOne`
    helper instead of the out-of-line `convertFromDecimal`. The value is
    identical (same `convertToImpl` math), but the conversion can now
    auto-vectorize (`vcvtdq2pd`/`vdivpd` for `Decimal32` on x86, `scvtf`/`fdiv`
    on AArch64) and, more importantly, the per-element PLT call is gone. This
    alone speeds up x86: `Decimal32` -27%, `Decimal64` -32%, `Decimal128` -50%
    vs the previous tiled version (single-thread, 100M rows, Granite Rapids).

  - Keep the tile only on `__x86_64__`; on other targets accumulate in one
    direct pass (the inline convert vectorizes, so no buffer is needed). On
    AArch64 the hot loop is `scvtf`/`fdiv`/`fmul`/`fadd` over `2d` vectors with
    no store/load round-trip, which removes the regression.

Results are bit-identical to before (the convert math is unchanged), so no test
references change. x86 codegen unchanged for `Float64` (38 `ymm`); AArch64
direct path verified via cross-compiled codegen. ARM runtime to be confirmed by
the CI performance test (the Graviton bench box was unavailable).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat
nickitat force-pushed the scoped-fp-flags-stats branch from 78bbca0 to 8d9efe7 Compare June 30, 2026 11:04
`W` is only used by the x86 tiled path; on AArch64 the `#else` branch does not
reference it, so it tripped `-Werror,-Wunused-variable` and broke the arm_release
build. Move the declaration into the `#if defined(__x86_64__)` block.

Verified both targets compile: x86-64 locally and aarch64 (`-fsyntax-only`) on a
Graviton4.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108648&sha=8d9efe7c6229f66dc73f21af8375e11633bbc02e&name_0=PR&name_1=Build%20%28arm_release%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@nickitat nickitat removed the ci-performance performance only label Jun 30, 2026
`google-default-arguments` prohibits default arguments on virtual/override
methods; the default lives on the base `IAggregateFunction::addBatchSinglePlace`
declaration. This broke the arm_tidy build. The only caller passes
`if_argument_pos` explicitly, so dropping the `= -1` is a no-op.

CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108648&sha=21001c26ef53f59539105d7228581fd1e11a9923&name_0=PR&name_1=Build+%28arm_tidy%29

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

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is scoped entirely to vectorizing the variance/stddev/skew/kurtosis aggregate family (varPop, varSamp, stddevPop, skewPop, kurtPop) in AggregateFunctionVarianceSimple, plus test/reference updates. ClickBench Q4 and Q15 do not use any of those functions, so the code path the PR changes is never executed by these queries. The flagged ~17-18% improvements on Q4 and Q15 are therefore run-to-run variance rather than a real effect of this change, and both have been downgraded to not-sure. The PR's actual impact should be read from the dedicated variance_aggregates benchmark it adds.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 263 217 -17.5% <0.0001 aggregation: PR only vectorizes variance/stddev/skew aggregates; Q4 uses none of them, so -17% is run-to-run variance.
⚠️ 15 not_sure 247 202 -18.2% <0.0001 aggregation: PR only touches the variance/stddev aggregate family; Q15 doesn't call those, so -18% is run-to-run variance.

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: 904501bd-c6aa-4522-ad61-dc26df25aab9
  • MIRAI run: 6e6d3bd4-f213-4361-9fd4-78d1c8f32b45
  • PR check IDs:
    • clickbench_531426_1782848945
    • clickbench_531432_1782848945
    • clickbench_531443_1782848945
    • tpch_adapted_1_official_531451_1782848945
    • tpch_adapted_1_official_531465_1782848945
    • tpch_adapted_1_official_531478_1782848945

@clickhouse-gh

clickhouse-gh Bot commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 85.50% +0.10%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

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

Full report · Diff report

@nickitat nickitat changed the title Apply -ffp-contract=fast -freciprocal-math to variance/stddev and avgWeighted Auto-vectorize statistics functions Jul 1, 2026
@nickitat nickitat changed the title Auto-vectorize statistics functions Auto-vectorise statistics functions Jul 1, 2026
@nickitat

nickitat commented Aug 3, 2026

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

# Conflicts:
#	tests/queries/0_stateless/00700_decimal_aggregates.reference
#	tests/queries/0_stateless/01278_variance_nonnegative.sql

Copilot AI commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Done — merged origin/master into the branch. There were two conflicts:

  • 01278_variance_nonnegative.sql: adopted master's BETWEEN 0 AND 1e-6 approach (cleaner invariant test that matches the already-updated reference file).
  • 00700_decimal_aggregates.reference: kept the values produced by the vectorized code (94.44444438684269, 95.38888883071111), which differ from the pre-vectorization values by 1 ULP.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ nickitat
❌ Copilot
You have signed the CLA already but the status is still pending? Let us recheck it.

nickitat and others added 4 commits August 5, 2026 13:54
…Weighted

The variance/stddev (AggregateFunctionSecondMoment.cpp: varPop, varSamp,
stddevPop, stddevSamp) and avgWeighted hot loops are scalar reductions that do
not vectorize - the per-element Decimal->Float64 conversion and the column
access block auto-vectorization. Measured on AggregateFunctionSecondMoment.cpp
(release, -march=x86-64-v3):

  - -fassociative-math: no-op (byte-identical codegen; reduction stays scalar)
  - -ffp-contract=fast: fuses the scalar `a*b + c` accumulations into FMA
    (0 -> 700 vfmadd*sd)
  - -freciprocal-math: turns the per-element divide-by-10^scale of the Decimal
    conversion into a multiply (320 -> 240 scalar divides)

So the realizable flag win is scalar (FMA + fewer divides), matching the
`decimal_aggregates` and `avgWeighted` improvements seen in the global fast-math
experiment. `-fassociative-math` is deliberately excluded - it changes nothing
here and would only add reassociation non-determinism. The two flags override
the global `-ffp-contract=off`; the last-bit, non-bit-identical-across-platforms
cost is acceptable for these already-approximate floating-point statistics.

A follow-up will try a structural refactor (typed batch loop + partial
accumulators, pre-converting Decimal columns in bulk) to actually vectorize
these reductions and compare the numbers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The merge of `master` brought in the vectorized `addBatchSinglePlace` and
`addBatchSinglePlaceNotNull` for `AggregateFunctionVarianceSimple` added by
#110461, which collided with the override introduced on this branch:

    AggregateFunctionStatisticsSimple.h:252:10: error: class member cannot be redeclared

Every other error in the report cascades from that redeclaration.

The implementation from `master` supersedes this branch's for every
non-`Decimal` type - it accumulates into `128 / sizeof(T)` lanes rather than 4,
dispatches to an AVX-512 variant through `MULTITARGET_FUNCTION_X86_V4`, and
also covers the conditional and not-null paths - so keep it and drop this
branch's `addManyTyped` along with its override.

What `master` does not cover is `Decimal`: it routes those to the scalar
per-row fallback, because the values need a per-row conversion with the source
scale before they can be accumulated. Keep that part of this branch's work by
staging a cache-resident tile of converted values and feeding the tile to the
`addMany` kernel from `master`. For `varPop` over `Decimal128` in
`00700_decimal_aggregates` this also brings the result back to the reference
value, `34` rather than the `34.00000000000001` that the scalar path produces.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108648&sha=f8a5f4281a8d69cc20ce47354d36ec8587a7a413&name_0=PR&name_1=Fast%20test
Related: #108648
Related: #110461

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
The two references were adjusted on this branch for its own lane layout. That
implementation is gone - `master` now supplies the vectorized path - so the
values go back to what `master` records, except for one cell.

`varPop` over the `Decimal128` column of `00700_decimal_aggregates` is now
`34` rather than `34.00000000000001`: `Decimal` no longer goes through the
scalar per-row fallback, and the partial sums of the vectorized kernel carry
less rounding error, so the result lands on the exact value.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108648&sha=f8a5f4281a8d69cc20ce47354d36ec8587a7a413&name_0=PR&name_1=Fast%20test
Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Reverts 1ddf024.

Two reasons. The measured one: fusing `m[2] += x * x` into an FMA puts the
multiply onto the loop-carried accumulator of a latency-bound serial reduction,
which is a win on Intel but a regression on AMD Zen - a flag whose sign depends
on the microarchitecture is a bad trade. And the loops the commit message
describes no longer exist: `master` supplies a vectorized `addMany` for these
functions, so the premise that they are scalar reductions that do not vectorize
is stale.

It also changes results - `00954_resample_combinator` fails on the last bits of
`stddevPopResample` with the flags applied and passes without them.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
@nickitat nickitat changed the title Auto-vectorise statistics functions Speed up variance, standard deviation, skewness and kurtosis over Decimal columns Aug 5, 2026
The vectorized `Decimal` path is shared by all four moment levels, but the only
`Decimal` results any stateless test checks are the variance and stddev queries
in `00700_decimal_aggregates`. `skewPop` and `kurtPop` over `Decimal` run only
in `tests/performance/variance_aggregates.xml`, which measures time and never
compares output, so a broken fold of the `m[3]` or `m[4]` accumulators would go
unnoticed.

The new test covers all four of `skewPop`, `skewSamp`, `kurtPop` and `kurtSamp`
across `Decimal32`, `Decimal64` and `Decimal128`, at three row counts - one that
spans several whole conversion tiles and leaves a partial one, one that stays
below a single tile, and one that is an exact multiple of the tile size. It also
compares each result against the same values read as `Float64`, which take the
path the non-`Decimal` types already use, and checks that skewness of a sample
symmetric about zero stays zero.

Verified by mutation: dropping the partial tail tile, and accumulating one
element fewer per tile, are both caught. Ran 12 times with settings
randomization and 12 times without, stable in all 24.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
nickitat and others added 2 commits August 6, 2026 18:30
The previous wording, that the column "cannot be fed to the vectorized
`addMany` kernel directly", claims a constraint that does not exist. `Decimal`
converts implicitly to its native integer through `Decimal::operator T`, so
passing the column straight to `addMany` compiles - it just accumulates the
unscaled integers and returns a wrong answer. A reader who tried it would find
the comment says the opposite of what the compiler does.

Say instead where the scale lives and why the kernel cannot apply it, and
separate that from the second reason the loops stay apart, which is that
`x86-64-v3` has no packed `int64 -> double` and a fused convert-and-accumulate
loop would therefore not vectorize.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
nickitat added a commit that referenced this pull request Aug 6, 2026
Three things were wrong with the size of this test.

`max_memory_usage` was set to 35G, copied from `decimal_aggregates` next door.
That setting defaults to `0`, meaning unlimited, so the line raised no limit -
it imposed one. It dates from when the default was 10 GiB. Dropped.

The `Float32`, `UInt32` and `Int64` columns and their queries duplicated
`statistics_simple_if`, which already measures `varSamp` and `kurtSamp` over
`UInt64`, `varSampIf` over `Float64` and `Float32`, and a `Nullable(Float64)`
table - all over `numbers()`, needing no table at all. Dropped, leaving one
`Float64` query as a control that shares the aggregate function but not the
`Decimal` path.

That leaves 300M rows of a seven-column table, ~15G held for the whole run, to
measure an aggregation the machine was not spending its time on: past roughly
100M rows these queries are bound by memory bandwidth, so a wider table shrinks
the difference being measured rather than growing it. Measured on `Decimal64`,
best of three: 300M rows gives 0.124s against 0.058s, and 100M rows gives 0.045s
against 0.019s - a bigger relative gap on the smaller table.

At 100M rows the table holds 3.36 GiB, and all four `Decimal` queries move by
half or more while the `Float64` control stays flat.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Three things were wrong with the size of this test.

`max_memory_usage` was set to 35G, copied from `decimal_aggregates` next door.
That setting defaults to `0`, meaning unlimited, so the line raised no limit -
it imposed one. It dates from when the default was 10 GiB. Dropped.

The `Float32`, `UInt32` and `Int64` columns and their queries duplicated
`statistics_simple_if`, which already measures `varSamp` and `kurtSamp` over
`UInt64`, `varSampIf` over `Float64` and `Float32`, and a `Nullable(Float64)`
table - all over `numbers()`, needing no table at all. Dropped, leaving one
`Float64` query as a control that shares the aggregate function but not the
`Decimal` path.

That leaves 300M rows of a seven-column table, ~15G held for the whole run, to
measure an aggregation the machine was not spending its time on: past roughly
100M rows these queries are bound by memory bandwidth, so a wider table shrinks
the difference being measured rather than growing it. Measured on `Decimal64`,
best of three: 300M rows gives 0.124s against 0.058s, and 100M rows gives 0.045s
against 0.019s - a bigger relative gap on the smaller table.

At 100M rows the table holds 3.36 GiB, and all four `Decimal` queries move by
half or more while the `Float64` control stays flat.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
@nickitat
nickitat force-pushed the scoped-fp-flags-stats branch from 3edb3c2 to 464de71 Compare August 6, 2026 18:52
nickitat and others added 2 commits August 6, 2026 19:21
CI measured `varPop`/`varSamp`/`stddevPop` over `Decimal32` and `Decimal64`
running 38.8% and 42.0% slower on ARM, and `skewPop`/`kurtPop` over `Decimal64`
42.0% slower, while every one of them got faster on x86-64.

Resolving the merge with master dropped an arch guard this branch used to
carry. Converting into a buffer before accumulating is a workaround for an ISA
gap: `x86-64-v3` has no packed `int64 -> double`, so a fused convert-and-
accumulate loop runs the converts scalar and the accumulation never vectorizes.
AArch64 has no such gap - `scvtf` and `fdiv` both work on `2d` vectors - so
there the buffer is a copy that buys nothing. Measured on Graviton, 100M
elements, best of five: the buffer costs +38.7% against the per-row path while
dividing inside the accumulation loop gains -9.1%. The disassembly agrees: the
loop loads the column with `ldp q` and runs `scvtf v.2d`, `fdiv v.2d`,
`fmul v.2d`, `fadd v.2d`, with no store and reload of a buffer.

So `addManyDivided` accumulates straight off the column, and the caller picks
between it and the buffer by what the target can convert packed. `Decimal128`
and wider keep the buffer everywhere, having no packed conversion on either
target.

This does not change results. Both shapes accumulate into the same lanes and
walk the input in the same `TILE`-sized chunks, so they fold the moments at the
same points; compiling both on x86-64 and comparing the raw bits of `varPop`,
`varSamp`, `stddevPop`, `skewPop` and `kurtPop` over `Decimal32`, `Decimal64`
and `Decimal128` gives identical output. Single-threaded - `max_threads` still
reorders the merge, on master too.

`skewPop` and `kurtPop` go back to the per-row path on every target. They carry
two more moments per lane, and on AArch64 no lane count pays for them: against
the per-row path, the best of 2, 4, 8 and 16 lanes is +6.9% at level 3 and
-2.0% at level 4. The x86-64 side gives up little, since CI measured the whole
gain for those two at -7.2%.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/PRs/108648/29090a3b7ef9d815b86ad87b3ad9a3c6aaad9269/performance_comparison_arm_release_master_head_3_6/report.html
Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Keep the reasons, drop the retelling of the measurements - those are in the
commit that made the change.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
@nickitat nickitat changed the title Speed up variance, standard deviation, skewness and kurtosis over Decimal columns Speed up variance and standard deviation over Decimal columns Aug 6, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

No arm_release build profile data for commit 19ce464 - the build was skipped, reused from cache, or predates profile upload.

nickitat and others added 3 commits August 7, 2026 12:45
The per-row path gives each moment its own dependency chain, so the third and
fourth are free to it - measured on AArch64 it takes the same time at level 2,
3 and 4 - while the lane kernel pays for them in arithmetic. That, rather than
the lane count on its own, is why `skewPop` and `kurtPop` do not move.

Also record what the lane kernel is doing on AArch64 for the lower levels,
which is not what the previous comment implied: it only matches the per-row
path there, since the gain is the inlined conversion rather than the lanes. It
earns its place by folding the same way as x86-64, so both targets return the
same value.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Two things were wrong. `StatFuncOneArg` is only instantiated at levels 2, 3 and
4, so "the two levels below" named a level 1 that does not exist. And the claim
that AArch64 merely matches the per-row path there holds only for the types
that divide inline, `Decimal32` and `Decimal64`. `Decimal128` takes the buffer
on either target, and CI measures it at -52.7% on AArch64 - it is where most of
the gain is, not an exception to a rule about breaking even.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Neither was answerable from the comment. The width split reads as an
optimization applied only to wide types, and the level cutoff reads as an
arbitrary number.

The width split is what the target converts packed: `x86-64-v3` has no packed
`int64 -> double`, and buffers `Decimal32` too because that measured faster
even though `vcvtdq2pd` exists; AArch64 converts packed up to 64-bit lanes with
`scvtf` and needs no buffer below `Decimal128`; `Decimal128` has no packed
conversion anywhere. Every width takes the fast path on both targets - they
differ in how the values reach it.

The level cutoff is not per-target even though the loss is. Levels 3 and 4 lose
on AArch64 whatever the lane count, and the two targets have to fold the same
way to return the same value, so taking the path on x86-64 alone is not
available - it goes for both or neither, and the x86-64 gain there was -7.2%.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
nickitat and others added 3 commits August 7, 2026 17:50
The comment said the split was about what the target converts packed. Building
the branch on AArch64 and disassembling both variants says otherwise.

Up to 64 bits the conversion is one instruction, so fusing it into the
accumulation leaves the loop call-free and it vectorizes: for `Decimal64`, 40
packed ops, no calls, 6 stack accesses. `wide::integer<128>` has no such
instruction and lowers to soft-float quad calls - `__floatunditf`, `__multf3`,
`__addtf3` - and because the procedure call standard clobbers the vector
registers, the lane accumulators spill around every one: 102 calls and 291
stack accesses against 37 for the buffered shape. Measured on `varPop` over
`Decimal128`, 50M rows, single thread: buffered 0.950s, fused 1.004s.

Note the fused shape has more vectorization than the buffered one, 49 packed
ops against none, and is still slower - on AArch64 this was never about SIMD.
The buffered accumulation there keeps 16 scalar accumulators in registers.

Also verified the two shapes are bit-identical for `Decimal128` on AArch64;
that had only been checked for the narrower types on x86-64.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
`sizeof(NativeType) > 8` was standing in for "converting this needs library
calls rather than an instruction". `is_big_int_v` says that, and is exactly
equivalent here: for the native types of `Decimal32`, `Decimal64`, `Decimal128`
and `Decimal256` the two agree on all four.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
The comment framed the choice as whether converting an element takes a call,
which got two things wrong.

The tile does not remove the calls. For `wide::integer` the soft-float quad
routines run once per element out of the tile exactly as they would out of a
fused loop; what changes is that they no longer run in a loop holding sixteen
live accumulators. That is why the tile is worth 5%, not 3x.

And the deciding constraint is register pressure, not the presence of an
instruction. `Decimal32` on x86-64 has a packed convert and still measures
faster through the tile - 0.194s against 0.237s - because fusing it into a loop
already carrying sixteen lane accumulators exceeds the 16 `ymm` registers: the
loop spills every iteration and the vectorizer drops to a mix of two-wide and
scalar, 11 scalar `vcvtsi2sd` against 3 packed `vcvtdq2pd`. AArch64 fuses
because it has 32 SIMD registers, and the same kernel there needs 6 stack
accesses against 14 inside the x86-64 loop alone.

Also correct which change the two levels gain from. It is the batched loop, not
the precomputed divisor: isolated with `varPopIf`, which stays on the per-row
path, `Decimal32` and `Decimal64` measure the same before and after on both
targets. The divisor matters for `Decimal128`, where it is most of the win.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
Comment on lines +27 to +31
SELECT
round(abs(skewPop(d64) - skewPop(toFloat64(d64))), 10),
round(abs(skewSamp(d64) - skewSamp(toFloat64(d64))), 10),
round(abs(kurtPop(d64) - kurtPop(toFloat64(d64))), 10),
round(abs(kurtSamp(d64) - kurtSamp(toFloat64(d64))), 10)

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.

The only independent oracle here is the toFloat64 cross-check, but it is wired only for d64. d128 takes the distinct buffered big-int conversion path that this PR changes most, and d32 follows a different x86 path than d64, so their rounded reference values are still self-generated by the implementation under review.

That means a width-specific bug can still be blessed by re-recording the .reference file. Please extend the same abs(fn(dX) - fn(toFloat64(dX))) check to at least d128, and ideally d32 as well.

nickitat and others added 3 commits August 7, 2026 19:58
… variant

The justification for buffering on x86-64 rested on two properties that
`x86-64-v4` removes: no packed `int64 -> double`, and 16 `ymm` registers. The
measurements behind it were never checked against a host that has AVX-512, and
`addManyDivided` carried a `_x86_64_v4` variant that nothing could reach, since
x86-64 always buffers.

Checked on a Granite Rapids host, which meets every prerequisite
`getSupportedArchs` lists for `x86_64_v4`, so the dispatch does fire there. The
fused kernel at `v4` is much better than at `v3` - it uses `vcvtqq2pd` on `zmm`
and spills nothing - but it still vectorizes only lanes 0 to 7 and leaves the
other eight scalar, with `vcvtsi2sdq`, `vdivsd` and `vunpcklpd` glue. Buffering
stays ahead: `varPop` over `Decimal32`, 100M rows, single thread, 0.194s against
0.238s, and over `Decimal64` 0.220s against 0.276s. So no x86-64 level wants the
fused shape, and the branch stays a compile-time one.

Since it can never be reached, the multitarget wrapper on `addManyDivided` is
gone. It was emitting nothing anyway - the template is not instantiated on
x86-64, and `USE_MULTITARGET_CODE` is 0 where it is - but it implied a choice
that does not exist.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
It covers plain unary aggregation only. `AggregateFunctionIf` always passes a
non-negative `if_argument_pos` and `Nullable` arguments go through
`addBatchSinglePlaceNotNull`, so both stay on the per-row loop - which the
comment and the changelog entry did not say.

They are not left out entirely. `convertOne` is used by `add`, so `Decimal128`
gains on those paths too: measured on AArch64, 50M rows, single thread,
`varPopIf` goes 1.058s to 0.556s and `varPop` over `Nullable(Decimal128)` goes
2.014s to 1.101s. `Decimal32` and `Decimal64` are unchanged there, 0.187s
against 0.184s and 0.395s against 0.391s, since for them the batched loop is
the whole gain.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
`AggregateFunctionIf` always passes a non-negative `if_argument_pos`, and
`Nullable` arguments go through `addBatchSinglePlaceNotNull`, so both forms sat
on the per-row loop and got none of the batching. They take it now, through the
same tiles and the same lane count: `addManyConditional` off a converted tile
where the target buffers, and a new `addManyConditionalDivided` where it does
not. Measured on AArch64, 50M rows, single thread: `varPopIf` over `Decimal32`
0.196s to 0.180s and over `Decimal64` 0.187s to 0.173s, `varPop` over
`Nullable(Decimal64)` 0.393s to 0.324s.

Wide decimals are excluded from the masked forms, which is the opposite of the
unconditional case. A tile is converted whole and masked afterwards, so it
converts rows the flag then discards - fine while the conversion is an
instruction, but for `wide::integer` it is the dominant cost and doubling it
gave back everything the batching won: `varPopIf` over `Decimal128` went 0.554s
to 1.033s before this was gated. On the per-row path they keep the -47% that
hoisting the divisor already bought them.

The choice of shape still does not change the result: compiling both on x86-64
and diffing the raw bits of the conditional and `Nullable` forms over
`Decimal32` and `Decimal64` gives identical output.

`04696_decimal_variance_conditional` covers the masked forms, which nothing did
- including both flags at once, an all-zero and an all-one mask, and row counts
that span the tile. Verified by mutation: dropping the per-tile offset from the
flag slice is caught. Ran 12 times with settings randomization and 12 without.

Related: #108648

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_017MaihqgmEYC2qDoriB8aa3
@clickhouse-gh

clickhouse-gh Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Dear @nickitat, this PR hasn't been updated for a while. Will you continue working on it? If not, please close it. Otherwise, ignore this message.

This branch has not been deployed

No deployments
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-performance Pull request with some performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants