Skip to content

[GPU] Use JIT to compile expressions into NVPTX - #129288

Merged
scanhex12 merged 16 commits into
masterfrom
gpu-expression-jit
Nov 10, 2026
Merged

scanhex12 merged 16 commits into
masterfrom
gpu-expression-jit

Conversation

@scanhex12

@scanhex12 scanhex12 commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Slop description:

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: #119502
Related: #128777

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Human description: I need to translate ActionDAG, etc to CUDA. There are 2 ways: 1) write CUDA code again 2) use our JIT infrastructure and convert it into NVPTX. Doc: https://llvm.org/docs/NVPTXUsage.html


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

Version info

  • Merged into: 26.11.1.1865-master (included in 26.11 and later)

…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: #119502
Related: #128777
@scanhex12
scanhex12 marked this pull request as draft November 4, 2026 14:20
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7fe2cdf]


AI Review

Summary

PR #129288 adds an experimental GPU expression compiler using the existing CPU JIT lowerings, CUDA kernel loading and launching, and a bounded kernel cache with reloadable limits. Reviewed head: 7fe2cdf79868825f0573b1300352f218f95dd6b9. The earlier eviction allocation bug is fixed. No new inline findings; execution coverage remains insufficient for approval.

Missing context / blind spots
  • ⚠️ No CUDA toolkit, device, or configured ClickHouse build is available here, so device execution and concurrent kernel unloading could not be validated. A GPU-enabled build and focused execution results would close this gap. The Praktika report supplies no GPU execution evidence; the configured CI jobs do not enable ENABLE_GPU.
Findings

⚠️ Majors

  • src/GPU/GPUExpression.cpp:24 — GPU/CPU result equivalence has no execution coverage. [dismissed by author -- https://github.com/[GPU] Use JIT to compile expressions into NVPTX #129288#discussion_r4470355942] The author silently resolved the earlier coverage thread; it stays resolved. The concern remains because compileGPUFilter, compileGPUExpression, and evaluateGPUExpression still have no callers outside their implementation and no tests exercise generated kernels, argument passing, or either output layout. Existing CPU tests cannot detect incorrect predicate masks or numeric device results. Add a small direct API harness while SQL integration is absent.

💡 Nits

  • PR description — The description still promises string/Decimal constant conversion and compiled date comparisons, although those changes were removed. It also says value kernels always produce Float64, whereas they now write their supported result type. Remove the obsolete bullets and describe value output as its own fixed-width type. Not for changelog is appropriate for this internal groundwork and does not require a changelog entry.
Tests
  • ⚠️ Run a GPU-enabled harness comparing predicate masks and integer/Float32/Float64 values with CPU results, including row counts around a warp boundary and refusal of unsupported/Nullable inputs. Include the previously reported wide-intermediate expression to prove it is refused without terminating the process.
  • ⚠️ Exercise cache eviction and resizing while another expression retains a kernel, then release the final owner after stream synchronization. Verify that retirement allocates nothing and unloading occurs outside the cache mutex.
Final Verdict

Status: ⚠️ Request changes. Supply focused GPU execution and cache-lifetime evidence. Existing dismissed threads were left closed, and no duplicate inline comments were posted.

@clickhouse-gh clickhouse-gh Bot added pr-not-for-changelog This PR should not be mentioned in the changelog submodule changed At least one submodule changed in this PR. labels Nov 4, 2026
…DAG`

The compiler of the device walked the `ActionsDAG` of an expression on its own
to build the `CompileDAG`. Now it takes it with `getCompilableDAG`, which the
CPU's JIT takes it with, made public in `CompileDAG.h`, and only checks that
what does not compile, the inputs it leaves, are columns that the device reads.

The string and `Decimal` constants that comparisons convert are converted in a
copy of the `ActionsDAG` beforehand, with the comparisons rebuilt for them, so
that they compile.
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
…block size of the most occupancy

A kernel was looked up by its name in a map of its own, under a lock, at every
launch, and its PTX was loaded by the first launch, in the middle of a query.

Now the compiler loads it as soon as it emits its PTX, with
`cudaLibraryLoadData`, and keeps the module, the kernel and its block size, so
that a `GPUExpression` is the kernel itself and a launch takes no lock. The
block size is the whole number of warps that keeps the most threads of a
multiprocessor busy, by `cudaOccupancyMaxActiveBlocksPerMultiprocessor`, rather
than a fixed 256. A failure to load is an error of the query's planning.
scanhex12 added a commit that referenced this pull request Nov 4, 2026
…he CPU's comparison converts them, one launch

From the review of #129288:

- The kernels were kept for as long as the process runs, one for every distinct
  expression, constants included. They are kept by a `CacheBase` now, bounded as
  the CPU's `CompiledExpressionCache` is, and by the `CompiledGPUExpression`s of
  them, which whatever runs an expression keeps: an evicted kernel is unloaded,
  with `cudaLibraryUnload`, once nothing keeps it.
- A string constant is read as `FunctionComparison` reads it, with the
  `FormatSettings` of `ComparisonParams`, so with `cast_string_to_date_time_mode`;
  a `Decimal` compared with a float is converted with `castColumn` to a
  `Float64`, where `convertFieldToType` threw for every `Decimal`.
- The aliases of an expression are removed before `getCompilableDAG`, which takes
  one as an input, so that `(x + y AS s) > 100` compiles as `x + y > 100` does.
- `evaluatePredicateToBitmask` and `evaluateExpressionToFloat64` were the same
  launch: there is one, `evaluateGPUExpression`, and `GPUExpression::result` says
  what its kernel writes.

In this branch, `GPUDerivedValue` and the inputs of a derived value move to `CudfGroupBy`, the steps of the plan keep the kernels of their expressions, and `05455_gpu_compiled_filter_constants_and_aliases` covers the three predicates.
…he CPU's comparison converts them, one launch

From the review of #129288:

- The kernels were kept for as long as the process runs, one for every distinct
  expression, constants included. They are kept by a `CacheBase` now, bounded as
  the CPU's `CompiledExpressionCache` is, and by the `CompiledGPUExpression`s of
  them, which whatever runs an expression keeps: an evicted kernel is unloaded,
  with `cudaLibraryUnload`, once nothing keeps it.
- A string constant is read as `FunctionComparison` reads it, with the
  `FormatSettings` of `ComparisonParams`, so with `cast_string_to_date_time_mode`;
  a `Decimal` compared with a float is converted with `castColumn` to a
  `Float64`, where `convertFieldToType` threw for every `Decimal`.
- The aliases of an expression are removed before `getCompilableDAG`, which takes
  one as an input, so that `(x + y AS s) > 100` compiles as `x + y > 100` does.
- `evaluatePredicateToBitmask` and `evaluateExpressionToFloat64` were the same
  launch: there is one, `evaluateGPUExpression`, and `GPUExpression::result` says
  what its kernel writes.
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.
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
Comment thread src/GPU/GPUExpression.cpp Resolved
@scanhex12
scanhex12 marked this pull request as ready for review November 4, 2026 16:47
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.
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.
Comment thread src/GPU/GPUExpressionCompiler.cpp Resolved
scanhex12 added a commit that referenced this pull request Nov 4, 2026
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.
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.
@clickhouse-gh

clickhouse-gh Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.86, programs/clickhouse-keeper ×1.08 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse DB::registerFunctionConversion(DB::FunctionFactory&) 7.9 s 16.7 s +9.9 s (+145%)
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 4.0 s 8.6 s +5.1 s (+150%)
Compile time of recompiled translation units

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

Job report

`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.
… 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.
scanhex12 added a commit that referenced this pull request Nov 5, 2026
… 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.
@scanhex12
scanhex12 requested a review from groeneai November 5, 2026 12:48
@Manerone Manerone self-assigned this Nov 5, 2026

@groeneai groeneai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not run the device path (no CUDA device here, and no CI job builds with ENABLE_GPU), so I checked code generation with llc/opt 22.1.8 (Ubuntu build, not the bundled LLVM) and read the rest.

  • The open i128 blocker is fixed at this head: toFloat64(toUInt128(x) * toUInt128(y)) still has mul i128 and uitofp i128 after O3, llc aborts on them with LLVM ERROR: unsupported library call operation, and the type scan in emitPTX refuses them before code_generation.run. All 215 integer (i8 to i64), float/double and allowlisted-intrinsic operations I generated compile for sm_70 to sm_120, and fadd/fmul/fdiv are emitted with .rn (no FMA contraction), so rounding matches the CPU.
  • The description is behind the diff: constants of comparisons are no longer converted (1bca33b); comparisons of Date/Date32/DateTime still do not compile (FunctionsComparison.h:2314-2317, see f449b19), so even d < toDate('1994-01-01') is refused on the device (on master that predicate adds no CompileFunction event); and an expression's kernel writes its own type, not Float64 (094d132). The comment at contrib/llvm-project-cmake/CMakeLists.txt:189 points to src/GPU/GPUJIT.h, which does not exist.

One inline comment, on the kernel cache.

Comment thread src/GPU/GPUKernelCache.cpp Resolved

@Manerone Manerone left a comment

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.

I think the PR looks good, you are using the already JIT compiled parts with a wrapper around it to fit the GPU processing model.

I left some comments, which if the project is only experimental you could fix afterwards, but if not then it might be good to address now. Anyway, the comments revolve around the entry cache, which we need a bit more fine grain control. From what I understood, the kernels live within the GPU memory and not in RAM. In the unlikely event we fill the GPU memory with kernels we end up running out of memory for things that matter, processing of data.

I am not a specialist in GPU internals, so this comment might be incorrect.

Comment thread src/GPU/GPUKernelCache.cpp Resolved
Comment thread src/GPU/GPUKernelCache.cpp Resolved
Comment thread src/GPU/GPUKernelCache.h Resolved
…its weight is the device code, no device sync on unload

`~GPUKernel` no longer waits for the whole device: it ran under the mutex of `CacheBase` when an eviction dropped the
last reference, and stalled every compilation behind the work of all queries. Whoever launches a kernel holds
`CompiledGPUExpression::kernel` until the stream it was launched on is synchronized, so no launch can be queued when
the last reference goes; `GPUDevice` still waits for the device before it destroys the cache.

The limits are the server settings `gpu_expression_kernel_cache_size` and `gpu_expression_kernel_cache_elements_size`,
applied again when the configuration is reloaded, instead of the constants borrowed from the cache of the CPU JIT.

The PTX is linked into a cubin by the linker of the driver (`cuLinkCreate` and friends, through
`cudaGetDriverEntryPointByVersion`), and the cache weighs the cubin, which is what stays loaded, not the PTX text. A
failed link reports the error log of the driver.

#129288
…inker of the driver

Linking the PTX into a cubin through `cuLinkCreate` and friends only made the weight of a cache entry more exact, and
the size of the cubin misses the overhead of the driver per loaded module as well. The kernels of expressions are a few
kilobytes, the size of their PTX is proportional to the code on the device, and the number of loaded modules is bounded
by `gpu_expression_kernel_cache_elements_size`. The PTX is loaded with `cudaLibraryLoadData` as before.

#129288
@scanhex12
scanhex12 requested a review from Manerone November 9, 2026 19:06

@Manerone Manerone left a comment

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.

Looks good to me. Claude complains about the description being outdated:

It still promises the string/Decimal constant conversion and the Date comparison change; git show --stat on 1bca33b and f449b19 shows both were removed. The headline example d < '1994-01-01' is now refused, and kernels write the result's own type, not Float64. The "Slop description:" prefix and the text in the changelog-entry slot are still there.

@scanhex12
scanhex12 enabled auto-merge November 10, 2026 09:30
@scanhex12
scanhex12 disabled auto-merge November 10, 2026 09:30
…rnel cache is released

`cudaLibraryUnload` can wait for the device to free the code, and an eviction ran it under the mutex of
`CacheBase`, stalling every lookup and compilation behind the work queued on the device. `GPUKernelCache`
now keeps the evicted kernels in `onEntryRemoval` and drops them in `getOrSet`, `set`, `setMaxSizeInBytes`
and `setMaxCount` after the mutex is released.

Related: #129288
Comment thread src/GPU/GPUKernelCache.cpp Resolved
`SLRUCachePolicy::removeOverflow` subtracts the weight of the victim before `onEntryRemoval` and erases
it only after it returns, so a `push_back` that throws there left the entry resident with its weight
already subtracted. The evicted kernels are now linked into a list through `GPUKernel::next_evicted`,
which only moves a `shared_ptr`. `set` is deleted, so that a kernel cannot be linked twice.

Related: #129288
@scanhex12
scanhex12 enabled auto-merge November 10, 2026 12:21
@scanhex12
scanhex12 disabled auto-merge November 10, 2026 13:52
@scanhex12
scanhex12 added this pull request to the merge queue Nov 10, 2026
Merged via the queue into master with commit f75564e Nov 10, 2026
143 of 185 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants