Repository navigation
Conversation
|
Workflow [PR], commit [19ce464] Summary: ❌
AI ReviewSummaryThis PR speeds up the simple Findings💡 Nits
Tests
Final Verdict
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 34/42 (80.95%) · Uncovered code |
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]>
1955835 to
3b4cb11
Compare
…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]>
2c39c2b to
ccef40f
Compare
…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]>
a63f549 to
c5e7a07
Compare
…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]>
78bbca0 to
8d9efe7
Compare
`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]>
`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]>
|
📊 Cloud Performance Report ✅ AI verdict: 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. clickbenchFlagged queries (2 of 43)
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
|
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 52/52 (100.00%) · Uncovered code |
-ffp-contract=fast -freciprocal-math to variance/stddev and avgWeighted|
@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
Done — merged
|
|
|
…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
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
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
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
3edb3c2 to
464de71
Compare
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
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. |
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
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
| 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) |
There was a problem hiding this comment.
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.
… 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
|
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. |
The "simple" statistics aggregate functions got a vectorized accumulation path in #110461, but
only for non-
Decimalarguments. ADecimalcolumn stores unscaled integers - the scale belongsto the data type, not the column - and the kernel has no way to apply it, so
Decimalstayed onthe generic per-row loop, which additionally called the out-of-line
convertFromDecimalonce pervalue.
varPop,varSamp,stddevPopandstddevSampnow take the vectorized path overDecimaltoo,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:
vector: 40 packed ops, no calls, 6 stack accesses for
Decimal64. So the division rides alonginside the loop and nothing is copied.
ymmand does not. Its fused loop spills every iteration and the vectorizer dropsto a mix of two-wide and scalar glued with shuffles - 11 scalar
vcvtsi2sdagainst 3 packedvcvtdq2pd, 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::integerhas no conversion instruction at all and lowers to soft-float quad calls, whichclobber 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,skewPopandkurtPopoverDecimal32,Decimal64and
Decimal128gives identical output.skewPopandkurtPopdeliberately stay on the per-row path. They carry two more moments perlane, 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:
varPop,varSamp,stddevPopoverDecimal32varPop,varSamp,stddevPopoverDecimal64varPop,varSamp,stddevPopoverDecimal128skewPop,kurtPopoverDecimal64varPopoverFloat64(control)Decimal128gains most, and mostly for a reason unrelated to the accumulation.convertFromDecimalevaluates
static_cast<Float64>(value) / static_cast<Float64>(scaleMultiplier<Int128>(scale)), so itconverts a 128-bit wide integer to
doubletwice per row - once for the value and once to re-derivea divisor that never changes.
convertOnecomputes the divisor once, in the constructor. Measured onvarPopoverDecimal128, 50M rows, single thread, on both targets: x86-64 goes 0.517s to 0.251swith 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
Decimal32andDecimal64the hoisting is worth nothing - isolated withvarPopIf,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 qand runsscvtf v.2d,fdiv v.2d,fmul v.2dandfadd v.2d, with no store and reload of a buffer.Scope
The batched path covers plain unary aggregation and the masked forms - the
-Ifcombinator andNullablearguments - for types narrower than 128 bits. Measured on AArch64, 50M rows, singlethread:
varPopIfoverDecimal32varPopIfoverDecimal64varPopoverNullable(Decimal64)varPopIfoverDecimal128varPopoverNullable(Decimal128)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::integerit is the dominant cost and doublingit gave back everything the batching won, 0.554s to 1.033s on
varPopIfoverDecimal128. Theystill gain there, from the hoisted divisor rather than the batching.
The two-argument kinds -
covarPop,covarSamp,corr- and the higher moments stay on theper-row path everywhere.
Coverage
00700_decimal_aggregateschecks variance and stddev overDecimalbut nothing checks the highermoments, and the performance test never compares output, so
04695_decimal_skewness_kurtosiscovers
skewPop,skewSamp,kurtPopandkurtSampoverDecimal32,Decimal64andDecimal128at 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_conditionaldoes the same for the masked forms, including bothflags at once, an all-zero and an all-one mask.
Result change
One value in
00700_decimal_aggregatesmoves:varPopover theDecimal128column is now34rather than
34.00000000000001. The partial sums accumulate less rounding error than thesequential loop, so the result lands on the exact value.
Related: #110461
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
varPop,varSamp,stddevPopandstddevSampare now faster overDecimalandDateTime64arguments. Plain aggregation is 20-25% faster forDecimal32andDecimal64on x86-64 and about twice as fast forDecimal128on both x86-64 and AArch64. The-Ifcombinator andNullablearguments are faster too - around 8% forDecimal32andDecimal64, 18% forNullable(Decimal64)and about 45% forDecimal128.