Repository navigation
[GPU] Use JIT to compile expressions into NVPTX - #129288
Conversation
…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
|
Workflow [PR], commit [7fe2cdf] AI ReviewSummaryPR #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: Missing context / blind spots
Findings
💡 Nits
Tests
Final VerdictStatus: |
…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.
…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.
…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.
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.
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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Slowest function optimization changes (ThinLTO)Median per-function time ratio to the master baseline:
Compile time of recompiled translation units141 translation units recompiled, 1479 s compile time in total, 141 of them have a recent master baseline. |
`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.
… 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.
groeneai
left a comment
There was a problem hiding this comment.
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
i128blocker is fixed at this head:toFloat64(toUInt128(x) * toUInt128(y))still hasmul i128anduitofp i128after O3,llcaborts on them withLLVM ERROR: unsupported library call operation, and the type scan inemitPTXrefuses them beforecode_generation.run. All 215 integer (i8toi64),float/doubleand allowlisted-intrinsic operations I generated compile forsm_70tosm_120, andfadd/fmul/fdivare 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/DateTimestill do not compile (FunctionsComparison.h:2314-2317, see f449b19), so evend < toDate('1994-01-01')is refused on the device (on master that predicate adds noCompileFunctionevent); and an expression's kernel writes its own type, notFloat64(094d132). The comment atcontrib/llvm-project-cmake/CMakeLists.txt:189points tosrc/GPU/GPUJIT.h, which does not exist.
One inline comment, on the kernel cache.
Manerone
left a comment
There was a problem hiding this comment.
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.
…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
Manerone
left a comment
There was a problem hiding this comment.
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.
…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
`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
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.
GPUExpressionCompilerbuilds theCompileDAGof an output ofActionsDAG, as the CPU's JIT does, and emits a kernel aroundCompileDAG::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 aNullablecolumn, is refused, with the reason. A predicate's kernel writes the null mask of cuDF directly, byvote.ballot.sync; an expression's kernel writes aFloat64for each row. The PTX is kept by the hash of the expression, andGPUExpression.cpploads it once, withcudaLibraryLoadData, and runs it withcudaLaunchKernel.Decimalconstant compared with a column is converted to the column's type and the comparison rebuilt for it:d < '1994-01-01'.FunctionComparisoncompiles a comparison of two dates of the same type,Date,Date32orDateTime, as the integers that hold them, which the CPU's JIT gains as well.ENABLE_GPU, which now requiresENABLE_EMBEDDED_COMPILER.Related: #119502
Related: #128777
Changelog category (leave one):
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
26.11.1.1865-master(included in26.11and later)