From 5c49bf54a034e8f63d2ce061848748b66cffd614 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 1/7] POCL: return the session by reference Avoid repeated struct copies and store-forwarding stalls. A trivial launch on a Xeon E3-1245 v6 drops from 602 to 566 cycles. --- src/pocl/pocl.jl | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/pocl/pocl.jl b/src/pocl/pocl.jl index 961d0f3f0..b53685965 100644 --- a/src/pocl/pocl.jl +++ b/src/pocl/pocl.jl @@ -11,21 +11,22 @@ import .nanoOpenCL as cl ## session state -# what every task shares: one context, so that kernels are only linked once per process -struct Session - platform::cl.Platform - device::cl.Device - context::cl.Context +# shared context: link kernels once per process. +# mutable so `session()` returns a reference, avoiding repeated copies per launch. +mutable struct Session + const platform::cl.Platform + const device::cl.Device + const context::cl.Context # querying the device allocates, so cache what launches need - limits::@NamedTuple{ + const limits::@NamedTuple{ max_work_group_size::Int, max_work_group_dims::NTuple{3, Int}, sub_group_size::Int, compute_units::Int, preferred_work_group_size_multiple::Int, fp16::Bool, fp64::Bool, } # duration threshold in cycle counter ticks for long launches (see `host_dispatch`) - host_kernel_long_ticks::UInt64 + const host_kernel_long_ticks::UInt64 # serial-duration threshold in ticks for small launches (see `host_schedule`) - host_kernel_serial_ticks::UInt64 + const host_kernel_serial_ticks::UInt64 end # a cheap monotonic counter: the TSC on x86, the virtual timer on AArch64 (where From f8deada1257eb88136e694f928b5a750df2444ef Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 2/7] Avoid divisions when computing launch geometry Use shifts and masks for power-of-two work-group sizes; skip division by the extent in preliminary partitions. This reduces repeated divisions in partitioning, coverage checks and PoCL tuning. On a Xeon E3-1245 v6, where 64-bit division costs tens of cycles, a trivial launch drops from 566 to 493 cycles. --- src/backend_launch.jl | 3 ++- src/nditeration.jl | 29 +++++++++++++++++++++++++++-- src/pocl/backend.jl | 17 ++++++++--------- 3 files changed, 37 insertions(+), 12 deletions(-) diff --git a/src/backend_launch.jl b/src/backend_launch.jl index b0e2bd7c1..d3d6bd741 100644 --- a/src/backend_launch.jl +++ b/src/backend_launch.jl @@ -271,7 +271,8 @@ bounded(range, iterspace) = builtin(iterspace) && cartesian(range) isa Cartesian # whether workgroups of `items` work-items, partitioning the `range`, which is `bounded`, # cover it exactly -covers(range, items::Dims) = all(map((n, i) -> iszero(n % i), size(cartesian(range)), items)) +covers(range, items::Dims) = + all(map((n, i) -> iszero(NDIteration.fldmod_extent(n, i)[2]), size(cartesian(range)), items)) # (kept out of `launch_kernel`, which is compiled for every kernel) @noinline covers(range, ctx::CompilerMetadata) = covers(range, size(workitems(__iterspace(ctx)))) diff --git a/src/nditeration.jl b/src/nditeration.jl index 2848295fb..ef7c88b53 100644 --- a/src/nditeration.jl +++ b/src/nditeration.jl @@ -253,6 +253,30 @@ Base.@propagate_inbounds function expand(ndrange::NDRange{N}, groupidx::Integer, return expand(ndrange, blocks(ndrange)[groupidx], idx) end +## integer arithmetic for launch geometry + +# launches compute their geometry every time, and a 64-bit division costs tens of cycles on +# some CPUs. these avoid dividing in the common cases: tuned work-group sizes are powers of +# two unless the range or kernel limits intervene, and preliminary partitions divide an +# extent by itself. (Base's `fldmod` and `cld` always divide unless the divisor is a +# constant, and `nextpow` keeps a `DomainError` path even when inlined.) + +# `fldmod(n, d)` for `n >= 0` and `d > 0` +@inline function fldmod_extent(n::Int, d::Int) + n == d && return 1, 0 + ispow2(d) && return n >> trailing_zeros(d), n & (d - 1) + return fldmod(n, d) +end + +# `cld(n, d)` for `n >= 0` and `d > 0` +@inline function cld_extent(n::Int, d::Int) + q, r = fldmod_extent(n, d) + return q + !iszero(r) +end + +# `nextpow(2, n)` for `n >= 1` +@inline nextpow2(n::Int) = n <= 1 ? 1 : 1 << (8 * sizeof(n) - leading_zeros(n - 1)) + """ partition(ndrange, workgroupsize) @@ -277,8 +301,9 @@ needs to perform dynamic bounds-checking. dynamic = Ref(false) blocks = ntuple(Val(length(ndrange))) do I Base.@_inline_meta - dynamic[] |= mod(ndrange[I], workgroupsize[I]) != 0 - return fld1(ndrange[I], workgroupsize[I]) + q, r = fldmod_extent(ndrange[I], workgroupsize[I]) + dynamic[] |= r != 0 + return q + (r != 0) end return blocks, workgroupsize, dynamic[] ? DynamicCheck() : NoDynamicCheck() diff --git a/src/pocl/backend.jl b/src/pocl/backend.jl index dda8af390..c18d6e163 100644 --- a/src/pocl/backend.jl +++ b/src/pocl/backend.jl @@ -8,6 +8,7 @@ using SPIRV_LLVM_Backend_jll, SPIRV_Tools_jll import KernelAbstractions as KA import KernelInterface as KI +using KernelAbstractions.NDIteration: fldmod_extent, cld_extent, nextpow2 import SPIRVIntrinsics @@ -313,7 +314,7 @@ end # that divides `n`. if none exists, use a quarter of `x` (a multiple of `m`) when `shrink`, # or keep `x` otherwise function fit_workgroup(n::Int, x::Int, m::Int, shrink::Bool) - n % x == 0 && return x + iszero(fldmod_extent(n, x)[2]) && return x d = largest_divisor(n, x, m) d == 0 || return d shrink || return x @@ -325,7 +326,7 @@ end # skips `x` (`largest_divisor(8, 4, 1) == 2`). function largest_divisor(n::Int, x::Int, m::Int) # (a multiple of `m` only divides multiples of `m`) - n % m == 0 || return 0 + iszero(fldmod_extent(n, m)[2]) || return 0 lo = cld(x, 2) hi = (x - 1) ÷ m * m if (hi - lo) ÷ m <= fld(n, lo) - cld(n, x) @@ -356,18 +357,16 @@ function cpu_workgroupsize(nitems, threads, max_items, multiple) items = min(nextpow2(min(nitems, max_items)), max_items) # one work-group, which isn't split (without dividing, for small launches) items >= nitems && items < 2 * min_items && return items - groups = cld(nitems, items) - while (splits = min(threads ÷ groups, items ÷ min_items)) > 1 + groups = cld_extent(nitems, items) + while threads >= 2 * groups && items >= 2 * min_items + splits = min(threads ÷ groups, items ÷ min_items) # PoCL splits by the largest factor of at most `splits` that divides the work-group - items ÷= prevpow(2, splits) - groups = cld(nitems, items) + items >>= trailing_zeros(prevpow(2, splits)) + groups = cld_extent(nitems, items) end return items end -# `nextpow(2, n)` for `n >= 1`, inlined -@inline nextpow2(n::Integer) = n <= 1 ? one(n) : one(n) << (8 * sizeof(n) - leading_zeros(n - one(n))) - KI.supports_subgroups(::POCLBackend) = device_limits().sub_group_size > 0 # PoCL forms sub-groups from consecutive work-items, but executes sub-group operations as # work-group barriers, so they need work-group-uniform control flow (see `POCLBackend`) From e7e473deb8e5db08db2d4733165bd4ef7721a85f Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 3/7] Tune each launch's workgroup size once Reuse the predicted size and coverage result when the backend confirms the prediction. PoCL checks that kernel and device limits match. Avoiding repeated tuning and coverage checks saves about 85 instructions per launch. --- src/backend_launch.jl | 49 ++++++++++++++++++++++++++++--------------- src/pocl/backend.jl | 5 +++++ test/runtests.jl | 1 + 3 files changed, 38 insertions(+), 17 deletions(-) diff --git a/src/backend_launch.jl b/src/backend_launch.jl index d3d6bd741..07efbd8b6 100644 --- a/src/backend_launch.jl +++ b/src/backend_launch.jl @@ -162,7 +162,12 @@ function launch_kernel( # compiled once. tuned = workgroupsize(obj) <: DynamicSize && _workgroupsize === nothing range = something(ndrange, static_ndrange(obj)) - unchecked = !checked && skip_bounds_check(b) && expect_coverage(b, launch, range, iterspace, tuned) + # predicted workgroup size (`expected`) and per-dimension sizes (`predicted`) + unchecked, expected, predicted = if !checked && skip_bounds_check(b) + expect_coverage(b, launch, range, iterspace, tuned) + else + false, 0, size(workitems(iterspace)) + end kernel = if skip_bounds_check(b) # hide the check type from inference, so that the lookup compiles once for both compiled_tt = Base.compilerbarrier(:type, unchecked ? without_bounds_check(tt) : tt)::Type @@ -173,17 +178,21 @@ function launch_kernel( end # tune the workgroup size, keeping the context type (and thus the kernel) the same - threads = if tuned - KI.launch_configuration(kernel; nitems = saturated_prod(extents(range))).workgroupsize - else + threads = if !tuned nothing + elseif expected > 0 && tunes_as_expected(kernel) + expected + else + KI.launch_configuration(kernel; nitems = saturated_prod(extents(range))).workgroupsize end ctx, groups, items = launch_geometry(sizes_only(obj), launch, subgroups, ndrange, iterspace, ctx, threads) - # partial workgroups need bounds checks. if kernel-specific tuning introduced them - # unexpectedly, relaunch checked. otherwise, split-capable backends can run full - # workgroups unchecked. - if !checked && skip_bounds_check(b) && bounded(range, iterspace) && !covers(range, ctx) + # partial workgroups need bounds checks. if kernel-specific tuning adds them unexpectedly, + # relaunch checked; otherwise, split-capable backends can run full workgroups unchecked. + # reuse coverage only if workgroup sizes match the prediction; custom `partition` may + # change them. + if !checked && skip_bounds_check(b) && bounded(range, iterspace) && + !(size(workitems(__iterspace(ctx))) == predicted ? unchecked : covers(range, ctx)) unchecked && return launch_kernel(obj, launch, subgroups, ndrange, _workgroupsize, iterspace, args, true) extent = split_extent(size(cartesian(range)), items) @@ -253,6 +262,15 @@ work-items, computed without a kernel. Only called if `skip_bounds_check(backend """ function expected_workgroupsize end +""" + tunes_as_expected(kernel)::Bool + +Whether [`expected_workgroupsize`](@ref) predicts the size from `KI.launch_configuration`, +so tuning can be skipped (e.g. when kernel and device limits match). +Only called if `skip_bounds_check(backend)`. +""" +tunes_as_expected(kernel) = false + # the argument types `tt` of a launch, with `NoDynamicCheck` in the type of the context # (which `argconvert` doesn't change) instead of `DynamicCheck`. computed from the types, as # constructing the context takes more host code to compile for every kernel. @@ -277,16 +295,13 @@ covers(range, items::Dims) = @noinline covers(range, ctx::CompilerMetadata) = covers(range, size(workitems(__iterspace(ctx)))) # whether the workgroups of a launch over `range`, partitioned as `iterspace` or with a -# `tuned` workgroup size, are expected to cover it exactly (see `bounded` and `covers`) +# `tuned` size, should cover it exactly (see `bounded` and `covers`), plus the predicted +# tuned size (0 if not `tuned`) and per-dimension workgroup sizes @noinline function expect_coverage(b, launch, range, iterspace, tuned::Bool) - bounded(range, iterspace) || return false - items = if tuned - expected = expected_workgroupsize(b, saturated_prod(extents(range))) - launch_workgroupsize(b, launch, expected, range) - else - size(workitems(iterspace)) - end - return covers(range, items) + expected = tuned ? expected_workgroupsize(b, saturated_prod(extents(range))) : 0 + bounded(range, iterspace) || return false, expected, size(workitems(iterspace)) + items = tuned ? launch_workgroupsize(b, launch, expected, range) : size(workitems(iterspace)) + return covers(range, items), expected, items end # the context and launch geometry, re-partitioned for the tuned workgroup size `threads` diff --git a/src/pocl/backend.jl b/src/pocl/backend.jl index c18d6e163..c821a3c3a 100644 --- a/src/pocl/backend.jl +++ b/src/pocl/backend.jl @@ -278,6 +278,11 @@ end # the workgroup size `KI.launch_configuration` tunes for kernels with the device's limits, # which is what PoCL kernels report, unless their estimated stack use limits their size +function KA.tunes_as_expected(kernel::KI.Kernel{POCLBackend}) + k, limits = kernel.kern.kernel.fun, device_limits() + return k.tuned_work_group_size == limits.max_work_group_size && + k.preferred_work_group_size_multiple == limits.preferred_work_group_size_multiple +end function KA.expected_workgroupsize(::POCLBackend, nitems) limits = device_limits() return cpu_workgroupsize( diff --git a/test/runtests.jl b/test/runtests.jl index 2c05f838e..f3dd93b8e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -1560,6 +1560,7 @@ end # the device's largest work-group needs more stack than a host kernel may use @test fun.private_mem_size * fun.work_group_size > POCL.host_kernel_stack_limit items = KernelAbstractions.KernelInterface.launch_configuration(kernel; nitems = n).workgroupsize + @test !KernelAbstractions.tunes_as_expected(kernel) sizes = (; global_size = (n, 1, 1), local_size = (items, 1, 1)) @test POCL.host_kernel(kernel.kern.kernel, sizes, nothing) !== nothing kernel(B, idx; workgroupsize = items, numgroups = cld(n, items)) From b8c5a2b173123e690d00765464f16e12fbaebc30 Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 4/7] POCL: share argument generation with host kernel launches Use the vector-based helper shared with `launch_converted` to avoid recompiling the `host_launch_converted` generator for each argument count. Its expression tuples cost 15-20 ms per compilation, 59 times in an Oceananigans model's first time step. --- src/pocl/compiler/execution.jl | 33 +++++++++++---------------------- 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/src/pocl/compiler/execution.jl b/src/pocl/compiler/execution.jl index ad476096e..e0e9441ed 100644 --- a/src/pocl/compiler/execution.jl +++ b/src/pocl/compiler/execution.jl @@ -244,9 +244,12 @@ end KernelState(rng_state ? rng_seed() : UInt32(0), UInt64(UInt(exception_info))) @noinline rng_seed() = Base.rand(UInt32) -# the call's tuple type and argument expressions for `launch_converted`. (on vectors, so that -# it compiles once for all argument counts.) -function kernel_call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int) +# For the generators below: the argument types of a kernel compiled for `F` and the +# argument types `TT`, as a tuple type, and the expressions that compute the arguments from +# `kernel`, its `nargs` arguments `args` and `exception_info`, with `null` for the values of +# non-isbits arguments. (a function of its own, working on vectors, so that it is compiled +# once rather than for every number of arguments.) +function kernel_call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int, null) params = Any[F, TT.parameters...] # Base.signature_type with a function type exprs = Any[:(kernel.f); Any[:(clconvert(args[$i])) for i in 1:nargs]] call_t = Type[KernelState] @@ -257,7 +260,7 @@ function kernel_call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int) # replace non-isbits arguments (they should be unused, or compilation would have # failed) push!(call_t, isbitstype(dt) ? dt : Ptr{Any}) - push!(call_args, isbitstype(dt) ? ex : :C_NULL) + push!(call_args, isbitstype(dt) ? ex : null) end return Base.to_tuple_type(call_t), call_args end @@ -265,7 +268,7 @@ end @inline @generated function launch_converted( kernel::AbstractKernel{F, TT}, args::Tuple, exception_info, global_size, local_size ) where {F, TT} - call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args)) + call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args), :C_NULL) # the converted arguments only hold pointers to the arrays in `args` return inline_body( @@ -882,23 +885,9 @@ end kernel::AbstractKernel{F, TT}, args::Tuple, exception_info, h, num_groups, full, extent ) where {F, TT} - sig = Tuple{F, TT.parameters...} - args = (:(kernel.f), (:(clconvert(args[$i])) for i in 1:fieldcount(args))...) - - to_pass = map(pass_arg, sig.parameters) - call_t = Type[x[1] for x in zip(sig.parameters, to_pass) if x[2]] - call_args = Union{Expr, Symbol}[x[1] for x in zip(args, to_pass) if x[2]] - for (i, dt) in enumerate(call_t) - if !isbitstype(dt) - call_t[i] = Ptr{Any} - call_args[i] = :(Ptr{Any}(C_NULL)) - end - end - pushfirst!(call_t, KernelState) - pushfirst!(call_args, :(kernel_state(kernel.rng_state, exception_info))) - call_tt = Base.to_tuple_type(call_t) - arg_ptrs = [:(base + $(fieldoffset(call_tt, i))) for i in 1:length(call_t)] - N = length(call_t) + call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args), :(Ptr{Any}(C_NULL))) + N = length(call_args) + arg_ptrs = Expr[:(base + $(fieldoffset(call_tt, i))) for i in 1:N] # the converted arguments only hold pointers to the arrays in `args`. the local memory # arguments of RNG kernels are set on the host kernel, so they get no value. From 6112866ad045745c7ee828ce3b20a21ce04b7cbe Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 5/7] POCL: sample timings of short launches on the launching task MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cycle-counter reads cost 40 of a trivial launch's 383 cycles on a Ryzen 9 5950X; on a Xeon E3-1245 v6, they overlap with the launch. After a sample below 1 µs, time one in 16 launches. Always time grids with no estimate or a changed work-group count. Detecting longer work within a grid can lag by 16 launches; work varying with that period can evade sampling entirely. --- src/pocl/compiler/execution.jl | 35 +++++++++++++++---- src/pocl/nanoOpenCL.jl | 6 ++-- src/pocl/pocl.jl | 6 +++- test/runtests.jl | 61 +++++++++++++++++++++++++++++++--- 4 files changed, 95 insertions(+), 13 deletions(-) diff --git a/src/pocl/compiler/execution.jl b/src/pocl/compiler/execution.jl index e0e9441ed..f429e8cfa 100644 --- a/src/pocl/compiler/execution.jl +++ b/src/pocl/compiler/execution.jl @@ -434,6 +434,9 @@ const host_steal_max_groups = Int(typemax(Int32)) # 8192 work-items to recover that cost on 4 or 8 threads (see `host_schedule`). const host_kernel_serial_items = 8192 +# untimed launches after a short sample in `run_short`; resampling detects longer work +const host_untimed_launches = 15 + # host kernels use the calling thread's stack; Julia task stacks are at least 4 MiB. cap # estimated use at 1 MiB, using PoCL's upper bound per work-item. tuning shrinks work-groups # to fit (see `link_kernel`); sizes that still exceed the limit use the queue. @@ -676,6 +679,9 @@ end # racy by design: these statistics affect scheduling policy only @inline function record_serial_sample(h::cl.HostKernelHandle, groups::Int, sample::UInt64) + # a coarse counter (24 MHz on Apple silicon) can measure 0 ticks, which would read as no + # estimate and make `run_short` time every launch + sample = max(sample, one(UInt64)) if (Base.@atomic :monotonic h.serial_groups_a) == groups previous = Base.@atomic :monotonic h.serial_sample_a else @@ -795,6 +801,8 @@ end launch() Base.@atomic :monotonic h.last_duration = cycle_counter() - start Base.@atomic :monotonic h.last_groups = total + # resample on the launching task: team timings may not apply + Base.@atomic :monotonic h.untimed = 0 end # yield after team or long launches so repeated launches don't starve tasks, timers or # I/O @@ -856,12 +864,27 @@ end # supplies both the serial estimate and the last-launch duration @inline function run_short(l::HostLaunch) scratch = host_scratch_ptr(l.scratch_size, l.scratch_alignment) - start = cycle_counter() - host_run(l, 0, l.total, scratch) - duration = cycle_counter() - start - record_serial_sample(l.h, l.total, duration) - Base.@atomic :monotonic l.h.last_duration = duration - Base.@atomic :monotonic l.h.last_groups = l.total + h = l.h + # counter reads can cost tens of cycles. sample every `host_untimed_launches + 1` launches + # after a short sample; detecting longer work can lag that long or miss work varying + # with that period entirely. always time grids with no estimate or a changed work-group + # count: estimates are per grid, the countdown per kernel; no estimate means one thread. + untimed = Base.@atomic :monotonic h.untimed + if untimed == 0 || + (Base.@atomic :monotonic h.last_duration) >= session().host_kernel_short_ticks || + (Base.@atomic :monotonic h.last_groups) != l.total || + serial_duration(h, l.total) == 0 + start = cycle_counter() + host_run(l, 0, l.total, scratch) + duration = cycle_counter() - start + record_serial_sample(h, l.total, duration) + Base.@atomic :monotonic h.last_duration = duration + Base.@atomic :monotonic h.untimed = host_untimed_launches + else + host_run(l, 0, l.total, scratch) + Base.@atomic :monotonic h.untimed = untimed - 1 + end + Base.@atomic :monotonic h.last_groups = l.total return end diff --git a/src/pocl/nanoOpenCL.jl b/src/pocl/nanoOpenCL.jl index 23f05ddb5..466bb9fac 100644 --- a/src/pocl/nanoOpenCL.jl +++ b/src/pocl/nanoOpenCL.jl @@ -1300,9 +1300,11 @@ mutable struct HostKernelHandle const local_size::NTuple{3, Int} const scratch_size::Int const scratch_alignment::Int - # how long the last launch took, in cycle counter ticks, and how many work-groups it had + # last sampled duration (counter ticks) and last launch's work-group count Base.@atomic last_duration::UInt64 Base.@atomic last_groups::Int + # untimed launches remaining on the launching task + Base.@atomic untimed::Int # serial estimates for the last two work-group counts (`a` is latest): work per item can # vary with grid size. scale the first range's time to the whole grid, in cycle counter # ticks. use the smaller of two samples (zero without a previous sample) to discount a @@ -1315,7 +1317,7 @@ mutable struct HostKernelHandle Base.@atomic serial_duration_b::UInt64 function HostKernelHandle(id, local_size, scratch_size = 0, scratch_alignment = 1) - h = new(id, local_size, scratch_size, scratch_alignment, 0, 0, 0, 0, 0, 0, 0, 0) + h = new(id, local_size, scratch_size, scratch_alignment, 0, 0, 0, 0, 0, 0, 0, 0, 0) id == C_NULL || finalizer(h -> clReleaseHostKernelPOCL(h.id), h) return h end diff --git a/src/pocl/pocl.jl b/src/pocl/pocl.jl index b53685965..8d707fd34 100644 --- a/src/pocl/pocl.jl +++ b/src/pocl/pocl.jl @@ -27,6 +27,8 @@ mutable struct Session const host_kernel_long_ticks::UInt64 # serial-duration threshold in ticks for small launches (see `host_schedule`) const host_kernel_serial_ticks::UInt64 + # below this duration (ticks), sample timings on the launching task; see `run_short` + const host_kernel_short_ticks::UInt64 end # a cheap monotonic counter: the TSC on x86, the virtual timer on AArch64 (where @@ -101,10 +103,12 @@ function Session() host_kernel_long_ticks = round(UInt64, 50_000 * rate) # 4 µs, several times what starting and joining a team costs, see `host_schedule` host_kernel_serial_ticks = round(UInt64, 4_000 * rate) + # 1 µs, compared with tens of nanoseconds to time a launch + host_kernel_short_ticks = round(UInt64, 1_000 * rate) return Session( platform, device, context, limits, host_kernel_long_ticks, - host_kernel_serial_ticks + host_kernel_serial_ticks, host_kernel_short_ticks ) end diff --git a/test/runtests.jl b/test/runtests.jl index f3dd93b8e..1eb576fd7 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -666,10 +666,11 @@ end @test POCL.host_schedule(h, s, nt, false) == (1, false) # large grids select the full team @test POCL.host_schedule(h, s, 10^6, false)[1] == nt - # estimates are per grid: a short one-group launch must not make a heavy grid run - # serially - kernel(A, 10^5; sizes...) - kernel(A, 10^5; sizes...) + # estimates are per grid: a short one-group launch must not keep a heavy grid serial. + # allow enough launches to resample longer work. + for _ in 1:(POCL.host_untimed_launches + 2) + kernel(A, 10^5; sizes...) + end kernel(A, 0; global_size = (1, 1, 1), local_size = (1, 1, 1)) @test POCL.host_schedule(h, s, nt, false)[1] == nt @@ -684,6 +685,40 @@ end @test POCL.host_schedule(h, s, smax + 1, true) == (nt, false) @test POCL.host_schedule(h, s, tmax, true) == (nt, false) end + + # time grid changes: a heavy grid alternating with a cheap one must not evade + # sampling and stay on one thread (per-kernel countdown, per-grid estimates). + B = ones(4) + grid(n) = (; global_size = (n, 1, 1), local_size = (1, 1, 1)) + for _ in 1:2 + kernel(B, 0; grid(2)...) + kernel(B, 0; grid(3)...) + end + Base.@atomic h.untimed = POCL.host_untimed_launches + Base.@atomic h.last_duration = 0 + for _ in 1:(POCL.host_untimed_launches + 1) + kernel(B, 10^5; grid(2)...) + kernel(B, 0; grid(3)...) + end + @test POCL.host_schedule(h, s, 2, false)[1] == 2 + # missing estimates override the countdown. (check the countdown, which a timed launch + # restarts: a coarse counter can measure any duration, e.g. 1 tick.) + kernel(B, 0; grid(1)...) + Base.@atomic h.untimed = 1 + Base.@atomic h.last_duration = 1 + kernel(B, 0; grid(1)...) + @test (Base.@atomic h.untimed) == POCL.host_untimed_launches + @test POCL.serial_duration(h, 1) > 0 + Base.@atomic h.last_duration = 1 + kernel(B, 0; grid(1)...) + @test (Base.@atomic h.last_duration) == 1 + @test (Base.@atomic h.untimed) == POCL.host_untimed_launches - 1 + # resample on one thread after a team launch + POCL.record_serial_sample(h, nt, typemax(UInt64)) + POCL.record_serial_sample(h, nt, typemax(UInt64)) + Base.@atomic h.last_duration = 0 + kernel(A, 0; sizes...) + @test (Base.@atomic h.untimed) == 0 end end @@ -751,6 +786,24 @@ end end @test woke[] wait(task) + + # sample short launches after two runs establish the grid's estimate + one = (; global_size = (1, 1, 1), local_size = (1, 1, 1)) + Base.@atomic h.untimed = 0 + Base.@atomic h.last_duration = 0 + kernel(A; one...) + kernel(A; one...) + @test POCL.serial_duration(h, 1) > 0 + @test (Base.@atomic h.untimed) == POCL.host_untimed_launches + Base.@atomic h.last_duration = 1 + kernel(A; one...) + @test (Base.@atomic h.last_duration) == 1 + @test (Base.@atomic h.untimed) == POCL.host_untimed_launches - 1 + # time every long launch + Base.@atomic h.untimed = 1 + Base.@atomic h.last_duration = s.host_kernel_short_ticks + kernel(A; one...) + @test (Base.@atomic h.untimed) == POCL.host_untimed_launches end end From 2078adf3dd84af950b775ef67c0d63f06a9cd9dd Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 6/7] POCL: convert launch arguments once for both paths Share argument conversion between queue and host-kernel paths to avoid duplicating most per-kernel launch code. Launch inference for the 71 kernels of an Oceananigans time step drops from 5.6 to 3.1 s. --- src/pocl/compiler/execution.jl | 93 ++++++++++++++++++++-------------- test/pocl_session.jl | 2 +- 2 files changed, 56 insertions(+), 39 deletions(-) diff --git a/src/pocl/compiler/execution.jl b/src/pocl/compiler/execution.jl index f429e8cfa..75948f6d4 100644 --- a/src/pocl/compiler/execution.jl +++ b/src/pocl/compiler/execution.jl @@ -190,12 +190,14 @@ function launch_and_wait( # unavailable, run every work-group checked. hp = host_kernel(with_fun(kernel, partial), values(kwargs), groups) h = hp === nothing ? nothing : full_host_kernel(kernel, partial, hp) + # share conversion, the bulk of each path's per-kernel code + converted = converted_arguments(kernel, args) if hp === nothing info = exception_info() info[] = ExceptionInfo_st() GC.@preserve info begin info_ptr = Base.unsafe_convert(Ptr{ExceptionInfo_st}, info) - event = launch_tuple(with_fun(kernel, partial), args, info_ptr; kwargs...) + event = launch_queued(with_fun(kernel, partial), converted, info_ptr; kwargs...) wait_for_kernel(event) end check_exception(info) @@ -207,7 +209,7 @@ function launch_and_wait( info = Ref(ExceptionInfo_st()) GC.@preserve info begin info_ptr = Base.unsafe_convert(Ptr{ExceptionInfo_st}, info) - host_launch_converted(kernel, args, info_ptr, hp, num_groups, h, extent) + host_launch_converted(kernel, converted, info_ptr, hp, num_groups, h, extent) end # passing the status avoids allocating `info` check_exception(info[].status) @@ -236,7 +238,15 @@ end @inline launch_tuple( kernel::AbstractKernel, args::Tuple, exception_info::Ptr; global_size = (1,), local_size = nothing -) = launch_converted(kernel, args, exception_info, global_size, local_size) +) = GC.@preserve args launch_converted( + kernel, converted_arguments(kernel, args), exception_info, global_size, local_size +) + +# `launch_tuple` for preconverted arguments +@inline launch_queued( + kernel::AbstractKernel, converted::Tuple, exception_info::Ptr; + global_size = (1,), local_size = nothing +) = launch_converted(kernel, converted, exception_info, global_size, local_size) # kept out of the launches, which are compiled for every kernel: inlining `rand` makes them # several times as expensive to compile @@ -244,38 +254,44 @@ end KernelState(rng_state ? rng_seed() : UInt32(0), UInt64(UInt(exception_info))) @noinline rng_seed() = Base.rand(UInt32) -# For the generators below: the argument types of a kernel compiled for `F` and the -# argument types `TT`, as a tuple type, and the expressions that compute the arguments from -# `kernel`, its `nargs` arguments `args` and `exception_info`, with `null` for the values of -# non-isbits arguments. (a function of its own, working on vectors, so that it is compiled -# once rather than for every number of arguments.) -function kernel_call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int, null) +# argument expressions for a kernel compiled for `F` and `TT`. +# vectors let this helper compile once for all argument counts. +function converted_argument_exprs(@nospecialize(F), @nospecialize(TT), nargs::Int) params = Any[F, TT.parameters...] # Base.signature_type with a function type exprs = Any[:(kernel.f); Any[:(clconvert(args[$i])) for i in 1:nargs]] - call_t = Type[KernelState] - call_args = Any[:(kernel_state(kernel.rng_state, exception_info))] + converted = Any[] for (dt, ex) in zip(params, exprs) # filter out ghost arguments that shouldn't be passed pass_arg(dt) || continue # replace non-isbits arguments (they should be unused, or compilation would have # failed) - push!(call_t, isbitstype(dt) ? dt : Ptr{Any}) - push!(call_args, isbitstype(dt) ? ex : null) + push!(converted, isbitstype(dt) ? ex : :(Ptr{Any}(C_NULL))) end - return Base.to_tuple_type(call_t), call_args + return converted end -@inline @generated function launch_converted( - kernel::AbstractKernel{F, TT}, args::Tuple, exception_info, global_size, local_size +# arguments for `kernel(args...)`, excluding kernel state. +# array arguments become pointers; the caller must keep `args` alive. +@inline @generated function converted_arguments( + kernel::AbstractKernel{F, TT}, args::Tuple ) where {F, TT} - call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args), :C_NULL) + exprs = converted_argument_exprs(F, TT, fieldcount(args)) + return inline_body(:(($(exprs...),))) +end + +kernel_argument_types(@nospecialize(converted::Type)) = Tuple{KernelState, converted.parameters...} - # the converted arguments only hold pointers to the arrays in `args` +@inline @generated function launch_converted( + kernel::AbstractKernel, converted::Tuple, exception_info, global_size, local_size + ) + call_tt = kernel_argument_types(converted) + vals = Expr[:(converted[$i]) for i in 1:fieldcount(converted)] return inline_body( quote - GC.@preserve args begin - $cl.clcall(kernel.fun, $call_tt, ($(call_args...),); global_size, local_size, kernel.rng_state) - end + $cl.clcall( + kernel.fun, $call_tt, (kernel_state(kernel.rng_state, exception_info), $(vals...)); + global_size, local_size, kernel.rng_state + ) end ) end @@ -905,25 +921,26 @@ end # like `launch_converted`, but passes a pointer to each converted argument @inline @generated function host_launch_converted( - kernel::AbstractKernel{F, TT}, args::Tuple, exception_info, h, num_groups, full, - extent - ) where {F, TT} - call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args), :(Ptr{Any}(C_NULL))) - N = length(call_args) + kernel::AbstractKernel, converted::Tuple, exception_info, h, num_groups, full, extent + ) + call_tt = kernel_argument_types(converted) + N = fieldcount(call_tt) + vals = Expr[:(converted[$i]) for i in 1:fieldcount(converted)] arg_ptrs = Expr[:(base + $(fieldoffset(call_tt, i))) for i in 1:N] - # the converted arguments only hold pointers to the arrays in `args`. the local memory - # arguments of RNG kernels are set on the host kernel, so they get no value. - return quote - vals = Ref{$call_tt}(($(call_args...),)) - GC.@preserve args vals begin - base = Ptr{Cvoid}(Base.unsafe_convert(Ptr{$call_tt}, vals)) - ptrs = Ref{NTuple{$(N + 2), Ptr{Cvoid}}}(($(arg_ptrs...), C_NULL, C_NULL)) - GC.@preserve ptrs begin - arg_values = Ptr{Ptr{Cvoid}}(Base.unsafe_convert(Ptr{NTuple{$(N + 2), Ptr{Cvoid}}}, ptrs)) - host_dispatch(h, arg_values, num_groups, exception_info, full, extent) + # RNG local memory arguments are set on the host kernel; pass no values here + return inline_body( + quote + vals = Ref{$call_tt}((kernel_state(kernel.rng_state, exception_info), $(vals...))) + GC.@preserve vals begin + base = Ptr{Cvoid}(Base.unsafe_convert(Ptr{$call_tt}, vals)) + ptrs = Ref{NTuple{$(N + 2), Ptr{Cvoid}}}(($(arg_ptrs...), C_NULL, C_NULL)) + GC.@preserve ptrs begin + arg_values = Ptr{Ptr{Cvoid}}(Base.unsafe_convert(Ptr{NTuple{$(N + 2), Ptr{Cvoid}}}, ptrs)) + host_dispatch(h, arg_values, num_groups, exception_info, full, extent) + end end + nothing end - nothing - end + ) end diff --git a/test/pocl_session.jl b/test/pocl_session.jl index a0ebf63a7..c48934a32 100644 --- a/test/pocl_session.jl +++ b/test/pocl_session.jl @@ -249,7 +249,7 @@ end info = Ref(POCL.ExceptionInfo_st()) GC.@preserve info begin ptr = Base.unsafe_convert(Ptr{POCL.ExceptionInfo_st}, info) - POCL.host_launch_converted(k, (B, m), ptr, h, (2, 1, 1), full, (1, 1, 1)) + POCL.host_launch_converted(k, POCL.converted_arguments(k, (B, m)), ptr, h, (2, 1, 1), full, (1, 1, 1)) end end err = try From cc7cf19c05ef4bfbfde391f94a70b6f3a3bac22f Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Tue, 27 Oct 2026 06:08:29 +0100 Subject: [PATCH 7/7] POCL: avoid materializing short host launches in memory Call PoCL directly for unsplit launches. This avoids the memory traffic from passing `HostLaunch` by reference to `host_run`. --- src/pocl/compiler/execution.jl | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/pocl/compiler/execution.jl b/src/pocl/compiler/execution.jl index 75948f6d4..b74af5b1f 100644 --- a/src/pocl/compiler/execution.jl +++ b/src/pocl/compiler/execution.jl @@ -891,19 +891,29 @@ end (Base.@atomic :monotonic h.last_groups) != l.total || serial_duration(h, l.total) == 0 start = cycle_counter() - host_run(l, 0, l.total, scratch) + host_run_all(l, scratch) duration = cycle_counter() - start record_serial_sample(h, l.total, duration) Base.@atomic :monotonic h.last_duration = duration Base.@atomic :monotonic h.untimed = host_untimed_launches else - host_run(l, 0, l.total, scratch) + host_run_all(l, scratch) Base.@atomic :monotonic h.untimed = untimed - 1 end Base.@atomic :monotonic h.last_groups = l.total return end +# unsplit launches call PoCL directly to avoid materializing `HostLaunch` in memory +@inline function host_run_all(l::HostLaunch, scratch::Ptr{Cvoid}) + if l.full === l.h + host_run(l.h, l.arg_values, l.num_groups, 0, l.total, l.exception_info, scratch) + else + host_run(l, 0, l.total, scratch) + end + return +end + # private scratch avoids locks and task switches, which finalizers cannot perform @noinline function host_dispatch_finalizer(l::HostLaunch) # alignment is a power of two, and at least that of malloc