Skip to content

[GPU] Support aggregation functions - #119502

Open
scanhex12 wants to merge 102 commits into
masterfrom
gpu-sum-aggregation
Open

scanhex12 wants to merge 102 commits into
masterfrom
gpu-sum-aggregation

Conversation

@scanhex12

@scanhex12 scanhex12 commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • New Feature

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

Support sum/min/max aggregation + group by


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

scanhex12 and others added 6 commits September 10, 2026 22:46
`ENABLE_GPU=1` gains libcudf, the RAPIDS dataframe library, which is what
the GPU aggregation in the next commit computes its sums with. The source
list in `contrib/cudf-cmake` is upstream's `add_library(cudf ...)` verbatim;
the dependencies come from ClickHouse's contrib rather than from CPM, and
every compiled target goes through `gpu_island_target`, because ClickHouse's
global compile options do not survive nvcc.

nvcomp is not vendored. libcudf's Parquet and ORC codecs name it
unconditionally and it is a proprietary binary, so `contrib/nvcomp-cmake`
expects an unpacked NVIDIA archive under `contrib/nvcomp` - now ignored by
git - and says where to get it when it is not there.

Three things the island needed beyond the wiring itself:

- `gpu_island_executable` in `cmake/cuda.cmake`, for the two librtcx embed
  generators. CMake links a CUDA-language executable through the host
  compiler, and that link must not see ClickHouse's flags either: lld's
  whole-archive of llvm-libc, and the libc++, libc++abi and
  glibc-compatibility that any ClickHouse target drags in, are all wrong for
  a program compiled against gcc's libstdc++.
- `ch_gpu::stdcxx`, the libstdc++ the island is compiled against. A binary
  carrying both halves holds two standard libraries in disjoint namespaces
  sharing one Itanium ABI runtime - libc++abi's, which `libstdc++.so` binds
  to. Shared rather than static for exactly that reason: a second static
  copy of the ABI runtime would be a duplicate definition, a shared one is
  interposed.
- `__isoc23_strtol` and its siblings, plus `__libc_single_threaded`, in
  `base/glibc-compatibility`. The island compiles against this machine's
  glibc headers and links against the sysroot's 2.31, and libstdc++ inlines
  calls to both.

And two adaptations of cuDF 26.08 to the contrib it meets here. It includes
librtcx's umbrella header flat, as `<rtcx.hpp>`, where `contrib/librtcx` is
newer than the commit cuDF pins and has moved every header under `rtcx/`.
And it calls `ZSTD_findDecompressedSize`, which `zstd.h` declares only
behind `ZSTD_STATIC_LINKING_ONLY` - upstream sets that on its own zstd
target, and the function is in ClickHouse's archive either way.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Everything here was found by building `ENABLE_GPU=1` to the end and running
a query on a Tesla T4, which the previous commit's wiring had never done.

Two of these would have gone unnoticed until someone tried to use the
binary, and both are worth reading before touching this build again.

**The whole server could not throw.** With `libstdc++` anywhere but last on
the link line, the linker binds the executable's `__gxx_personality_v0` to
libstdc++'s definition rather than to libc++abi's, because it takes the
first definition in command-line order. Every frame in the binary then
unwinds through a personality routine that does not recognize a libc++
exception, and a plain `SELECT throwIf(1)` dies with a segfault - not just
the GPU path. The only visible trace is a dynamic relocation against
`__gxx_personality_v0@CXXABI_1.3` where a build without the GPU engine has
none. So the library is appended at the end of `DEFAULT_LIBS`, which is the
one place on the link line that is after libc++abi, and `cmake/cuda.cmake`
no longer offers a target for it.

**CUDA cannot reach a device without `dlopen`.** `programs/main.cpp` - and
`programs/keeper/keeper_main.cpp`, which is linked into the same binary -
define `dlopen` as a stub returning null, deliberately, to keep plugins out
of the process. There is no static driver library to link instead: even
`libcudart_static.a` finds the driver by `dlopen("libcuda.so.1")`, and with
the stub in place it reports that the driver is too old. `USE_GPU` now lifts
the ban the way `USE_OPENSSL_FIPS` already does, which means a GPU build
gives up that protection for the whole binary - one more reason for it to
stay experimental.

The rest is cuDF meeting this contrib:

- `contrib/cuCollections` was pinned to a commit from cuCollections' main
  branch, which had renamed part of the Bloom filter API; cuDF 26.08 wants
  `0883368`, what rapids-cmake's release/26.08 pins. Two compile failures
  were ours, not cuDF's.
- cuDF's format readers and writers - Parquet, ORC, JSON, CSV, Avro and the
  Arrow interop - are no longer built. Nothing reads a file through cuDF: a
  column reaches the device from a `MergeTree` part ClickHouse decoded
  itself. They are a third of the translation units and they do not compile
  here either, for reasons that would each have to be settled against a
  library we do not call: a flatbuffers version baked into cuDF's Arrow IPC
  headers, and an overload ambiguity in cuDF's own ORC statistics header
  under CUDA 13.2. nanoarrow and flatbuffers are no longer needed.
- `io/comp/decompression.cpp` calls `ZSTD_findDecompressedSize`, which
  `zstd.h` declares only behind `ZSTD_STATIC_LINKING_ONLY`.
- `integer_utils.hpp` uses `CUDF_UNREACHABLE` under `__CUDA_ARCH__` without
  including its definition. Upstream never notices: it compiles those
  translation units as C++, where the device branch reaches no compiler.
  Every one of cuDF's .cpp files goes through nvcc here, so the header is
  force-included.
- The two embedded blobs are assembly that pulls bytes in with `.incbin`,
  and clang's integrated assembler looks that file up on the include path
  and ignores `-isystem`. cuDF's compile options are also restricted to the
  sources nvcc compiles, since clang rejects `--expt-extended-lambda` when
  assembling.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`allow_experimental_gpu_aggregation` computes `sum` on a CUDA device instead
of on the CPU: with or without `GROUP BY`, over the fixed-width numeric
types, in a query over a single local `MergeTree` table. Anything else - a
different aggregate function, a `Nullable`, `Decimal` or `LowCardinality`
argument, `ROLLUP`, `CUBE`, `GROUPING SETS`, `WITH TOTALS`, several tables, a
distributed query - is aggregated on the CPU as before. The setting decides
where a supported aggregation runs, never what it returns.

The work itself is cuDF's: `cudf::reduce` with `make_sum_aggregation` when
there are no keys, `cudf::groupby` when there are. There are no kernels of
our own, because a sum is bandwidth-bound and `cub::DeviceReduce`, which is
what cuDF's reduction is, already saturates the device.

Three pieces:

- `src/GPU/GPUAggregationABI.h` is a flat C boundary. The two sides are
  compiled by different toolchains against different standard libraries -
  clang with ClickHouse's libc++ on one, nvcc's gcc host pass with libstdc++
  on the other - so nothing with a C++ ABI may cross it, exceptions least of
  all. `src/GPU/GPUAggregationCudf.cpp` is the cuDF side of it and includes
  no ClickHouse header.
- `src/GPU/GPUAggregation.cpp` stages columns in host memory and sends them
  over in batches of `gpu_aggregation_batch_bytes`. A block of 65536 rows is
  half a megabyte of `UInt64`: a transfer that small spends its time in the
  launch, and the reduction after it never reaches the device's memory
  bandwidth. A keyed partial result stays on the device between batches,
  merged by concatenating it with the next batch's groups and grouping that
  again - `sum` is associative, so the cost is proportional to the number of
  groups rather than to the rows read.
- `GPUAggregatingStep` replaces `AggregatingStep` when the whole aggregation
  is one the device can do. Being a separate step rather than a mode of that
  one has two consequences, and both are why the planner only reaches for it
  when the aggregation is the whole of the query's: the optimizations that
  look for an `AggregatingStep` do not fire, and a plan carrying it cannot
  be serialized to a replica.

Some of it is about matching the CPU's answer exactly rather than about
computing a sum:

- cuDF reduces an integer column into an `Int64` unless the type asked for
  is the column's own, so a `UInt32` column is summed in an `Int64` where
  ClickHouse would use a `UInt64`. The two agree because a batch is capped
  at cuDF's row count and the widest such type still fits: for `UInt32`,
  (2^32 - 1) * (2^31 - 1) < 2^63 - 1. A `UInt64` column is summed in its own
  type and wraps exactly as it does on the CPU.
- cuDF's groupby has no output type at all, so a `Float32` value column is
  widened on the device - ClickHouse's `sum(Float32)` returns a `Float64` -
  while the host copy stays four bytes a row.
- Float `GROUP BY` keys are not eligible. ClickHouse groups a `Float64` by
  its eight bytes, so `0.0` and `-0.0` are two groups; cuDF's hash groupby
  compares float keys with IEEE equality and makes them one. That is a
  different number of output rows, not a slower path.

`sum` over a float column does add the values in a different order than the
CPU does, so the last bits can differ. The setting documents it, and the
tests use data whose sums are exact in a double either way.

Measured on a Tesla T4, 200 million `UInt64` rows: the CPU takes 0.43 s and
the device 0.91 s, of which 0.36 s is the transfer and the reduction. This
path is bounded by the PCIe link, which is narrower than the CPU's own path
to memory, so it is expected to lose - what it buys is the path itself. The
speed is meant to come from keeping columns in device memory between
queries, which this does not do yet, and `GPUAggregationRows`,
`GPUAggregationBatches` and `GPUAggregationMicroseconds` say what a query
actually sent over.

Both tests compare the device's answer against the CPU's, and where there is
no device they compare the CPU with itself, which is what makes them
runnable in CI. On a machine with a T4 they are 65 real comparisons.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`join_algorithm = 'gpu_hash'` runs an `ALL INNER JOIN` on one integer key
through `cudf::hash_join`. It plugs in as an `IJoin`, so it needs no plan
step and no plan serialization of its own, and it is never chosen unless
asked for by name.

Only the left block's key column crosses the link. What comes back is one
row index per matching pair, and the left table's own columns are indexed on
the host with it - `IColumn::index`, the same call the CPU's hash join
finishes with. Only the right table's payload is gathered on the device and
copied back. The right key columns are not read back at all: an `INNER JOIN`
on equality between two columns of the same type makes a matched pair's keys
equal, so the right key is the indexed left key.

It is correct and it is slower than the CPU, which is the point of measuring
it. On 100 million left rows against 10 million right rows, `parallel_hash`
takes 0.87 s and this takes 1.54 s, of which 1.45 s is inside the device
section. The same probe and gather in one call take 0.35 s; in the 1529
blocks a pipeline actually hands a join, 0.53 s; the rest is latency, six
device operations and two synchronizations per block. Raising
`max_block_size` recovers 7%, because the read still hands the join many
parallel streams of modest blocks and they all queue on the one device.

Even a perfectly batched probe would only reach parity here: 0.17 s to send
the keys, 0.35 s to join, 0.25 s to bring the result back, against the CPU's
0.87 s. The 2x that a device-resident measurement shows comes from the
result never leaving the device. So this is worth having as the operator it
is, and the thing that would make it pay is the same thing the aggregation
wants: columns that are already on the device, and a consumer that is there
too.

`GPUJoinBuildRows`, `GPUJoinProbeRows`, `GPUJoinMatchedRows` and
`GPUJoinMicroseconds` in `system.events` say what a query actually did.

The test compares the device's answer with the CPU's across 48 shapes, and
where there is no device it compares the CPU with itself, which is what
makes it runnable in CI.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This is the piece the earlier commits were measuring their way towards.
`gpu_column_cache_size` gives the server a cache of `MergeTree` column data
held in GPU memory, and a plan pass answers a keyless `sum` from it: on a
hit the query reads no file, decompresses nothing and sends nothing over the
link.

Measured on a Tesla T4 over 200 million `UInt64` rows in one part:

- the CPU takes 0.35 s, of which the sum itself is about 0.06 s and the rest
  is reading and decompressing;
- a cache hit takes 0.008 s, 44 times faster, and `system.events` shows why:
  no bytes uploaded, not one file opened, no rows read;
- filling the cache takes 5.1 s, so the path pays for itself after about
  fifteen queries over the same data.

With the same rows spread over 80 parts the fill drops to 1.6 s, because
parts are read in parallel, and a hit rises to 0.016 s, because each part
costs a device call of its own. Both of those are where the next work is:
fill a part with several readers rather than one, and reduce all of a
column's parts in one call instead of per part.

Why it needs no invalidation protocol: a part is immutable, so a cache entry
holds the `DataPartPtr` it was filled from and a lookup is a hit only when
that is the same object the query is about to read. A merge, a mutation or a
TTL cannot make a cached column stale because the part it belongs to is
still exactly itself; what they do is produce different parts, which miss.
The price is that a cached entry pins its part's files until eviction.

The plan pass is the narrow part, and deliberately so: everything it cannot
prove, it refuses. It takes a `GPUAggregatingStep` with no keys over
`UInt64`, `Int64` or `Float64` columns - the three types whose `sum` returns
the column's own type, so the source step's header is the read step's
unchanged and the aggregation above it does not have to change. It descends
through the planner's renaming expression while proving that every summed
column is passed through and not computed, and refuses a filter, `PREWHERE`,
a row policy, sampling, `FINAL`, a lightweight delete, a pending mutation, a
part read in less than its entirety, a read limit that would fire on a miss
but not on a hit, and a dozen more. Each refusal says which one it was at
trace level, because `EXPLAIN` shows the plan that was kept and never the
check that kept it.

`gpu_column_cache_size` is 0 by default, so nothing reserves device memory
unless asked. Device memory is outside every limit the server knows about,
which makes that setting the only bound there is.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@scanhex12
scanhex12 marked this pull request as draft September 11, 2026 17:09
@scanhex12 scanhex12 changed the title [GPU] Support sum aggregation [GPU] Support aggregation Sep 16, 2026
@scanhex12 scanhex12 changed the title [GPU] Support aggregation [GPU] Support aggregation functions Sep 16, 2026
scanhex12 and others added 6 commits September 16, 2026 17:23
`cmake/ccache.cmake` set only the C and C++ launchers, so nothing nvcc
compiles was ever cached and every new build directory recompiled all of
cuDF. Measured on one of its translation units: 129.40 s cold against 0.08 s
on a hit.

Not in depend mode, unlike C and C++. That mode reads the compiler's
dependency file, CMake drives nvcc with no dependency flags at all, and
without such a file ccache stops caching rather than merely slowing down: on
the same unit it reports an error, takes no hit, and the second compilation
costs the full 132 s.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`src/GPU/GPUAggregationCudf.cpp` calls four cuDF entry points - `cudf::reduce`,
`cudf::groupby`, `cudf::cast` and `cudf::concatenate` - while the source list
is upstream's whole library: every join, every string and list operation, the
whole of IO. The linker takes what it needs from the archive and leaves the
rest, but nvcc has compiled all of it by then, and that is the larger part of
a cold GPU build: 212 of 469 translation units, 6.5 of the 16.6 CPU-hours cuDF
costs. `join/` alone is 2.3 of it, and the GPU join those sources were there
for no longer exists.

The excluded set is derived rather than picked: it is every archive member
outside the transitive closure of the island's undefined symbols, which is the
linker's own member-selection algorithm, so no member of it can be reached by
any link. Checked two ways - no retained member references a symbol that only
an excluded member defines, and recomputing the closure the way a linker
actually resolves a multiply-defined weak symbol (first definer in archive
order, strong definitions preferred) gives the same 201 members. So what stays
is genuinely needed: `binaryop/compiled`, at 3.6 CPU-hours, really is reachable
from `cudf::reduce`.

Ten members are kept despite being outside the closure, because their basename
is not unique in the list - `concatenate.cu` exists under both `copying/` and
`lists/` - and an archive names members by basename, so the analysis cannot
tell the two apart. All ten fall outside the closure, so they compile but never
link.

Upstream's list itself is untouched, so a version bump stays a diff against it,
and the exclusions are applied to it afterwards.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). label Sep 16, 2026
@scanhex12
scanhex12 marked this pull request as ready for review September 17, 2026 09:09
scanhex12 and others added 3 commits September 18, 2026 11:38
The build-system half of this work - `cmake`, the cuDF and nvcomp `contrib`
targets, the `glibc-compatibility` aliases the island needs and the `dlopen`
override it lifts - is its own change, on `gpu-build-island`. Reverting it here
leaves this pull request the aggregation code and its tests.

`ENABLE_GPU` is `OFF` by default, and everything added under `src/GPU` and
`src/Processors` is behind `USE_GPU`, so a default build is unaffected either
way. Building with `-DENABLE_GPU=1` needs both changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The CUDA runtime reaches a device only through `dlopen`, so a build with the GPU
engine cannot keep the stub that tells the process there are no shared libraries
to load. Both translation units defining it are here.

These two guards read `USE_GPU`, which `src/Common/config.h.in` defines, so they
belong with that definition rather than with the build island in
#120803 - the island alone has no
`USE_GPU` and `-Wundef -Werror` rejects the bare use.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
scanhex12 added a commit that referenced this pull request Sep 18, 2026
`programs/main.cpp` and `programs/keeper/keeper_main.cpp` read `USE_GPU`, which
`src/Common/config.h.in` defines - and that file is in
#119502, not here. Without it the
macro is undefined, and `-Wundef -Werror` fails the bare use, which is what the
Fast test and `Build (arm_tidy)` reported on `programs/main.cpp:262` and
`programs/keeper/keeper_main.cpp:103`.

Both files now go with that definition instead. Nothing left here reads
`USE_GPU`; everything is behind `ENABLE_GPU`, which cmake defines itself.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
PedroTadim pushed a commit to groeneai/ClickHouse that referenced this pull request Sep 19, 2026
…bing

Splits the build-system half of ClickHouse#119502 out of it, so that the pull request
there is the aggregation code and its tests alone.

What is here:

- `cmake/cuda.cmake`: the include half of `ch_gpu::cudart`, which every consumer
  of `ch_contrib::rmm` needs; `gpu_island_executable`, for the build-time tools
  on the island; and the shared `libstdc++` the island's host code is compiled
  against.
- `cmake/linux/default_libs.cmake`: where that `libstdc++` is appended, and why
  the order matters for the Itanium ABI runtime.
- `cmake/ccache.cmake`: a compiler launcher for `.cu` as well.
- `contrib/cudf-cmake`, `contrib/nvcomp-cmake`, `contrib/CMakeLists.txt`: cuDF
  and nvcomp as `ch_contrib::` targets.
- `contrib/cucascade`, and the `cuCollections` bump it needs.
- `base/glibc-compatibility`: the `__isoc23_strto*` aliases and
  `__libc_single_threaded`, which the island needs because it compiles against
  the host's headers and links against the sysroot's glibc.
- `programs/main.cpp`, `programs/keeper/keeper_main.cpp`: the `dlopen` override
  lifted in a GPU build, because the CUDA runtime reaches a device no other way.
- `.gitignore`: nvcomp is unpacked into `contrib/nvcomp` rather than vendored.

`contrib/cucascade` was a gitlink with no `.gitmodules` entry, so
`git submodule update --init` could not fetch it. Added it here.

`ENABLE_GPU` stays `OFF`, so nothing in a default build changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
scanhex12 and others added 3 commits September 19, 2026 17:14
`join_algorithm = 'gpu_hash'` runs an `ALL INNER JOIN` on one integer key
through `cudf::hash_join`. It plugs in as an `IJoin`, so it needs no plan step
and no plan serialization of its own, and it is never chosen unless asked for
by name.

Whether it pays depends on the size of the result, not on the size of the
tables, and it depends on it steeply. Measured on a Tesla T4 against
`parallel_hash` on 16 cores, with both tables held at 100 million and 10
million rows and only the number of matching pairs varied:

    matches      GPU     CPU
    0           0.67s   1.01s
    1000        0.68s   0.99s
    100000      0.72s   1.02s
    1000000     0.68s   0.98s
    10000000    0.77s   0.89s
    20000000    0.82s   0.91s
    50000000    1.05s   0.97s
    100000000   1.40s   1.04s

The device's time is flat up to ten million pairs, because what dominates is
sending the left table's keys and nothing comes back; past that it grows with
the result, because every matching pair returns four bytes of index and eight
of payload. The crossover is at a result of roughly a third of the left table.
With the result ten times the left table the device is 1.84x slower. So the
algorithm is worth having where a join filters, and the thing that would fix
the other end is a consumer that reads the result where it already lies.

The transfers go through `GPU::UploadPipe`, which stages into pinned host
memory and uploads asynchronously; `GPU::ColumnBuffer` is the device-resident
result, and the aggregation reduces out of one instead of out of host bytes,
so `clickhouseGPUReduceCompressed` and its second decoding path are gone.
Pinned memory is what makes `cudaMemcpyAsync` actually asynchronous, so the
staging buffer may not be reused until the copy has drained - the pipe keeps
two of them and waits on a CUDA event rather than on the whole stream.

The boundary between ClickHouse and the cuDF island is now ordinary C++ in
`namespace DB::GPU` rather than `extern "C"`: a function whose signature holds
no `std::` type mangles identically under libstdc++ and libc++, which is what
lets one side call the other. What still cannot cross is an exception, so the
entry points report failure through a buffer, and `GPU::call` hides that from
their callers.

`GPUJoinBuildRows`, `GPUJoinProbeRows`, `GPUJoinMatchedRows` and
`GPUJoinMicroseconds` in `system.events` say what a query actually did.

Related: #116807

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
# Conflicts:
#	src/Common/ErrorCodes.cpp
#	src/Core/SettingsChangesHistory.cpp
…d grouping, raw upload

A keyed `GROUP BY` on the device keeps the accumulators of a group in one
record beside a `cuco::static_set` of keys (`RecordGroupBy`), and the
`GPUAggregatingStep` above a `ReadFromGPUCompressedColumns` passes the
already grouped rows through instead of grouping them again.

A `PREWHERE` of comparisons, `and`, `or` and `not` over numeric columns
is compiled into a small stack program (`GPUFilterCompiler`) and
evaluated in the grouping kernel, with its columns read as a third
column group beside the keys and the values.

A chunk whose groups are few next to its rows may be grouped in two
passes, sorted into buckets and grouped in shared memory, when the
direct kernel is measured to cost more than the link does per row.

Columns that compression does not halve are expanded on the host and
sent as they are (`gpu_aggregation_device_decompression_max_ratio`,
default 0.5), by as many reading threads as `gpu_aggregation_readers`
says or a quarter of the cores.

`GPUGroupByKernelMicroseconds` tells the kernels' own time from what
they waited for. New tests: 05232-05235.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The compiler of the device converted a string or `Decimal` constant compared
with a column to the column's type, in a copy of the `ActionsDAG` changed in
place, with the comparison rebuilt for it, so that it compiled. That is a gap of
the CPU's JIT, which compiles no such comparison either, and is to be closed
there, for both. Until then, such a predicate is evaluated on the CPU.

`05455` is of the alias alone now, and `05447_gpu_filtered_read` writes the date of its string conjunct's query as a date.

The previous commit, of the same title, renamed the test only: these are its changes.
It is done, and for more types, by
#128974, which the device's
expressions are to take once it is merged. Until then, a predicate with a
comparison of dates is evaluated on the CPU.

`05447_gpu_filtered_read` checks the plans of reads filtered by numbers rather than by dates.
The cache was a static allocated once and never destroyed, so that the kernels
it kept were not unloaded at the exit of the process, after CUDA is gone. Now
`GPUKernel` and `GPUKernelCache` are of their own, and `GPUDevice`, which the
global `Context` holds and destroys at the shutdown of the server, holds the
cache: the kernels are unloaded after the device is waited for, while it is
there.
The CPU's JIT registered the host's target under a `std::call_once` of its own,
and the compiler of the device's expressions NVPTX under another, so that the
first compilation of each could register into the registry of LLVM, which is not
synchronized, at once, or look a target up while the other registered one.
`initializeLLVMTargets` registers both under one, and both call it before they
look up a target.

From the review of #129288.

Also, the comments of the files of the device's expressions and of their kernels are removed.
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

`GPUExpression` and `GPUExpressionInputs`, which go between the code of
ClickHouse and that of the GPU built against another standard library, held
arrays of 16 column types and columns, so that an expression of more columns was
refused, for no limit of the device's. They are views now: of the column types
that the `GPUKernel` keeps, which the kernel was compiled for, and of the
columns that whoever runs it keeps. A launch takes its arguments in a vector.

In this branch, `GPUDerivedValue::columns` is a `GPUSpan` of the indices that the step's `DerivedColumn` keeps, and `05457_gpu_filter_of_many_columns` filters by 20 columns on the device.
… a target machine for each thread

From the review of #129288: an
expression of integers wider than 64 bits, which every function of it compiles
for the CPU, as `toFloat64(toUInt128(a) * toUInt128(b))`, made NVPTX convert an
`i128` to a double by a call of a library that the device does not have, and LLVM
aborted the server with "unsupported library call operation". The code of a
kernel, once optimized, is refused where an instruction is of an integer wider
than 64 bits, or of a float other than a `float` or a `double`, before NVPTX
emits it.

The `TargetMachine` of NVPTX is made once for each thread that compiles, rather
than for every kernel, as one is not used by several threads at once.

`05458_gpu_expression_of_wide_integers` runs that expression as the argument of an aggregate and in a predicate.
And the `IRBuilder` of `emitKernel` is `builder`.
…ads, not only a `Float64`

An expression that was not a predicate had to be a `Float64`, as the arithmetic
of the interpreter before the JIT was in doubles. Its kernel writes the value of
its own type now, of any fixed width the device reads, and
`GPUExpression::value_type` says which: `GPUExpressionResult::Float64` is
`GPUExpressionResult::Value`. `CompiledGPUExpression::result_type` is the type of
the expression in ClickHouse.

In this branch, an aggregate's computed argument is of the type of its expression, of columns of any fixed width, rather than a `Float64` of stored `Float64` columns: `sum(a * b)` of integers is grouped on the device. `05459_gpu_group_by_derived_values_of_integers` covers it, and `05245_gpu_group_by_strings` reads `sum(toFloat64(i))` from the compressed columns, compared with the CPU.
Blargian pushed a commit to Blargian/ClickHouse that referenced this pull request Nov 10, 2026
…to PTX

The device evaluates a predicate or an expression over the columns of a row
with the code that the functions of ClickHouse compile into for the CPU, rather
than with a second implementation of their semantics.

`GPUExpressionCompiler` builds the `CompileDAG` of an output of `ActionsDAG`,
as the CPU's JIT does, and emits a kernel around `CompileDAG::compile`, a thread
for each row, that LLVM's NVPTX target turns into PTX for the device's
architecture. An expression with a function that does not compile, or with a
`Nullable` column, is refused, with the reason. A predicate's kernel writes the
null mask of cuDF directly, by `vote.ballot.sync`; an expression's kernel writes
a `Float64` for each row. The PTX is kept by the hash of the expression, and
`GPUExpression.cpp` loads it once, with `cudaLibraryLoadData`, and runs it with
`cudaLaunchKernel`.

- A string or `Decimal` constant compared with a column is converted to the
  column's type and the comparison rebuilt for it: `d < '1994-01-01'`.
- `FunctionComparison` compiles a comparison of two dates of the same type,
  `Date`, `Date32` or `DateTime`, as the integers that hold them, which the CPU's
  JIT gains as well.
- The bundled LLVM builds its NVPTX target with `ENABLE_GPU`, which now requires
  `ENABLE_EMBEDDED_COMPILER`.

Related: ClickHouse#119502
Related: ClickHouse#128777
@clickhouse-gh

clickhouse-gh Bot commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

Dear @rienath, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

…ice might not fit

`CudfGroupBy::group` asked `distinct_keys` before every slice, which waits for the device. A bound on the host, the
groups at the last ask plus the rows grouped since, decides whether a slice might not fit, and only then is it asked.
This reverts commit ae3f216: without the comparisons of dates the device refuses the
`PREWHERE` of TPC-H Q1, Q6 and Q12, and `GDeflate` is expanded on the CPU instead.
A reader of a part on S3 waits for responses most of the time. Over cold TPC-H SF100 on S3, Q6 took 8.8 s with 4
readers and 3.6 s with 16.
With 12 or 16 readers TPC-H Q1 over S3, of seven columns, ran the 22 GiB of an A10G out of memory; with 8 it took 4.5 s,
and Q6 3.6 s against 3.3 s with 16.
…4 GiB

The runs gathered stay on the device until they are combined, and combining concatenates them into a copy as large:
`GROUP BY l_returnflag, l_linestatus` over TPC-H SF100, of 4 groups but runs of a fourth of its rows, took 10.7 GiB of
the device with one reader, and 2.7 GiB now.
…part

Rows are grouped once every column of a reader has them, and a column of varying width only up to where its bytes are on
the device. A piece of a column was handed over at 32 MiB of decompressed bytes: of `l_returnflag`, a byte a row, that
is 33 million rows, which every other column of the reader then kept on the device as well. And the device thread
handed over one reader's rows per expansion, while an expansion brings rows to many readers, so that their columns grew
until the device ran out of memory: TPC-H Q1 over S3 did with 12 readers.

A piece is handed over at about a batch of rows of its column, every reader's rows ready are handed over after each
expansion, and a reader hands over a whole batch rather than a share of one, as small batches cost more in calls into
cuDF than their rows. Q1 with 16 readers takes 16 GiB of the device at most.
…ader holds a batch on the device

Over cold TPC-H SF100 on S3, with 8 readers against 16: Q6 5.7 s against 2.6 s, Q12 5.8 s against 2.7 s, Q14 5.5 s
against 3.1 s.
…s Sirius schedules its pipelines

Each reading thread is a worker that does all of a batch itself on a CUDA stream of its own: it uploads its
compressed blocks, nvcomp expands them straight into the batch's columns (a `CompressedPiece` now has a
`destination` of its own), and it waits for the device where it must, as for how many rows of a column of strings
it has. It then groups the batch in the first free of up to 8 lanes, each a `CudfGroupBy` on a stream of its own.
`CudfGroupBy::absorb` merges the lanes into one at the end, and the lanes reduce their batches alike, as the first
batch decided, so that they merge.

Before, one device thread expanded every reader's blocks into per-reader columns, copied the rows ready in every
column to one grouping thread, and that thread grouped every batch through one `streaming_groupby`, with about ten
waits for the device a batch inside cuDF: the device was idle 28% of a warm TPC-H Q1, and the device thread, the
readers and the copies all waited for the grouping thread. Now a thread that waits leaves the device to the
others: the device is idle 13% of Q1, the copies on the device are 3 GB instead of 157 GB over three runs, and the
host memory of Q1 is 4.9 GB instead of 16.5 GB.

Warm TPC-H SF100 on an A10G, 16 readers, best of three: Q1 1.66 s -> 1.37 s, Q6 0.84 s -> 0.61 s, Q18 1.26 s ->
1.19 s; the CPU over ZSTD takes 4.27 s, 1.66 s and 3.56 s.

The device thread, the grouping thread, the expansion slots, the per-reader columns with their checkpoints of
offsets and the staging budget of `GroupByGPUAccumulator` are gone, which keeps only the plain columns of
`GPUAggregatingTransform`.
…without their `what`

The binary holds libstdc++ for the device code and libc++ for the rest, whose
`std::logic_error::what` and `std::runtime_error::what` have the same symbol. The
linker keeps the one of libc++, which reads the message where the exceptions of
libc++ keep it, past the end of an exception of libstdc++. So `guarded` read a
wild pointer for any `cudf::logic_error`, and the server died of a segmentation
fault instead of throwing. `messageOf` reads the message from where libstdc++
keeps it.
…merging into it

`streaming_groupby` takes others to merge only once it has taken a batch. A grown
one, made by `absorb` when the groups of two lanes do not fit, had taken none, so
`merge` threw. It happened where a lane had grouped no batch, which the GPU tests
`05232`, `05235`, `05245`, `05442` and `05443` hit. A grown one now first takes a
row of the first slice its lane grouped, whose first key is null, which
`streaming_groupby` leaves out as it does the rows a `WHERE` leaves out.
… lanes that split their groups by the keys

The read was one source with reading threads of its own, which did everything
inside. It is now a pipeline of ordinary processors:

    GPUCompressedBlocks ×N -> GPUUpload ×N -> Resize N -> L -> GPUGrouping ×L
        -> Resize L -> 1 -> GPUSplitLanes -> Resize 1 -> P -> GPUMergePart ×P

- `GPUCompressedBlocks` is a plain `ISource`: it reads a part with
  `MergeTreeCompressedColumnsReader::readNext`, which reads one block at a time,
  and emits the compressed blocks staged in pinned memory, a batch per chunk
  (`GPUBlockStager`). It does not use the device.
- `GPUUpload` sends a batch to the device and expands it with nvcomp, and carries
  the tails of the columns to the next batch (`GPUBatchUploader`).
- `GPUGrouping` is a lane: a CUDA stream and a `CudfGroupBy` (`GPUGroupingLane`).
  The resize hands a batch to the first lane that is free, which replaces the
  queue of free lanes. A batch moves to the lane's stream through an event.
- As Sirius does, a lane reduces each batch into partial results with a groupby
  of cuDF and splits them by a hash of the keys into P parts
  (`CudfGroupBy::splitIntoParts`), so that no hash table grows over the batches.
  `GPUMergePart` merges one part of every lane on a stream of its own
  (`CudfGroupBy::absorbPart`): the keys of the parts differ, so the parts are the
  groups and go downstream as P chunks.
- With an `avg`, whose partial results do not combine, or without keys, the
  lanes are merged into one by `GPUMergeGroups`, which now grows the lane with
  the most groups once for the groups of all (`CudfGroupBy::reserveGroups`)
  instead of once per lane merged into it.

`cudf::hash_partition` is built again (`src/partitioning/partitioning.cu`).
`GPUReadersWaitMicroseconds` and the `GPUReader` thread name are gone with the
reading threads.

Warm, TPC-H SF100 on an A10G, the aggregations of TPC-H over one table, best of
three, GPU over `lineitem_gd` (`GDeflate`) against the CPU over `lineitem` (LZ4):
the `GROUP BY l_partkey, l_suppkey` of Q20 (54.5M groups) went from 1.77 s to
0.81 s (CPU 1.17 s), the `GROUP BY l_orderkey HAVING` of Q18 from 0.90 s to
0.66 s (CPU 2.95 s); Q1, Q6, the view of Q15 and the `avg` of Q17 are as before.
Cold over S3, Q12 and Q14 got faster (4.7 s to 4.4-4.6 s, 4.7 s to 3.9-4.1 s), as
reading no longer waits for the device.
…of S3, fewer classes

- `CudfGroupBy` reduces each batch into partial results (an `avg` as a `sum` and
  a `count`, divided at `finalize`) split by the keys into parts, which others
  merge by `absorbPart`. The first batch picks how: runs of mostly distinct keys
  by a sorted groupby, few groups by one `streaming_groupby` that never grows
  (it goes into the parts when full), otherwise a hash groupby per batch. Its
  interface is `addBatch`, `absorbPart`, `finalize`, `filterGroups`, `key`,
  `value`; collecting rows without aggregates is `CudfRowCollector`. Gone:
  `absorb`, `reserveGroups`, the shared decision, `GPUMergeGroups`.
- The read prefetches every column of a part on a remote disk after each piece,
  opens the next part ahead and prefetches its start, reads at least 4 MiB at a
  time, and uses 32 readers on remote disks instead of 16. Cold over S3, Q1 took
  3.0 s instead of 4.5 s, and the `GROUP BY` of Q15 and of Q20 went from slower
  than the CPU to 2.5 s and 2.6 s against 2.9 s and 3.0 s.
- `GroupByGPUAccumulator` is the pipes of plain columns and a `GPUGroupingLane`;
  the old upload of compressed blocks (`CompressedUploadPipe`, `IUploadPipe`,
  `SyncDecompressor`, `AsyncDecompressor`) and the compressed path of
  `GPUAccumulator` are gone, as nothing used them. `evaluateMask`, `keptRows` and
  `deviceViewByBits` are helpers of `Cudf.cuh`.
@clickhouse-gh clickhouse-gh Bot added comp-gpu GPU execution: columns on the GPU, upload and decompression, expression compilation to GPU kernel... and removed comp-aggregation GROUP BY / aggregation framework (hash tables, spilling, external aggregation). labels Nov 19, 2026
`GPU_EXP_ASYNC_DEPTH`: `GPUBatchUploader::upload` does not wait for its batch; the staged memory is held and the
decompression checked when that many more batches were sent, or at `drain`.
`GPU_EXP_EAGER`: the lanes hand their parts to a merger of each part as they read, so that `GPUMergePart` finishes
only what is left.
`GPU_EXP_THREADS`: a `Resize` to that many streams after `GPUUpload`, for more threads of the pipeline than sources.
None paid: on S3, uploads that do not wait were 0.85-1.02x and raced with more threads of the pipeline; those threads
gave 0.95-1.05x; one part instead of one per lane lost 8% on A17 and 25% on A18.
… say the message of a standard one

A libstdc++ exception destroyed at the end of the `catch` binds to the destructor of libc++, which crashed the server on
a `std::overflow_error` of `streaming_groupby` (signal 11 in `__cxa_end_catch`). It is leaked now, as in the GPU
aggregation pull request, and the message of a `std::runtime_error` or a `std::logic_error` is read past its vtable.

This branch was successfully deployed

1 active (outdated) deployment
staging - docs — 121f7f22 Deployed Oct 21, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-gpu GPU execution: columns on the GPU, upload and decompression, expression compilation to GPU kernel... pr-feature Pull request with new product feature submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants