From c7dd1f1ed146b968f52fe969f0d191bb7db92aac Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 09:53:42 +0200 Subject: [PATCH 1/6] Keep the KernelInterface launch checks out of per-kernel code `kernel_context`, `kernel_device`, `throw_device_mismatch` and the body of `KI.max_work_group_size` only use the kernel's `cl.Kernel` handle, but took the `KI.Kernel`, whose type includes the kernel function and argument types, so they were inferred and compiled again for every kernel. Type them on the `cl.Kernel` instead. `KI.launch` and `KI.kernel_function` are necessarily compiled per kernel: move the activation and context check of the former into `prepare_launch`, and don't inline `activate` in the latter. Per new broadcast kernel, after warm-up: compile time 176 -> 143 ms, inference 178 -> 145 ms. --- src/OpenCLKernels.jl | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/OpenCLKernels.jl b/src/OpenCLKernels.jl index 88a6b50a..47a701e1 100644 --- a/src/OpenCLKernels.jl +++ b/src/OpenCLKernels.jl @@ -182,7 +182,7 @@ KI.argconvert(::OpenCLBackend, arg) = kernel_convert(arg) # again at every launch, because the converted callable only holds pointers to the arrays # it captures function KI.kernel_function(backend::OpenCLBackend, f::F, tt::TT=Tuple{}; name = nothing, kwargs...) where {F,TT} - activate(backend) + @noinline activate(backend) # this method is compiled for every kernel check_sub_group_size(backend, kwargs) kern = GC.@preserve f clfunction(kernel_convert(f), tt; source=f, name, kwargs...) KI.Kernel{OpenCLBackend, typeof(kern)}(backend, kern) @@ -197,20 +197,23 @@ function check_sub_group_size(backend::OpenCLBackend, kwargs) return end +# these helpers take the `cl.Kernel` instead of the `KI.Kernel`, whose type depends on the +# kernel's function and argument types, so that they are compiled once instead of per kernel + # the context that a kernel was compiled for -function kernel_context(kernel::KI.Kernel{OpenCLBackend}) +function kernel_context(kernel::cl.Kernel) ctx = Ref{cl.cl_context}() - cl.clGetKernelInfo(kernel.kern.fun, cl.CL_KERNEL_CONTEXT, sizeof(cl.cl_context), ctx, C_NULL) + cl.clGetKernelInfo(kernel, cl.CL_KERNEL_CONTEXT, sizeof(cl.cl_context), ctx, C_NULL) return ctx[] end -function kernel_device(kernel::KI.Kernel{OpenCLBackend}) +function kernel_device(kernel::cl.Kernel) ctx = kernel_context(kernel) ctx == cl.context().id && return cl.device() return context_device(cl.Context(ctx; retain=true)) end -@noinline function throw_device_mismatch(kernel) +@noinline function throw_device_mismatch(kernel::cl.Kernel) throw(ArgumentError("Cannot launch a kernel compiled for $(kernel_device(kernel).name) on $(cl.device().name)")) end @@ -218,6 +221,14 @@ end throw(ArgumentError("KernelInterface kernels take `numgroups`, `workgroupsize` or `ndrange`, not `global_size` or `local_size`")) end +# activate the backend, and check that the kernel was compiled for its device. kept out of +# `KI.launch`, which is compiled for every kernel. +@noinline function prepare_launch(backend::OpenCLBackend, fun::cl.Kernel) + activate(backend) + kernel_context(fun) == cl.context().id || throw_device_mismatch(fun) + return +end + # passes the arguments on as a tuple, like calling the `HostKernel` does function KI.launch(kernel::KI.Kernel{OpenCLBackend}, groups::Dims{3}, items::Dims{3}, args::Tuple; kwargs...) @@ -225,15 +236,15 @@ function KI.launch(kernel::KI.Kernel{OpenCLBackend}, groups::Dims{3}, items::Dim if haskey(kwargs, :global_size) || haskey(kwargs, :local_size) throw_geometry_keyword() end - activate(kernel.backend) - kernel_context(kernel) == cl.context().id || throw_device_mismatch(kernel) + prepare_launch(kernel.backend, kernel.kern.fun) OpenCL.launch_tuple(kernel.kern, args; local_size = items, global_size = items .* groups, kwargs...) return end function KI.max_work_group_size(kernel::KI.Kernel{OpenCLBackend})::Int - wginfo = cl.work_group_info(kernel.kern.fun, kernel_device(kernel)) + fun = kernel.kern.fun + wginfo = cl.work_group_info(fun, kernel_device(fun)) Int(wginfo.size) end From ace1341cb17ef7e19a3d54ba454eec0b0b9efc66 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 09:54:31 +0200 Subject: [PATCH 2/6] Register indirect memory outside the per-signature cl.call `cl.call` is compiled for every kernel signature, and inlined the loop over the indirect memory objects (union-split over the memory types) and the `clSetKernelExecInfo` calls, none of which depend on the arguments. Move them into a function that's compiled once, as oneAPI.jl does for its argument-independent launch code. Per new broadcast kernel, after warm-up: compile time 143 -> 116 ms, inference 145 -> 121 ms. --- lib/cl/kernel.jl | 105 +++++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 50 deletions(-) diff --git a/lib/cl/kernel.jl b/lib/cl/kernel.jl index 04b4e585..24a6a8de 100644 --- a/lib/cl/kernel.jl +++ b/lib/cl/kernel.jl @@ -269,63 +269,68 @@ function call( ) return Base.@lock k begin _set_args!(k, args) - if !isempty(indirect_memory) - svm_pointers = CLPtr{Cvoid}[] - usm_pointers = CLPtr{Cvoid}[] - bda_pointers = CLPtr{Cvoid}[] - device_access = host_access = shared_access = false - for memory in indirect_memory - ptr = pointer(memory) - if ptr == C_NULL || ptr == CL_NULL - continue - end + isempty(indirect_memory) || set_indirect_memory!(k, indirect_memory) + enqueue_kernel(k, global_size, local_size; global_work_offset, wait_on, rng_state, + nargs=length(args)) + end +end - if memory isa SharedVirtualMemory - # system memory is not an SVM allocation and needs no registration: - # indirect access to it is governed by `SVM_FINE_GRAIN_SYSTEM`, which - # defaults to true on devices that support it. - is_system(memory) || push!(svm_pointers, ptr) - elseif memory isa Buffer - push!(bda_pointers, ptr) - elseif memory isa UnifiedDeviceMemory - device_access = true - push!(usm_pointers, ptr) - elseif memory isa UnifiedHostMemory - host_access = true - push!(usm_pointers, reinterpret(CLPtr{Cvoid}, ptr)) - elseif memory isa UnifiedSharedMemory - shared_access = true - push!(usm_pointers, ptr) - else - throw(ArgumentError("Unknown memory type")) - end +# register the memory that the kernel accesses through pointers that aren't arguments. +# kept out of `call`, which is compiled for every kernel signature. +@noinline function set_indirect_memory!(k::Kernel, indirect_memory::Vector{AbstractMemory}) + svm_pointers = CLPtr{Cvoid}[] + usm_pointers = CLPtr{Cvoid}[] + bda_pointers = CLPtr{Cvoid}[] + device_access = host_access = shared_access = false + for memory in indirect_memory + ptr = pointer(memory) + if ptr == C_NULL || ptr == CL_NULL + continue end - # configure USM access - if device_access - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) - end - if host_access - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) - end - if shared_access - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) + if memory isa SharedVirtualMemory + # system memory is not an SVM allocation and needs no registration: + # indirect access to it is governed by `SVM_FINE_GRAIN_SYSTEM`, which + # defaults to true on devices that support it. + is_system(memory) || push!(svm_pointers, ptr) + elseif memory isa Buffer + push!(bda_pointers, ptr) + elseif memory isa UnifiedDeviceMemory + device_access = true + push!(usm_pointers, ptr) + elseif memory isa UnifiedHostMemory + host_access = true + push!(usm_pointers, reinterpret(CLPtr{Cvoid}, ptr)) + elseif memory isa UnifiedSharedMemory + shared_access = true + push!(usm_pointers, ptr) + else + throw(ArgumentError("Unknown memory type")) end + end - # set the pointers - if !isempty(svm_pointers) - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_SVM_PTRS, sizeof(svm_pointers), svm_pointers) - end - if !isempty(bda_pointers) - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_DEVICE_PTRS_EXT, sizeof(bda_pointers), bda_pointers) - end - if !isempty(usm_pointers) - clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_USM_PTRS_INTEL, sizeof(usm_pointers), usm_pointers) - end + # configure USM access + if device_access + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) end - enqueue_kernel(k, global_size, local_size; global_work_offset, wait_on, rng_state, - nargs=length(args)) + if host_access + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) + end + if shared_access + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true)) + end + + # set the pointers + if !isempty(svm_pointers) + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_SVM_PTRS, sizeof(svm_pointers), svm_pointers) + end + if !isempty(bda_pointers) + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_DEVICE_PTRS_EXT, sizeof(bda_pointers), bda_pointers) + end + if !isempty(usm_pointers) + clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_USM_PTRS_INTEL, sizeof(usm_pointers), usm_pointers) end + return end # From `julia/base/reflection.jl`, adjusted to add specialization on `t`. From 4b67ca2eb2e98aa286a278299e00992fe34e53e4 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 10:01:25 +0200 Subject: [PATCH 3/6] Keep the exception mailbox bookkeeping out of per-signature code `launch_with_exception_mailbox` is compiled for every kernel signature, and inlined the mailbox lookup (a `get!` with a closure, under a lock), the launch ID atomics and the bookkeeping of pending queues. None of that depends on the arguments, so move it into functions that are compiled once. The calls, their order and the locks held around them are unchanged. Per new broadcast kernel, after warm-up: compile time 116 -> 106 ms, inference 121 -> 108 ms. --- src/compiler/exceptions.jl | 45 +++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/src/compiler/exceptions.jl b/src/compiler/exceptions.jl index 8092f668..4f4824b0 100644 --- a/src/compiler/exceptions.jl +++ b/src/compiler/exceptions.jl @@ -179,26 +179,45 @@ end function launch_with_exception_mailbox(kernel::cl.Kernel, args::Tuple; indirect_memory::Vector{cl.AbstractMemory}, rng_state::Bool, kwargs...) + mailbox, queue = current_exception_mailbox() + Base.@lock mailbox.lock begin + state = next_kernel_state(mailbox, indirect_memory, rng_state) + result = cl.call(kernel, prepend(state, args); indirect_memory, rng_state, kwargs...) + # only publish the launch once it has been submitted, so that `check_exceptions` + # can tell whether kernels have been submitted while it waited without the lock + publish_launch(mailbox, queue, state.launch_id) + return result + end +end + +# the parts of the launch that don't depend on the arguments, kept out of the function above, +# which is compiled for every kernel signature + +@noinline function current_exception_mailbox() ctx, dev, queue = cl.context(), cl.device(), cl.queue() mailbox = Base.@lock exception_mailboxes_lock begin get!(exception_mailboxes, (ctx, dev)) do allocate_exception_mailbox(ctx) end end - Base.@lock mailbox.lock begin - mailbox.mem === nothing || push!(indirect_memory, mailbox.mem) - launch_id = (Base.@atomic mailbox.launch_id) + UInt64(1) - state = KernelState(rng_state ? Base.rand(UInt32) : UInt32(0), mailbox.address, - launch_id) - result = cl.call(kernel, prepend(state, args); indirect_memory, rng_state, kwargs...) - # only publish the launch once it has been submitted, so that `check_exceptions` - # can tell whether kernels have been submitted while it waited without the lock - Base.@atomic mailbox.launch_id = launch_id - if mailbox.mem !== nothing - push!(mailbox.pending, queue) - end - return result + return mailbox, queue +end + +@noinline function next_kernel_state(mailbox::ExceptionMailbox, + indirect_memory::Vector{cl.AbstractMemory}, + rng_state::Bool) + mailbox.mem === nothing || push!(indirect_memory, mailbox.mem) + launch_id = (Base.@atomic mailbox.launch_id) + UInt64(1) + return KernelState(rng_state ? Base.rand(UInt32) : UInt32(0), mailbox.address, launch_id) +end + +@noinline function publish_launch(mailbox::ExceptionMailbox, queue::cl.CmdQueue, + launch_id::UInt64) + Base.@atomic mailbox.launch_id = launch_id + if mailbox.mem !== nothing + push!(mailbox.pending, queue) end + return end """ From 20ded2536ce07644d6e93d8669e6ac4b11c40615 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 10:03:50 +0200 Subject: [PATCH 4/6] Compile the kernel lookup in clfunction once `clfunction` is specialized on the kernel function and argument types, but only the method instance and the returned `HostKernel` depend on them. Move the rest, i.e. the compiler configuration, the cache lookup and the per-context kernel scan and linking, into a function that takes the method instance, as oneAPI.jl does with `zefunction_link`. The method instance is now looked up before taking the compiler lock rather than under it. Per new broadcast kernel, after warm-up: compile time 106 -> 90 ms, inference 108 -> 96 ms. --- src/compiler/execution.jl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/compiler/execution.jl b/src/compiler/execution.jl index 1b6e8255..6b982461 100644 --- a/src/compiler/execution.jl +++ b/src/compiler/execution.jl @@ -255,9 +255,15 @@ end const clfunction_lock = ReentrantLock() function clfunction(f::F, tt::TT=Tuple{}; source=f, kwargs...) where {F,TT} + kernel, device_rng = clfunction_link(methodinstance(F, tt); kwargs...) + HostKernel{F,typeof(source),tt}(f, source, kernel, device_rng) +end + +# the part of `clfunction` that doesn't depend on the kernel's function and argument types, +# kept separate so that it's compiled once rather than for every kernel +function clfunction_link(mi::Core.MethodInstance; kwargs...) Base.@lock clfunction_lock begin config = compiler_config(cl.device(); kwargs...)::OpenCLCompilerConfig - mi = methodinstance(F, tt) job = CompilerJob(mi, config) res = compile_or_lookup(job)::OpenCLResults @@ -282,7 +288,7 @@ function clfunction(f::F, tt::TT=Tuple{}; source=f, kwargs...) where {F,TT} end end - HostKernel{F,typeof(source),tt}(f, source, kernel, res.device_rng) + return kernel, res.device_rng end end From a82a9127a5f4f4995b3d5344f1b7bc57c737df62 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 10:05:13 +0200 Subject: [PATCH 5/6] Set kernel arguments through an unspecialized setter `set_arg!` is compiled for every argument type, and contained the `clSetKernelArg` call and its error handling, including the interpolated message about mismatched argument sizes. Only compute the size and address of the argument there, and leave the rest to a function that's compiled once, as oneAPI.jl does for `zeKernelSetArgumentValue`. Per new broadcast kernel, after warm-up: compile time 90 -> 84 ms, inference 96 -> 86 ms. --- lib/cl/kernel.jl | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/cl/kernel.jl b/lib/cl/kernel.jl index 24a6a8de..4c706b37 100644 --- a/lib/cl/kernel.jl +++ b/lib/cl/kernel.jl @@ -431,8 +431,15 @@ end function set_arg!(k::Kernel, idx::Integer, arg::T) where {T} ref = Ref(arg) - tsize = sizeof(ref) - err = unchecked_clSetKernelArg(k, idx - 1, tsize, ref) + GC.@preserve ref begin + set_arg_value!(k, Int(idx), sizeof(ref), Base.unsafe_convert(Ptr{Cvoid}, ref)) + end + return k +end + +# kept out of `set_arg!`, which is compiled for every argument type +@noinline function set_arg_value!(k::Kernel, idx::Int, size::Int, ptr::Ptr{Cvoid}) + err = unchecked_clSetKernelArg(k, idx - 1, size, ptr) if err == CL_INVALID_ARG_SIZE error("""Mismatch between Julia and OpenCL type for kernel argument $idx. @@ -446,7 +453,7 @@ function set_arg!(k::Kernel, idx::Integer, arg::T) where {T} elseif err != CL_SUCCESS throw(CLError(err)) end - return k + return end function set_arg!(k::Kernel, idx::Integer, arg::Nothing) From c7a88d0113d301cd891d54054cc8daa82aa4ffd7 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Fri, 16 Oct 2026 10:37:44 +0200 Subject: [PATCH 6/6] Keep the KernelInterface device queries out of KA's launch code KernelAbstractions' `launch_kernel` is compiled for every kernel, and inlined OpenCL.jl's `KI.max_work_group_size(::KI.Kernel)` (twice, through `launch_configuration` and `check_work_group_size`) as well as the task-local cache lookup of `device_properties`. Make the former forward to a function on the `cl.Kernel`, and don't inline either. Per new broadcast kernel, after warm-up: compile time 84 -> 78 ms, inference 86 -> 77 ms. --- src/OpenCLKernels.jl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/OpenCLKernels.jl b/src/OpenCLKernels.jl index 47a701e1..22d4bc9c 100644 --- a/src/OpenCLKernels.jl +++ b/src/OpenCLKernels.jl @@ -242,8 +242,9 @@ function KI.launch(kernel::KI.Kernel{OpenCLBackend}, groups::Dims{3}, items::Dim return end -function KI.max_work_group_size(kernel::KI.Kernel{OpenCLBackend})::Int - fun = kernel.kern.fun +# KernelAbstractions calls this from its launch code, which is compiled for every kernel +KI.max_work_group_size(kernel::KI.Kernel{OpenCLBackend}) = max_work_group_size(kernel.kern.fun) +@noinline function max_work_group_size(fun::cl.Kernel) wginfo = cl.work_group_info(fun, kernel_device(fun)) Int(wginfo.size) end @@ -252,7 +253,8 @@ end ## Device Properties # querying the device allocates, so cache what launches and kernels need. the cache is -# keyed on the device, because the task-local device can be switched. +# keyed on the device, because the task-local device can be switched. not inlined, as the +# device queries are used in launch code that is compiled for every kernel. const DeviceProperties = @NamedTuple{ max_work_group_size::Int, max_work_group_dims::NTuple{3, Int}, compute_units::Int, float64::Bool, unified::Bool, @@ -260,7 +262,7 @@ const DeviceProperties = @NamedTuple{ sub_group_size::Int, shuffle::Bool, float16::Bool, linear_sub_groups::Bool, independent_sub_groups::Bool, partitionable_sub_groups::Bool, } -function device_properties(dev::cl.Device) +@noinline function device_properties(dev::cl.Device) cache = get!(task_local_storage(), :CLDeviceProperties) do Dict{cl.Device, DeviceProperties}() end::Dict{cl.Device, DeviceProperties}