diff --git a/Project.toml b/Project.toml index 940e8f4c6..13c16b4da 100644 --- a/Project.toml +++ b/Project.toml @@ -23,6 +23,7 @@ SPIRVIntrinsics = "71d1d633-e7e8-4a92-83a1-de8814b09ba8" SPIRV_LLVM_Backend_jll = "4376b9bf-cff8-51b6-bb48-39421dff0d0c" SPIRV_Tools_jll = "6ac6d60f-d740-5983-97d7-a4482c0689f4" StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +ThreadTeams = "100744f9-5cbb-42a9-938e-f15a20f71997" UnsafeAtomics = "013be700-e6cd-48c3-b4a1-df204f14c38f" pocl_standalone_jll = "54f56a70-6062-5590-a942-1226658f6c83" @@ -67,6 +68,8 @@ SPIRV_Tools_jll = "2024.4, 2025.1" SparseArrays = "<0.0.1, 1.6" StaticArrays = "1.5" StaticArraysCore = "1" +# 1.3: `foreach_range` steals from nearby threads first +ThreadTeams = "1.4" UnsafeAtomics = "0.4" julia = "1.10" oneAPI = "2" diff --git a/docs/src/examples/numa_aware.md b/docs/src/examples/numa_aware.md index ad14ba484..adb75adeb 100644 --- a/docs/src/examples/numa_aware.md +++ b/docs/src/examples/numa_aware.md @@ -15,24 +15,21 @@ $(read(path, String)) **Important remarks:** -The `CPU` backend runs kernels with [PoCL](https://portablecl.org) on PoCL's own threads, not on Julia's. That determines how to apply the usual advice for NUMA systems: +The `CPU` backend runs kernels on Julia's threads (see [`CPU`](@ref)). For NUMA locality: -1) Pin the threads that run the kernels. Set PoCL's `POCL_AFFINITY=1` environment variable before the backend is first used. It pins each of PoCL's threads to one of the CPUs the process may run on (respecting e.g. `taskset`), a core of its own first, spread over the NUMA domains, so that fewer threads than cores still use the memory bandwidth of every domain. Tools that pin Julia's threads, like [ThreadPinning.jl](https://github.com/carstenbauer/ThreadPinning.jl), don't affect the threads that run the kernels. Without pinning, the operating system moves the threads around, and where they touch the memory first says little about where they run later. +1) Pin Julia's threads before the first launch with [ThreadPinning.jl](https://github.com/carstenbauer/ThreadPinning.jl). `pinthreads(:numa)` spreads threads across NUMA domains; `pinthreads(:cores)` follows the machine's topology. Both pin only the default pool. Start Julia with `-t N,0` or pass `threadpool = :all` to pin small launches on the launching thread too. Without pinning, threads can migrate away from the memory they first touched. 2) Choose the number of threads with `julia -t N` or the `JULIA_KA_CPU_THREADS` environment variable; see [`CPU`](@ref). -3) Initialize your data in parallel(!), with a kernel. Under the ["NUMA first-touch policy"](https://queue.acm.org/detail.cfm?id=2513149#:~:text=This%20is%20called%20the%20first,policy%20associated%20with%20a%20task.) a page of memory is placed in the memory domain of the thread that first writes to it. `fill!` writes from the calling thread, which places all the memory in that thread's domain. The example instead allocates with `KernelAbstractions.allocate` and writes the initial values with a kernel (`init = :parallel`). PoCL gives each thread a contiguous block of a kernel's workgroups, so a later kernel with as many workgroups mostly works on each part of the array from the thread that touched it first. `KernelAbstractions.zeros(backend, dtype, N)` and `KernelAbstractions.ones` initialize with a kernel too, for arrays of bits types of at least 1 MiB; smaller arrays, and arrays of other types, are filled from the calling thread. - -This needs KernelAbstractions 0.10.2 or later, which avoids the masked memory accesses that made kernels slow on some AMD CPUs, and the `pocl_standalone_jll` 7.2.3+1 or later that it installs, whose PoCL schedules workgroups and pins threads this way. +3) Initialize data with a parallel kernel. Under the [NUMA first-touch policy](https://queue.acm.org/detail.cfm?id=2513149#:~:text=This%20is%20called%20the%20first,policy%20associated%20with%20a%20task.), a memory page belongs to the domain of the thread that first writes it. `fill!` places pages in the calling thread's domain. The example uses `KernelAbstractions.allocate` followed by an initialization kernel (`init = :parallel`). Launches with as many workgroups start each block of them on the same thread, as `Threads.@threads :static` does, so later kernels mostly work on the data their thread touched first. `KernelAbstractions.zeros(backend, dtype, N)` and `KernelAbstractions.ones` also use a kernel for arrays of bits types of at least 1 MiB; other arrays are filled on the calling thread. **Demonstration:** -On a system with two AMD EPYC 7502 (2 × 32 cores, 2 NUMA domains), the example (`N = 512_000_000`, workgroups of 1024) gets the following memory bandwidth, in GB/s: +On a system with two AMD EPYC 7502 (2 × 32 cores, 2 NUMA domains), the example (`N = 512_000_000`, workgroups of 1024), started with `-t T,0` for each thread count `T`, gets the following memory bandwidth, in GB/s: -| threads | initialization | `POCL_AFFINITY=1` | `POCL_AFFINITY` unset | +| threads | initialization | `pinthreads(:numa)` | `pinthreads(:cores)` | |--:|---|--:|--:| -| 64 | `init = :parallel`, or `zeros` and `ones` | 242 | 130–155 | -| 64 | `init = :serial` | 142 | 137 | -| 32 | `init = :parallel`, or `zeros` and `ones` | 157 | 121–135 | -| 32 | `init = :serial` | 124 | 121–139 | +| 64 | `init = :parallel` | 243 | 243 | +| 64 | `zeros` and `ones` | 241 | 242 | +| 32 | `init = :parallel` | 158 | | A plain `Threads.@threads :static` loop with its threads pinned by ThreadPinning.jl gets 240 GB/s with 64 threads. Initializing serially puts all the memory in one domain. Without pinning, the threads that touch the memory first aren't reliably the ones that work on it later, and the numbers vary from run to run with where the operating system places the threads. diff --git a/docs/src/index.md b/docs/src/index.md index 79ccb47d1..dbc75910c 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -218,6 +218,25 @@ end workgroup, on every backend. `@groupreduce` uses sub-groups internally where the backend can shuffle the values. See [Reductions and scans](@ref group_collectives). +#### Unreleased +- The `CPU` backend runs kernels on Julia's threads instead of PoCL's, through PoCL's + `cl_pocl_host_kernel` extension (`pocl_standalone_jll` 7.2.3 or later). On a 4-core x86 + machine, a launch costs about 0.15 µs on the launching task and 1 µs on several threads, + down from 5 µs. Small launches, and launches while the threads are busy (e.g. from a + `Threads.@threads` loop), run on the launching task alone. A launch doesn't yield while + its kernel runs. See [`CPU`](@ref). +- Launches with as many workgroups start each block of them on the thread on which a + `Threads.@threads :static` loop over as many iterations runs it, so data stays in that + thread's cache and NUMA node. Pin Julia's threads before the first launch, e.g. with + ThreadPinning.jl; `POCL_AFFINITY` only applies to the few kernels that still run on + PoCL's threads. +- On the `CPU` backend, work-items no longer check whether they are inside the range when + the workgroups cover it exactly, and otherwise only those of partial workgroups do (from + a kernel's second launch with partial workgroups on, so that a kernel launched once is + compiled once). This lets PoCL vectorize kernels better: an axpy over 10⁵ elements on one + thread took about 15% longer than a serial loop, rather than 3× (x86) to 7× (Apple M1) as + long. `muladd` is computed with fused multiply-adds on CPUs that have them. + ## Semantic differences ### To CUDA.jl/AMDGPU.jl diff --git a/docs/src/quickstart.md b/docs/src/quickstart.md index 90fe0583b..bd82ac3dc 100644 --- a/docs/src/quickstart.md +++ b/docs/src/quickstart.md @@ -195,8 +195,11 @@ function exchange_and_compute!(backend, A, B) end ``` -Waiting on a backend, whether with [`synchronize`](@ref) or at the end of a spawned task, -yields to the Julia scheduler, so other tasks keep making progress while a kernel runs. +Waiting on a GPU backend, whether with [`synchronize`](@ref) or at the end of a spawned +task, yields to the Julia scheduler, so other tasks keep making progress while a kernel runs. +The `CPU` backend runs every launch to completion before it returns, without yielding; +other tasks, timers and I/O run after launches on several threads and after long ones (see +[`CPU`](@ref)). ### Which device a task runs on diff --git a/examples/numa_aware.jl b/examples/numa_aware.jl index daa1dbe5e..f18b228f0 100644 --- a/examples/numa_aware.jl +++ b/examples/numa_aware.jl @@ -1,6 +1,6 @@ # EXCLUDE FROM TESTING -# Run with `POCL_AFFINITY=1` to pin the threads that run the kernels, e.g. -# POCL_AFFINITY=1 julia -t 128 examples/numa_aware.jl +# pin Julia's threads before the first launch: +# julia -t 128,0 -e 'using ThreadPinning; pinthreads(:numa); include("examples/numa_aware.jl")' using BenchmarkTools using KernelAbstractions diff --git a/src/KernelAbstractions.jl b/src/KernelAbstractions.jl index 1548b6509..bda2510d3 100644 --- a/src/KernelAbstractions.jl +++ b/src/KernelAbstractions.jl @@ -788,14 +788,42 @@ synchronize(CPU()) # Threads -Kernels run on as many threads as Julia's default thread pool has (`julia -t N`), up to the -number of hardware threads. These are POCL's own threads, so launching a kernel doesn't -occupy Julia's. To use a different number, set the `JULIA_KA_CPU_THREADS` environment -variable before the backend is first used, e.g., `JULIA_KA_CPU_THREADS=8 julia -t1`. POCL's -own variables (e.g., `POCL_CPU_MAX_CU_COUNT`) are respected too, and can also raise the -number above the number of hardware threads, but they also affect other users of POCL, like -OpenCL.jl. The device reports the number as its compute units: -`KernelAbstractions.POCL.device().max_compute_units`. +Kernels run on Julia's default thread pool (`julia -t N`), up to the number of hardware +threads. A launch splits its workgroups into blocks as `Threads.@threads :static` splits a +loop: block `k` starts on the `k`-th thread of the pool, whichever thread launches, and the +launching task runs the block of its own thread. + +Launches of up to 8192 work-items run on the launching task alone, unless the kernel's last +two launches over as many workgroups would each have taken 4 µs or more on one thread. So +do launches from finalizers, and launches while the threads are busy: from a +`Threads.@threads` loop, from a kernel, or while another task's launch uses them. On Julia +1.12 and later, such a launch from the interactive thread (`julia -t N,1`) runs there. + +A launch doesn't yield while its kernel runs, and delivers interrupts (`^C`) once it is +done. Before Julia 1.14, `^C` goes to whatever runs on thread 1, so this only protects +launches from there (e.g. the main task). Other tasks, timers and I/O run after launches on several threads, and after +launches of a kernel whose last launch took 50 µs or more. + +Since launches with as many workgroups start each block on the same thread, data that a +`Threads.@threads :static` loop or such a launch wrote first is usually in that thread's +cache and NUMA node. Workgroups still move: a block whose thread starts late runs on the +launching thread, and when the number of workgroups changed or the last launch took 50 µs +or more, threads that are done take workgroups from the others, nearby threads first (on +Linux, with pinned threads). + +Pin the threads before the first launch, e.g. with ThreadPinning.jl: `pinthreads(:numa)` +or `pinthreads(:cores)`. It pins only the default pool, so start Julia with `julia -t N,0`, +or pass `threadpool = :all`, to also pin launches on the launching task. + +Kernels with an explicit workgroup size that may need more than 1 MiB of stack, and +kernels that PoCL can't run on Julia's threads, run on PoCL's own threads instead; pin +those with `POCL_AFFINITY=1`. + +To use fewer threads, set `JULIA_KA_CPU_THREADS` before the backend is first used: +launches then use the first threads of the default pool, with larger blocks. PoCL's +variables (e.g. `POCL_CPU_MAX_CU_COUNT`) work too, but also affect other users of PoCL, +like OpenCL.jl. None of them raises the count above the pool's size; +`KernelAbstractions.KernelInterface.multiprocessor_count(CPU())` returns the count used. # Atomics diff --git a/src/backend_launch.jl b/src/backend_launch.jl index 0f709ff8a..b0e2bd7c1 100644 --- a/src/backend_launch.jl +++ b/src/backend_launch.jl @@ -180,10 +180,21 @@ function launch_kernel( end ctx, groups, items = launch_geometry(sizes_only(obj), launch, subgroups, ndrange, iterspace, ctx, threads) - # the kernel's limits aren't the device's, and the workgroups tuned for them don't cover - # the ndrange: launch the checked kernel instead - if unchecked && tuned && !covers(range, ctx) - return launch_kernel(obj, launch, subgroups, ndrange, _workgroupsize, iterspace, args, true) + # 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) + unchecked && + return launch_kernel(obj, launch, subgroups, ndrange, _workgroupsize, iterspace, args, true) + extent = split_extent(size(cartesian(range)), items) + if extent !== nothing && split_launch(b, launch, kernel) + full_tt = Base.compilerbarrier(:type, without_bounds_check(tt))::Type + full = kernel_function_as(b, obj.f, full_tt, tt; compiler_options(obj)...) + if prod(items) <= KI.max_work_group_size(full) + launch_split(full, kernel, extent, groups, items, prepend(ctx, kernel_args)) + return nothing + end + end end KI.check_work_group_size(kernel, items) @@ -206,6 +217,34 @@ specializing on `compiled_tt`. """ function kernel_function_as end +""" + split_launch(backend, launch, checked)::Bool + +Whether to run full workgroups unchecked and partial ones with `checked`, using +[`launch_split`](@ref). A backend may decline early launches to avoid compiling an unchecked +variant for kernels used only once. Only called if `skip_bounds_check(backend)`. +""" +split_launch(backend, launch, checked) = false + +# map `dims` to the launch grid, or return `nothing` if partial workgroups aren't confined +# to its edges. beyond 3 dimensions, `nd_grid` folds later dimensions into the third, +# placing partial third-dimension workgroups inside the grid. +function split_extent(dims::Dims{N}, items::Dims{3}) where {N} + N > 3 && dims[3] % items[3] != 0 && return nothing + return KI.pad3(nd_grid(dims)) +end + +""" + launch_split(kernel, checked, extent, groups, items, args) + +Run `groups` workgroups of `items` work-items as one launch. Workgroups entirely within +`extent` (the ndrange mapped by `split_extent`) use the unchecked `kernel`; the rest use +`checked`. Both take `args` with the same layout (see `kernel_function_as`). A backend may +fall back to `checked` for every workgroup. Only called if [`split_launch`](@ref) returned +`true`. +""" +function launch_split end + """ expected_workgroupsize(backend, nitems) diff --git a/src/pocl/backend.jl b/src/pocl/backend.jl index bce96a9ed..dda8af390 100644 --- a/src/pocl/backend.jl +++ b/src/pocl/backend.jl @@ -109,9 +109,9 @@ KA.@kernel function fill_kernel(A, x) @inbounds A[I] = x end -# Filling or copying into an array with a kernel first-touches its pages from PoCL's threads, -# which spreads them over the threads' memory domains instead of placing all of them in the -# calling thread's (see the NUMA example). Below 1 MiB, the launch overhead makes that up to +# Filling or copying into an array with a kernel first-touches its pages from the kernel's +# threads, which spreads them over the threads' memory domains instead of placing all of them +# in the calling thread's (see the NUMA example). Below 1 MiB, the launch overhead makes that up to # several times slower than writing from the host, while there are too few pages for # placement to matter. const KERNEL_FILL_BYTES = 1 << 20 @@ -217,9 +217,33 @@ function KI.launch(obj::KI.Kernel{POCLBackend}, groups::Dims{3}, items::Dims{3}, # compiled kernel only holds pointers to the arrays captured by `f`, so keep it alive # until the kernel completes. f = obj.kern.f - GC.@preserve f POCL.launch_and_wait( - obj.kern.kernel, args; local_size = items, global_size = groups .* items + k = obj.kern.kernel + global_size = groups .* items + # (see `KA.launch_split`, which shares this specialization) + GC.@preserve f POCL.launch_and_wait(k, args, k.fun, global_size, groups; local_size = items, global_size) + return nothing +end + +# split only N-d launches: linearized launches place partial work-groups where `host_run` +# cannot identify them. keep the first partial launch checked so kernels used once compile +# once. queue fallbacks also run every work-group checked. +function KA.split_launch(::POCLBackend, ::KA.NDLaunch, checked::KI.Kernel{POCLBackend}) + k = checked.kern.kernel.fun + (@atomic :monotonic k.launched_partial) && return true + @atomic :monotonic k.launched_partial = true + return false +end + +function KA.launch_split( + kernel::KI.Kernel{POCLBackend}, checked::KI.Kernel{POCLBackend}, extent::Dims{3}, + groups::Dims{3}, items::Dims{3}, args::Tuple ) + # keep captured arrays alive for both kernel variants + f = kernel.kern.f + k = kernel.kern.kernel + partial = checked.kern.kernel.fun + global_size = groups .* items + GC.@preserve f POCL.launch_and_wait(k, args, partial, extent, groups; local_size = items, global_size) return nothing end @@ -232,7 +256,7 @@ KI.max_num_groups(::POCLBackend)::NTuple{3, Int} = (typemax(Int), typemax(Int), KI.sub_group_size(::POCLBackend)::Int = device_limits().sub_group_size KI.multiprocessor_count(::POCLBackend)::Int = device_limits().compute_units -# PoCL runs each work-group on one of its threads, looping over (and vectorizing across) the +# each work-group runs on one thread, which loops over (and vectorizes across) its # work-items. the largest work-group would run a launch of up to that many work-items on a # single thread, so split it into about as many work-groups as there are threads, as long as # the work-groups stay large enough to vectorize. this assumes that the work is balanced @@ -244,7 +268,7 @@ KI.launch_configuration( # kept out of `KI.launch_configuration`, which is compiled for every kernel @noinline function launch_workgroupsize(kernel::cl.Kernel, nitems, max_work_group_size) - max_items = min(kernel.work_group_size, max_work_group_size) + max_items = min(kernel.tuned_work_group_size, max_work_group_size) items = cpu_workgroupsize( nitems, device_limits().compute_units, max_items, kernel.preferred_work_group_size_multiple ) @@ -267,32 +291,50 @@ end # keeps at least half its size. without one, the launch stays checked, but runs faster in # work-groups a quarter of the size (axpy, 1000003 work-items on 4 threads of a Ryzen 9 # 9950X: 71 vs 31 µs). +# vectorization is across the first dimension. below 16 vectors (of the preferred multiple), +# shrink it only to a vector-width multiple, never to a quarter: a scalar remainder costs +# more than a partial work-group (axpy, 1000 work-items on 32 threads: 146 ns in work-groups +# of 32, 162 ns of 25, 209 ns of 8). # (only shrink, so padding stays within the bound `KA.select_launch` assumes.) function KA.launch_workgroupsize(::POCLBackend, ::KA.NDLaunch, threads, ndrange) extent = KA.extents(ndrange) - limits = KA.nd_limits(device_limits().max_work_group_dims, extent) - items = KI.threads_to_workgroupsize(threads, extent, limits) - return map(fit_workgroup, extent, items) + limits = device_limits() + items = KI.threads_to_workgroupsize(threads, extent, KA.nd_limits(limits.max_work_group_dims, extent)) + width = limits.preferred_work_group_size_multiple + return ntuple(Val(length(extent))) do d + Base.@_inline_meta + n, x = extent[d], items[d] + small = d == 1 && width <= x < 16 * width + fit_workgroup(n, x, small ? width : 1, !small) + end end -function fit_workgroup(n::Int, x::Int) +# keep `x` if it divides `n`; otherwise use the largest multiple of `m` in `cld(x, 2):x` +# 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 - d = largest_divisor(n, x) - return d == 0 ? cld(x, 4) : d -end - -# the largest divisor of `n` in `cld(x, 2):x`, or 0 if there is none. searches the sizes -# or the work-group counts, whichever are fewer. requires `n % x != 0`: the size search -# skips `x` (`largest_divisor(8, 4) == 2`). -function largest_divisor(n::Int, x::Int) + d = largest_divisor(n, x, m) + d == 0 || return d + shrink || return x + return max(m, cld(x, 4) ÷ m * m) +end + +# the largest multiple of `m` in `cld(x, 2):x` that divides `n`, or 0 if none exists. search +# sizes or work-group counts, whichever are fewer. requires `n % x != 0`: the size search +# 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 lo = cld(x, 2) - if x - lo <= fld(n, lo) - cld(n, x) - for d in (x - 1):-1:lo + hi = (x - 1) ÷ m * m + if (hi - lo) ÷ m <= fld(n, lo) - cld(n, x) + for d in hi:-m:lo n % d == 0 && return d end else for g in cld(n, x):fld(n, lo) - n % g == 0 && return n ÷ g + n % g == 0 && (n ÷ g) % m == 0 && return n ÷ g end end return 0 @@ -311,7 +353,9 @@ function cpu_workgroupsize(nitems, threads, max_items, multiple) nitems === nothing && return max_items nitems = max(nitems, 1) min_items = min(4 * max(multiple, 1), max_items) - items = min(nextpow(2, min(nitems, max_items)), max_items) + 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 # PoCL splits by the largest factor of at most `splits` that divides the work-group @@ -321,6 +365,9 @@ function cpu_workgroupsize(nitems, threads, max_items, multiple) 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`) diff --git a/src/pocl/compiler/compilation.jl b/src/pocl/compiler/compilation.jl index 3379dcb08..666e6bf2e 100644 --- a/src/pocl/compiler/compilation.jl +++ b/src/pocl/compiler/compilation.jl @@ -295,5 +295,9 @@ function link_kernel(@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry: error("Your device does not support SPIR-V, which is currently required for native execution.") end cl.build!(prog) - return cl.Kernel(prog, entry) + kernel = cl.Kernel(prog, entry) + # cap tuned work-groups to avoid the queue fallback for excessive stack use; fitting to + # the ndrange can only shrink them further + kernel.tuned_work_group_size = min(kernel.work_group_size, host_kernel_max_items(kernel)) + return kernel end diff --git a/src/pocl/compiler/execution.jl b/src/pocl/compiler/execution.jl index f446bd17f..ad476096e 100644 --- a/src/pocl/compiler/execution.jl +++ b/src/pocl/compiler/execution.jl @@ -174,43 +174,83 @@ Core.kwcall(kwargs::NamedTuple, kernel::AbstractKernel, args::Vararg{Any, N}) wh launch_and_wait(kernel, args; kwargs...) # kernels operate on plain `Array`s, whose uses can't synchronize, so every launch waits for -# its kernel. this also keeps the arguments alive while the kernel runs. waiting yields to -# other tasks, as `synchronize` should (see the documentation on its semantics). -function launch_and_wait(kernel::AbstractKernel, args::Tuple; kwargs...) - info = exception_info() - info[] = ExceptionInfo_st() - GC.@preserve args info begin - event = launch_tuple(kernel, args, Base.unsafe_convert(Ptr{ExceptionInfo_st}, info); kwargs...) - wait_for_kernel(event, info) +# completion, keeping arguments alive. queue waits yield; host launches yield only after +# team or long launches (see `host_dispatch`). +# +# work-groups extending beyond `extent` run `partial`, a bounds-checked variant with the +# same argument layout. both variants share arguments and exception status. queue launches +# use `partial` for all work-groups: separate queued kernels cannot share group ids. +# `groups` is the work-group count, if known. +function launch_and_wait( + kernel::AbstractKernel, args::Tuple, partial = nothing, extent = nothing, + groups = nothing; kwargs... + ) + GC.@preserve args begin + # prepare both variants before running either; if the unchecked variant is + # 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) + 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...) + wait_for_kernel(event) + end + check_exception(info) + else + global_size = values(kwargs).global_size + num_groups = something(groups, global_size .÷ hp.local_size) + extent = something(extent, global_size) + # host launches finish before returning, even when interrupted + 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) + end + # passing the status avoids allocating `info` + check_exception(info[].status) + end end return nothing end # kept out of `launch_and_wait`, which is compiled for every kernel -@noinline function wait_for_kernel(event::cl.Event, info::Base.RefValue{ExceptionInfo_st}) +@noinline function wait_for_kernel(event::cl.Event) try wait(event) finally cl.clReleaseEvent(event) end - info[].status == 0 || throw(KernelException(device())) return end +check_exception(info::Base.RefValue{ExceptionInfo_st}) = check_exception(info[].status) +@inline function check_exception(status::Int32) + status == 0 || throw_kernel_exception() + return +end +@noinline throw_kernel_exception() = throw(KernelException(device())) + @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) +# kept out of the launches, which are compiled for every kernel: inlining `rand` makes them +# several times as expensive to compile +@inline kernel_state(rng_state::Bool, exception_info::Ptr) = + 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) 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[ - :(KernelState(kernel.rng_state ? Base.rand(UInt32) : UInt32(0), UInt64(UInt(exception_info)))), - ] + call_args = Any[:(kernel_state(kernel.rng_state, exception_info))] for (dt, ex) in zip(params, exprs) # filter out ghost arguments that shouldn't be passed pass_arg(dt) || continue @@ -253,8 +293,9 @@ end Base.showerror(io::IO, err::KernelException) = print(io, "KernelException: exception thrown during kernel execution on device ", err.dev.name) -# where kernels report exceptions: per task, as a task waits for every kernel it launches -exception_info() = get!(task_local_storage(), :POCLExceptionInfo) do +# queue-fallback exception storage is per task, since each task waits for its launches. it +# must outlive the stack frame, as an interrupted wait leaves the kernel running. +@noinline exception_info() = get!(task_local_storage(), :POCLExceptionInfo) do Ref(ExceptionInfo_st()) end::Base.RefValue{ExceptionInfo_st} @@ -267,6 +308,11 @@ struct HostKernel{F, TT} <: AbstractKernel{F, TT} rng_state::Bool end +# `kernel`, with `fun`, a variant of its compiled kernel for arguments of the same layout +@inline with_fun(kernel::AbstractKernel, ::Nothing) = kernel +@inline with_fun(kernel::HostKernel{F, TT}, fun::cl.Kernel) where {F, TT} = + HostKernel{F, TT}(kernel.f, fun, kernel.rng_state) + ## host-side API @@ -366,3 +412,506 @@ end end return res end + + +## host kernels +# +# `cl_pocl_host_kernel` runs work-groups on the calling thread without queues or events. +# small launches stay on the launching task; larger ones use a persistent Julia task team +# (see `ThreadTeams.foreach_range`). + +import ThreadTeams + +# `foreach_range` limits for team launches and stealing, respectively. above these, run on +# the launching task or disable stealing (see `host_schedule`). +const host_team_max_groups = typemax(Int) >> 2 +const host_steal_max_groups = Int(typemax(Int32)) + +# a team costs about 1 µs to start and join. a trivial kernel (store or axpy) needs about +# 8192 work-items to recover that cost on 4 or 8 threads (see `host_schedule`). +const host_kernel_serial_items = 8192 + +# 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. +const host_kernel_stack_limit = 1024 * 1024 + +# the largest power-of-two work-group of `k` within `host_kernel_stack_limit` (1 if a single +# work-item exceeds it) +function host_kernel_max_items(k::cl.Kernel) + k.private_mem_size == 0 && return typemax(Int) + return prevpow(2, max(host_kernel_stack_limit ÷ k.private_mem_size, 1)) +end + +@inline function host_kernel(kernel::HostKernel, kwargs::NamedTuple, groups) + haskey(kwargs, :local_size) && haskey(kwargs, :global_size) || return nothing + local_size, global_size = kwargs.local_size, kwargs.global_size + local_size isa Dims{3} && global_size isa Dims{3} || return nothing + # host kernels only run whole work-groups + groups === nothing && global_size .% local_size != (0, 0, 0) && return nothing + return host_kernel(kernel.fun, local_size, kernel.rng_state) +end + +# use the unchecked variant at `hp`'s work-group size, or keep `hp` if it is unavailable +@inline function full_host_kernel(kernel::HostKernel, partial, hp::cl.HostKernelHandle) + (partial === nothing || partial === kernel.fun) && return hp + return something(host_kernel(kernel.fun, hp.local_size, kernel.rng_state), hp) +end + +# kept out of `launch_and_wait`, which is compiled for every kernel +@noinline function host_kernel(k::cl.Kernel, local_size::Dims{3}, rng_state::Bool) + h = Base.@atomic :acquire k.host_kernel + if h === nothing || h.local_size != local_size + h = host_kernel_slow(k, local_size, rng_state) + end + return h.id == C_NULL ? nothing : h +end + +@noinline function host_kernel_slow(k::cl.Kernel, local_size::Dims{3}, rng_state::Bool) + h = @lock k.lock begin + i = findfirst(h -> h.local_size == local_size, k.host_kernels) + if i === nothing + h = create_host_kernel(k, local_size, rng_state) + push!(k.host_kernels, h) + h + else + k.host_kernels[i] + end + end + Base.@atomic :release k.host_kernel = h + return h +end + +# with `k.lock` held +function create_host_kernel(k::cl.Kernel, local_size::Dims{3}, rng_state::Bool) + dev = device() + stack = k.private_mem_size * prod(local_size) + stack > host_kernel_stack_limit && return cl.HostKernelHandle(C_NULL, local_size) + + # the host kernel takes the sizes of local memory arguments from the kernel + lsize = Csize_t[local_size...] + if rng_state + num_sub_groups = cl.KernelSubGroupInfo(k, dev, lsize).sub_group_count + nargs = cl.num_args(k) - 2 + # one UInt32 per sub-group + cl.set_arg!(k, nargs + 1, cl.LocalMem(UInt32, num_sub_groups)) + cl.set_arg!(k, nargs + 2, cl.LocalMem(UInt32, num_sub_groups)) + end + + err = Ref{Int32}() + id = cl.clCreateHostKernelPOCL(k, dev, 3, lsize, err) + # don't remember transient failures + err[] == cl.CL_OUT_OF_HOST_MEMORY && throw(OutOfMemoryError()) + if err[] != cl.CL_SUCCESS + # e.g. the kernel needs more local memory than a host kernel can have + @debug "Kernel can't run on Julia's threads, using PoCL's" exception = cl.CLError(err[]) + return cl.HostKernelHandle(C_NULL, local_size) + end + scratch_size, scratch_alignment = Ref{Csize_t}(), Ref{Csize_t}() + cl.clGetHostKernelInfoPOCL( + id, cl.CL_HOST_KERNEL_SCRATCH_SIZE_POCL, sizeof(Csize_t), scratch_size, C_NULL + ) + cl.clGetHostKernelInfoPOCL( + id, cl.CL_HOST_KERNEL_SCRATCH_ALIGNMENT_POCL, sizeof(Csize_t), scratch_alignment, C_NULL + ) + return cl.HostKernelHandle(id, local_size, Int(scratch_size[]), Int(scratch_alignment[])) +end + +# per-thread local memory and printf buffer. runs must not yield: they share scratch storage +# and must not overlap. look up the thread after the last possible yield, which may migrate +# the task. only the owning thread mutates its `HostScratch`; adding threads replaces the +# slots vector. +mutable struct HostScratch + ptr::Ptr{Cvoid} # aligned + raw::Ptr{Cvoid} + size::Int + events_run::UInt64 # see `run_other_tasks` +end + +mutable struct HostScratchSlots + Base.@atomic slots::Vector{HostScratch} + const lock::ReentrantLock +end + +const host_scratch = HostScratchSlots(HostScratch[], ReentrantLock()) + +@inline function host_scratch_ptr(size::Int, alignment::Int) + s = host_scratch_slot() + # (the alignment is a power of two) + if s.size < size || UInt(s.ptr) & (alignment - 1) != 0 + grow_host_scratch!(s, size, alignment) + end + return s.ptr +end + +@inline function host_scratch_slot() + while true + tid = Threads.threadid() + slots = Base.@atomic :acquire host_scratch.slots + tid <= length(slots) && return @inbounds slots[tid] + # may yield, so look the thread up again afterwards + add_host_scratch_slots() + end + return +end + +# doesn't yield +@noinline function grow_host_scratch!(s::HostScratch, size::Int, alignment::Int) + # alignment is a power of two, and at least that of malloc + size = max(size, s.size, 64 * 1024) + align = max(alignment, 64) + raw = Libc.malloc(size + align) + raw == C_NULL && throw(OutOfMemoryError()) + Libc.free(s.raw) + s.raw = raw + s.ptr = Ptr{Cvoid}((UInt(raw) + align - 1) & ~UInt(align - 1)) + s.size = size + return +end + +@noinline function add_host_scratch_slots() + @lock host_scratch.lock begin + slots = Base.@atomic :acquire host_scratch.slots + n = Threads.maxthreadid() + if n > length(slots) + new = [slots; [HostScratch(C_NULL, C_NULL, 0, 0) for _ in (length(slots) + 1):n]] + Base.@atomic :release host_scratch.slots = new + end + end + return +end + +# run `first_group:first_group + group_count - 1`; report PoCL traps through the launch's +# exception status +@inline function host_run( + h::cl.HostKernelHandle, arg_values::Ptr{Ptr{Cvoid}}, num_groups::Ptr{Csize_t}, + first_group::Int, group_count::Int, exception_info::Ptr{ExceptionInfo_st}, + scratch::Ptr{Cvoid} + ) + err = cl.clRunHostKernelPOCL( + h.id, arg_values, num_groups, first_group, group_count, scratch + ) + if err != cl.CL_SUCCESS + status = reinterpret(Ptr{Int32}, exception_info) + UnsafeAtomics.store!(status, Int32(err), UnsafeAtomics.release) + end + return +end + +# a callable struct keeps team code shared across kernels. up to `threads` threads run +# ranges of work-groups, stealing if `steal` is set (see `run_team`). +# +# `full` runs work-groups entirely within the ndrange; `h` runs partial ones. both use the +# same argument layout. `full === h` when no unchecked variant is needed or available. +struct HostLaunch + h::cl.HostKernelHandle + full::cl.HostKernelHandle + arg_values::Ptr{Ptr{Cvoid}} + num_groups::Ptr{Csize_t} + groups::Dims{3} + partial::NTuple{3, Bool} + total::Int + threads::Int + steal::Bool + scratch_size::Int + scratch_alignment::Int + exception_info::Ptr{ExceptionInfo_st} +end + +# batch `first:last-1` into runs of full or partial work-groups. x varies fastest: a +# partial x dimension affects each row's last group; partial y or z dimensions affect whole +# rows. +function host_run(l::HostLaunch, first::Int, last::Int, scratch::Ptr{Cvoid}) + if l.full === l.h + host_run(l.h, l.arg_values, l.num_groups, first, last - first, l.exception_info, scratch) + return + end + gx, gy, gz = l.groups + px, py, pz = l.partial + g = first + while g < last + row = g ÷ gx + x = g - row * gx + y, z = row % gy, row ÷ gy + if pz && z == gz - 1 + # the rest of the launch + h, stop = l.h, l.total + elseif py && y == gy - 1 + h, stop = l.h, (row + 1) * gx + elseif px && x == gx - 1 + h, stop = l.h, g + 1 + else + # up to the next partial work-group + h = l.full + stop = px ? row * gx + gx - 1 : + py ? (z * gy + gy - 1) * gx : + pz ? (gz - 1) * gy * gx : l.total + end + stop = min(stop, last) + host_run(h, l.arg_values, l.num_groups, g, stop - g, l.exception_info, scratch) + g = stop + end + return +end + +# `foreach_range` uses inclusive, 1-based ranges. time the range containing group 1 and +# scale to all groups to estimate the launch's serial duration. +function (l::HostLaunch)(first::Int, last::Int) + scratch = host_scratch_ptr(l.scratch_size, l.scratch_alignment) + if first != 1 + host_run(l, first - 1, last, scratch) + return + end + start = cycle_counter() + host_run(l, 0, last, scratch) + duration = cycle_counter() - start + # (in floating point: the product may not fit) + sample = unsafe_trunc(UInt64, min(Float64(duration) * (l.total / last), 0x1p63)) + record_serial_sample(l.h, l.total, sample) + return +end + +# racy by design: these statistics affect scheduling policy only +@inline function record_serial_sample(h::cl.HostKernelHandle, groups::Int, sample::UInt64) + if (Base.@atomic :monotonic h.serial_groups_a) == groups + previous = Base.@atomic :monotonic h.serial_sample_a + else + previous = (Base.@atomic :monotonic h.serial_groups_b) == groups ? + (Base.@atomic :monotonic h.serial_sample_b) : UInt64(0) + # move the previous grid to slot b + g = Base.@atomic :monotonic h.serial_groups_a + sample_a = Base.@atomic :monotonic h.serial_sample_a + duration_a = Base.@atomic :monotonic h.serial_duration_a + Base.@atomic :monotonic h.serial_groups_b = g + Base.@atomic :monotonic h.serial_sample_b = sample_a + Base.@atomic :monotonic h.serial_duration_b = duration_a + Base.@atomic :monotonic h.serial_groups_a = groups + end + Base.@atomic :monotonic h.serial_sample_a = sample + Base.@atomic :monotonic h.serial_duration_a = min(sample, previous) + return +end + +# the lesser of the last two estimates for a grid of `groups` work-groups, zero if unknown +@inline function serial_duration(h::cl.HostKernelHandle, groups::Int) + (Base.@atomic :monotonic h.serial_groups_a) == groups && + return Base.@atomic :monotonic h.serial_duration_a + (Base.@atomic :monotonic h.serial_groups_b) == groups && + return Base.@atomic :monotonic h.serial_duration_b + return UInt64(0) +end + +# defer interrupts until all work-groups finish. otherwise a team skips unstarted ranges, +# and a serial launch can stop between full and partial groups. +function (l::HostLaunch)() + if l.threads == 1 + uninterruptible(run_serial, l) + else + uninterruptible(run_team, l) + end + return +end + +run_serial(l::HostLaunch) = l(1, l.total) + +# assign blocks as in `Threads.@threads :static`, independent of the launching thread, to +# preserve cache and NUMA locality across equal-sized grids. stealing prevents slow or +# descheduled threads from holding up the launch. a busy team (including nested launches and +# `Threads.@threads` loops) runs the launch on the calling task. +# +# `isolate`: waiting for the team would otherwise run other tasks, and on Julia 1.13 and +# earlier a deferred interrupt then goes to the next task on thread 1, not the launch. +run_team(l::HostLaunch) = ThreadTeams.foreach_range( + l, l.total; threads = l.threads, schedule = l.steal ? :steal : :static, isolate = true +) + +# `f(x)`, with interrupts and (on Julia 1.14+) cancellation delivered after it returns +@inline function uninterruptible(f::F, x) where {F} + @static if isdefined(Base, :CANCEL_TOKEN) + if Base.CANCEL_TOKEN[] === nothing + f(x) + else + Base.ScopedValues.with(() -> f(x), Base.CANCEL_TOKEN => nothing) + Base.checkcancel(Base.CANCEL_TOKEN[]) + end + else + # `disable_sigint`, without a closure + Base.sigatomic_begin() + try + f(x) + finally + Base.sigatomic_end() + end + end + return +end + +# shared across kernels: avoid inlining and specialization. `h` runs partial work-groups, +# `full` the rest (see `launch_and_wait`). +@noinline function host_dispatch( + h::cl.HostKernelHandle, arg_values::Ptr{Ptr{Cvoid}}, num_groups::Dims{3}, + exception_info::Ptr{ExceptionInfo_st}, full::cl.HostKernelHandle, extent::Dims{3} + ) + total = prod(num_groups) + total == 0 && return + partial = extent .< num_groups .* h.local_size + any(partial) || (full = h) + scratch_size = max(h.scratch_size, full.scratch_size) + scratch_alignment = max(h.scratch_alignment, full.scratch_alignment) + groups_ref = Ref(Csize_t.(num_groups)) + GC.@preserve groups_ref begin + groups_ptr = Ptr{Csize_t}(Base.unsafe_convert(Ptr{NTuple{3, Csize_t}}, groups_ref)) + launch = HostLaunch( + h, full, arg_values, groups_ptr, num_groups, partial, total, 1, false, + scratch_size, scratch_alignment, exception_info + ) + # finalizers can't switch tasks, which waiting for other threads and taking the + # lock of the scratch slots may do + if GC.in_finalizer() + host_dispatch_finalizer(launch) + return + end + s = session() + long = (Base.@atomic :monotonic h.last_duration) >= s.host_kernel_long_ticks + threads, steal = host_schedule(h, s, total, long) + if threads == 1 && !long + if full === h + run_short(launch) + else + uninterruptible(run_short, launch) + end + return + end + # create the slots of all threads now, so the work-groups' lookups never take the lock + host_scratch_slot() + start = cycle_counter() + launch = HostLaunch( + h, full, arg_values, groups_ptr, num_groups, partial, total, threads, steal, + scratch_size, scratch_alignment, exception_info + ) + launch() + Base.@atomic :monotonic h.last_duration = cycle_counter() - start + Base.@atomic :monotonic h.last_groups = total + end + # yield after team or long launches so repeated launches don't starve tasks, timers or + # I/O + run_other_tasks() + return +end + +# service waiting tasks; otherwise poll timers and I/O at most once per millisecond (the +# timer resolution). polling and yielding each cost 12 µs on macOS. track polls per thread: +# only one thread services events, outside `Threads.@threads`. +@noinline function run_other_tasks() + if !other_tasks() + s = host_scratch_slot() + now = time_ns() + now - s.events_run < 1_000_000 && return + s.events_run = now + Base.process_events() + other_tasks() || return + end + yield() + return +end + +@inline function other_tasks() + @static if isdefined(Base, :workqueue_for) && isdefined(Base, :Partr) && + isdefined(Base.Partr, :multiq_check_empty) + return !isempty(Base.workqueue_for(Threads.threadid())) || + !Base.Partr.multiq_check_empty() + else + return true + end +end + +# choose the thread count and stealing policy. only the `foreach_range` limits constrain +# correctness. +# +# small grids stay on one thread unless both recent serial estimates reach the threshold. +# estimates are per grid because work per item can vary with grid size. timing the first +# range also gives an estimate for team launches. switching between serial and team launches +# moves data between caches; keep the threshold well above trivial-kernel times to avoid +# repeated switching. +# +# use static blocks after a short launch of the same grid. first or long launches allow +# stealing so slow or descheduled threads don't hold up the team. both policies start blocks +# on the same threads, preserving locality. +function host_schedule(h::cl.HostKernelHandle, s::Session, total::Int, long::Bool) + threads = min(total, s.limits.compute_units) + (threads > 1 && total <= host_team_max_groups) || return 1, false + # (dividing: the number of work-items may not fit) + if total <= host_kernel_serial_items ÷ prod(h.local_size) && + serial_duration(h, total) < s.host_kernel_serial_ticks + return 1, false + end + steal = long || (Base.@atomic :monotonic h.last_groups) != total + return threads, steal && total <= host_steal_max_groups +end + +# a short launch on the launching task: one run covers the whole launch, so one timing +# 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 + 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 + align = l.scratch_alignment + raw = Libc.malloc(l.scratch_size + align) + raw == C_NULL && throw(OutOfMemoryError()) + scratch = Ptr{Cvoid}((UInt(raw) + align - 1) & ~UInt(align - 1)) + try + host_run(l, 0, l.total, scratch) + finally + Libc.free(raw) + end + return +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} + 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) + + # 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) + end + end + nothing + end +end diff --git a/src/pocl/nanoOpenCL.jl b/src/pocl/nanoOpenCL.jl index 233a01795..23f05ddb5 100644 --- a/src/pocl/nanoOpenCL.jl +++ b/src/pocl/nanoOpenCL.jl @@ -62,6 +62,8 @@ const CL_DEVICE_NOT_FOUND = -1 const CL_DEVICE_NOT_AVAILABLE = -2 +const CL_OUT_OF_HOST_MEMORY = -6 + const CL_INVALID_ARG_INDEX = -49 const CL_INVALID_ARG_VALUE = -50 @@ -648,6 +650,49 @@ end @gcsafe_ccall libopencl.POclReleaseKernel(kernel::cl_kernel)::cl_int end +# `cl_pocl_host_kernel` runs work-groups on the calling thread (PoCL's +# `include/CL/cl_ext_pocl.h`). all supported pocl_standalone_jll builds provide it; +# `Session()` rejects devices without it. + +const cl_host_kernel_pocl = Ptr{Cvoid} + +const CL_HOST_KERNEL_SCRATCH_SIZE_POCL = 0x4511 +const CL_HOST_KERNEL_SCRATCH_ALIGNMENT_POCL = 0x4512 + +function clCreateHostKernelPOCL(kernel, device, work_dim, local_work_size, errcode_ret) + return @gcsafe_ccall libopencl.POclCreateHostKernelPOCL( + kernel::cl_kernel, device::cl_device_id, work_dim::cl_uint, + local_work_size::Ptr{Csize_t}, errcode_ret::Ptr{cl_int} + )::cl_host_kernel_pocl +end + +@checked function clGetHostKernelInfoPOCL( + host_kernel, param_name, param_value_size, param_value, param_value_size_ret + ) + @gcsafe_ccall libopencl.POclGetHostKernelInfoPOCL( + host_kernel::cl_host_kernel_pocl, param_name::cl_uint, param_value_size::Csize_t, + param_value::Ptr{Cvoid}, param_value_size_ret::Ptr{Csize_t} + )::cl_int +end + +@checked function clReleaseHostKernelPOCL(host_kernel) + @gcsafe_ccall libopencl.POclReleaseHostKernelPOCL( + host_kernel::cl_host_kernel_pocl + )::cl_int +end + +# leave error handling to `host_run`. GC-safe calls let collection proceed during long runs +# instead of waiting for the kernel's thread. +@inline function clRunHostKernelPOCL( + host_kernel, arg_values, num_groups, first_group, group_count, scratch + ) + return @gcsafe_ccall libopencl.POclRunHostKernelPOCL( + host_kernel::cl_host_kernel_pocl, arg_values::Ptr{Ptr{Cvoid}}, + num_groups::Ptr{Csize_t}, C_NULL::Ptr{Csize_t}, first_group::Csize_t, + group_count::Csize_t, scratch::Ptr{Cvoid} + )::cl_int +end + @checked function clSetKernelArg(kernel, arg_index, arg_size, arg_value) @gcsafe_ccall libopencl.POclSetKernelArg( kernel::cl_kernel, arg_index::cl_uint, @@ -1248,26 +1293,64 @@ function Base.getproperty(p::Program, s::Symbol) end end +# a host kernel prepared for one work-group size; a NULL `id` caches an unsupported size +# (see `host_kernel`) +mutable struct HostKernelHandle + const id::cl_host_kernel_pocl + 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 + Base.@atomic last_duration::UInt64 + Base.@atomic last_groups::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 + # delayed run. + Base.@atomic serial_groups_a::Int + Base.@atomic serial_sample_a::UInt64 + Base.@atomic serial_duration_a::UInt64 + Base.@atomic serial_groups_b::Int + Base.@atomic serial_sample_b::UInt64 + 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) + id == C_NULL || finalizer(h -> clReleaseHostKernelPOCL(h.id), h) + return h + end +end + mutable struct Kernel const id::cl_kernel # kernel arguments are state of the kernel object, see `call` const lock::ReentrantLock - - # the work-group limits for the session's device, which every launch needs. they don't - # change, so they are queried once (see `work_group_info` for the others) + # the host-kernel handles of this kernel (under `lock`), and the one used last + const host_kernels::Vector{HostKernelHandle} + @atomic host_kernel::Union{Nothing, HostKernelHandle} + # whether a launch had partial work-groups (see `KA.split_launch`) + @atomic launched_partial::Bool + + # cache immutable device-specific work-group limits and the per-item stack estimate in + # bytes; see `work_group_info` for other properties const work_group_size::Int const preferred_work_group_size_multiple::Int + const private_mem_size::Int + # the largest work-group of tuned launches (see `POCL.link_kernel`) + tuned_work_group_size::Int function Kernel(k::cl_kernel) - function get(param) - result = Ref{Csize_t}() - clGetKernelWorkGroupInfo(k, device(), param, sizeof(Csize_t), result, C_NULL) + function get(param, T = Csize_t) + result = Ref{T}() + clGetKernelWorkGroupInfo(k, device(), param, sizeof(T), result, C_NULL) return Int(result[]) end kernel = try + work_group_size = get(CL_KERNEL_WORK_GROUP_SIZE) new( - k, ReentrantLock(), get(CL_KERNEL_WORK_GROUP_SIZE), - get(CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE) + k, ReentrantLock(), HostKernelHandle[], nothing, false, work_group_size, + get(CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE), + get(CL_KERNEL_PRIVATE_MEM_SIZE, cl_ulong), work_group_size ) catch clReleaseKernel(k) diff --git a/src/pocl/pocl.jl b/src/pocl/pocl.jl index a752e86f0..961d0f3f0 100644 --- a/src/pocl/pocl.jl +++ b/src/pocl/pocl.jl @@ -22,6 +22,33 @@ struct Session 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 + # serial-duration threshold in ticks for small launches (see `host_schedule`) + host_kernel_serial_ticks::UInt64 +end + +# a cheap monotonic counter: the TSC on x86, the virtual timer on AArch64 (where +# `llvm.readcyclecounter` reads PMCCNTR_EL0, which user code usually may not access) +@static if Sys.ARCH === :x86_64 || Sys.ARCH === :i686 + @inline cycle_counter() = ccall("llvm.readcyclecounter", llvmcall, UInt64, ()) +elseif Sys.ARCH === :aarch64 + @inline cycle_counter() = Base.llvmcall( + """ + %t = call i64 asm sideeffect "mrs \$0, cntvct_el0", "=r"() + ret i64 %t + """, UInt64, Tuple{} + ) +else + @inline cycle_counter() = time_ns() +end + +function ticks_per_ns() + t0, c0 = time_ns(), cycle_counter() + while time_ns() - t0 < 1_000_000 + end + t1, c1 = time_ns(), cycle_counter() + return (c1 - c0) / (t1 - t0) end # the sub-group width kernels are compiled for, or `nothing` if the device has no sub-groups. @@ -41,7 +68,7 @@ function Session() platform = cl.platforms()[idx] device = cl.default_device(platform) # PoCL's thread pool can only be sized with environment variables, so use a sub-device - # to run kernels on fewer threads. its other threads stay asleep. + # with the requested number of compute units. its other threads stay asleep. threads = cl.cpu_threads() if threads !== nothing && threads < device.max_compute_units && device.max_sub_devices > 0 device = cl.sub_device(device, threads) @@ -56,8 +83,8 @@ function Session() max_work_group_dims = ntuple(d -> d <= length(sizes) ? sizes[d] : 1, 3), # 0 if the device has no sub-groups sub_group_size = something(sub_group_size, 0), - # the threads PoCL runs work-groups on - compute_units = Int(device.max_compute_units), + # cap host-kernel threads at Julia's default pool size + compute_units = min(Int(device.max_compute_units), Threads.nthreads(:default)), # what kernels report, unless PoCL chose another for them preferred_work_group_size_multiple = Int(device.preferred_work_group_size_multiple), # collectives check these on every launch @@ -65,7 +92,19 @@ function Session() fp64 = "cl_khr_fp64" in extensions, ) - return Session(platform, device, context, limits) + "cl_pocl_host_kernel" in extensions || + error("The CPU back-end needs a PoCL build with the cl_pocl_host_kernel extension") + + rate = ticks_per_ns() + # 50 µs, which is long compared to the cost of letting other tasks run + 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) + + return Session( + platform, device, context, limits, host_kernel_long_ticks, + host_kernel_serial_ticks + ) end # created on first use, so that loading the package doesn't initialize PoCL @@ -185,6 +224,8 @@ function __init__() initialization_world[] = Base.get_world_counter() # there shouldn't be any session from precompilation, see `reset_session_state!` Base.@atomic session_cache.session = nothing + # nor scratch areas, whose pointers don't survive serialization + Base.@atomic host_scratch.slots = HostScratch[] return end diff --git a/test/pocl_session.jl b/test/pocl_session.jl index 6fbd36057..a0ebf63a7 100644 --- a/test/pocl_session.jl +++ b/test/pocl_session.jl @@ -29,6 +29,17 @@ function pointer_value(out, p) return end +# work-item i iterates n[i] times +function busy(A, n) + i = POCL.get_global_id() + x = 1.0 + for _ in 1:n[i] + x = sin(x) + 1.0 + end + A[i] = x + return +end + @testset "POCL session" begin @test Threads.nthreads() > 1 @@ -70,7 +81,7 @@ end # the default workgroup size spreads a launch over the threads @testset "default workgroup size" begin - threads = POCL.device().max_compute_units + threads = KernelAbstractions.KernelInterface.multiprocessor_count(CPU()) @test threads > 1 N = 4096 G = zeros(Int, N) @@ -99,6 +110,219 @@ end @test launch(Ptr{Float32}(C_NULL)) == 0 end + # host kernel launches on several threads, one work-group per thread + if POCL.device_limits().compute_units > 1 + nt = POCL.device_limits().compute_units + sizes = (; global_size = (nt, 1, 1), local_size = (1, 1, 1)) + A = zeros(nt) + n = zeros(Int, nt) + k = POCL.clfunction(busy, POCL.argument_types((A, n))) + h = POCL.host_kernel(k, sizes, nothing) + @test h !== nothing + # iterations per second + k(A, n; sizes...) + n[1] = 10^7 + rate = n[1] / @elapsed k(A, n; sizes...) + + # keep arguments alive until all threads finish, despite SIGINT (from a POSIX shell) + # or cancellation on Julia 1.14+ + cancellation = isdefined(Base, :CANCEL_TOKEN) + # on macOS before Julia 1.13, a race at start-up can leave SIGINT ignored for the + # whole process (JuliaLang/julia#62471) + sigint_ignored = Sys.isapple() && let act = Ref{NTuple{2, UInt64}}() + ccall(:sigaction, Cint, (Cint, Ptr{Cvoid}, Ptr{Cvoid}), 2, C_NULL, act) + act[][1] == 1 # SIG_IGN + end + sigint_ignored && @warn "SIGINT is ignored in this process; skipping the interrupt tests" + interruptible = cancellation || !(Sys.iswindows() || sigint_ignored) + interruptible && + @testset "interrupted launches ($path)" for path in (:short, :long) + # one work-group takes 2 s, the others 0.5 s, and the interrupt comes after 0.25 s + fill!(n, round(Int, rate / 2)) + n[end] = round(Int, 2rate) + fill!(A, 0) + # on a team of all threads + Base.@atomic :monotonic h.last_duration = path == :short ? 0 : typemax(UInt64) + POCL.record_serial_sample(h, nt, typemax(UInt64)) + POCL.record_serial_sample(h, nt, typemax(UInt64)) + @test POCL.host_schedule(h, POCL.session(), nt, path == :long)[1] == nt + launch() = k(A, n; sizes...) + t0 = time() + err = try + if cancellation + src = Base.CancellationTokenSource() + Threads.@spawn (sleep(0.25); Base.cancel!(src)) + Base.ScopedValues.with(launch, Base.CANCEL_TOKEN => Base.CancellationToken(src)) + else + Base.exit_on_sigint(false) + run(`sh -c "sleep 0.25; kill -INT $(getpid())"`; wait = false) + launch() + end + nothing + catch err + err + end + elapsed = time() - t0 + # don't let a late interrupt hit later tests + err === nothing && try + sleep(5) + catch + end + # defer the interrupt until the launch finishes + @test elapsed > 0.5 + @test err isa (cancellation ? Base.CancellationRequest : InterruptException) + @test all(!=(0), A) + end + + # a launch doesn't run other tasks on its thread while it waits for the team. before + # Julia 1.14, a task switch would hand the deferred interrupt to that task instead. + interruptible && + @testset "interrupted launch with a task waiting ($path)" for path in (:short, :long) + fill!(n, round(Int, rate / 2)) + n[end] = round(Int, 2rate) + fill!(A, 0) + Base.@atomic :monotonic h.last_duration = path == :short ? 0 : typemax(UInt64) + POCL.record_serial_sample(h, nt, typemax(UInt64)) + POCL.record_serial_sample(h, nt, typemax(UInt64)) + @test POCL.host_schedule(h, POCL.session(), nt, path == :long)[1] == nt + # a task that is runnable on this thread throughout the launch + done = Threads.Atomic{Bool}(false) + caught = Ref{Any}(nothing) + helper = Task() do + try + while !done[] + yield() + end + catch err + caught[] = err + end + end + helper.sticky = true + ccall(:jl_set_task_tid, Cint, (Any, Cint), helper, Threads.threadid() - 1) + schedule(helper) + # (let it enter the loop) + yield() + launch() = k(A, n; sizes...) + err = try + if cancellation + src = Base.CancellationTokenSource() + Threads.@spawn (sleep(0.25); Base.cancel!(src)) + Base.ScopedValues.with(launch, Base.CANCEL_TOKEN => Base.CancellationToken(src)) + else + Base.exit_on_sigint(false) + run(`sh -c "sleep 0.25; kill -INT $(getpid())"`; wait = false) + launch() + end + nothing + catch err + err + end + done[] = true + timedwait(() -> istaskdone(helper), 10) + err === nothing && caught[] === nothing && try + sleep(5) + catch + end + @test err isa (cancellation ? Base.CancellationRequest : InterruptException) + @test all(!=(0), A) + @test istaskdone(helper) && !istaskfailed(helper) + @test caught[] === nothing + pool = POCL.ThreadTeams.POOL.pool + @test pool !== nothing && !any(istaskfailed, pool.tasks) + end + + # a single-threaded launch runs full and partial work-groups separately (here: two + # handles of the same kernel); interrupts must wait until both runs finish + interruptible && + @testset "interrupted launch on one thread ($path)" for path in (:short, :long) + s = POCL.session() + full = @lock k.fun.lock POCL.create_host_kernel(k.fun, (1, 1, 1), false) + B = zeros(2) + m = [round(Int, rate / 2), 1] + # one thread (short serial estimate), with either a short or long previous launch + Base.@atomic :monotonic h.last_duration = path == :short ? 0 : typemax(UInt64) + POCL.record_serial_sample(h, 2, UInt64(0)) + POCL.record_serial_sample(h, 2, UInt64(0)) + @test POCL.host_schedule(h, s, 2, path == :long) == (1, false) + # the full work-group takes 0.5 s, and the interrupt comes after 0.25 s + function launch() + 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)) + end + end + err = try + if cancellation + src = Base.CancellationTokenSource() + Threads.@spawn (sleep(0.25); Base.cancel!(src)) + Base.ScopedValues.with(launch, Base.CANCEL_TOKEN => Base.CancellationToken(src)) + else + Base.exit_on_sigint(false) + run(`sh -c "sleep 0.25; kill -INT $(getpid())"`; wait = false) + launch() + end + nothing + catch err + err + end + err === nothing && try + sleep(5) + catch + end + @test err isa (cancellation ? Base.CancellationRequest : InterruptException) + # the partial work-group ran too + @test B[2] != 0 + end + + @testset "garbage collection during a launch" begin + # run one work-group for about a second while another thread collects garbage + fill!(n, 0) + n[1] = round(Int, rate) + Base.@atomic :monotonic h.last_duration = 0 + t0 = time() + gc = Threads.@spawn begin + while time() - t0 < 0.2 + end + @elapsed GC.gc() + end + k(A, n; global_size = (1, 1, 1), local_size = (1, 1, 1)) + elapsed = time() - t0 + # the collection doesn't wait for the kernel + @test fetch(gc) < elapsed / 2 + end + + @testset "launch from a finalizer" begin + # finalizers must run serially: waiting for a team may switch tasks + fill!(n, round(Int, rate / 20)) + n[1] = 0 + fill!(A, 0) + err = Ref{Any}(nothing) + launched = Ref(false) + # not inlined, so that nothing here keeps the object alive + @noinline function garbage() + finalizer(Ref(0)) do _ + try + k(A, n; sizes...) + catch e + err[] = e + end + launched[] = true + end + return + end + garbage() + # leave a task ready to expose an illegal switch from the finalizer + k(zero(A), zero(n); sizes...) + t = @async nothing + GC.gc() + wait(t) + @test launched[] + @test err[] === nothing + @test all(!=(0), A) + end + end + @testset "reset" begin s = POCL.session() q = POCL.queue() diff --git a/test/runtests.jl b/test/runtests.jl index cf61bf306..2c05f838e 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -45,14 +45,15 @@ end @testset "POCL thread count" begin # in fresh processes, as PoCL only reads its configuration once julia = Cmd(filter(arg -> !startswith(arg, "--code-coverage"), Base.julia_cmd().exec)) - script = "using KernelAbstractions: POCL; print(POCL.device().max_compute_units)" vars = ("JULIA_KA_CPU_THREADS", POCL.cl.pocl_thread_variables...) - function compute_units(env...; threads = 2) + function query(property, env...; threads = 2) + script = "using KernelAbstractions: POCL; print(POCL.$property)" cmd = `$julia --startup-file=no --threads=$threads --project=$(Base.active_project()) -e $script` cmd_env = filter(kv -> !(first(kv) in vars), copy(ENV)) return parse(Int, readchomp(setenv(cmd, cmd_env..., env...))) end + compute_units(env...; kwargs...) = query("device().max_compute_units", env...; kwargs...) # as many threads as Julia has @test compute_units(threads = 2) == 2 @@ -63,6 +64,13 @@ end @test compute_units("JULIA_KA_CPU_THREADS" => "3", "POCL_MAX_PTHREAD_COUNT" => "5") == 3 # up to the size of PoCL's device @test compute_units("JULIA_KA_CPU_THREADS" => "6", "POCL_MAX_PTHREAD_COUNT" => "5") == 5 + + # host launches cannot exceed Julia's default pool size + host_threads(env...) = query("device_limits().compute_units", env...) + @test host_threads() == 2 + @test host_threads("JULIA_KA_CPU_THREADS" => "1") == 1 + @test host_threads("JULIA_KA_CPU_THREADS" => "3") == 2 + @test host_threads("POCL_CPU_MAX_CU_COUNT" => "5") == 2 end @testset "POCL atomics descriptor" begin @@ -533,6 +541,426 @@ end @test allocated(KernelAbstractions.supports_float64, CPU()) == 0 end +@testset "POCL long host launches" begin + mod = @eval module $(gensym()) + using KernelAbstractions.POCL + function kernel(A, n) + i = POCL.get_global_id() + x = A[i] + for _ in 1:n + x = sin(x) + end + A[i] = x + return + end + end + A = ones(4) + kernel = POCL.clfunction(mod.kernel, POCL.argument_types((A, 1))) + sizes = (; global_size = (4, 1, 1), local_size = (4, 1, 1)) + h = POCL.host_kernel(kernel, sizes, nothing) + @test h !== nothing + # force the long path even on fast machines + function launch_long(kernel, h, A, n, sizes) + Base.@atomic :monotonic h.last_duration = typemax(UInt64) + kernel(A, n; sizes...) + end + allocated(f::F, args...) where {F} = (f(args...); @allocated f(args...)) + # shielding an active cancellation scope allocates on Julia 1.14+ + bytes = @static if isdefined(Base, :CANCEL_TOKEN) + Base.ScopedValues.with(Base.CANCEL_TOKEN => nothing) do + allocated(launch_long, kernel, h, A, 1, sizes) + end + else + allocated(launch_long, kernel, h, A, 1, sizes) + end + @test bytes == 0 skip = VERSION < v"1.12" + + # a long launch lets a queued task run afterwards; back-to-back launches let timers + # fire too + progressed = Ref(false) + task = @async (progressed[] = true) + launch_long(kernel, h, A, 1, sizes) + @test progressed[] + wait(task) + woke = Threads.Atomic{Bool}(false) + task = @async (sleep(0.01); woke[] = true) + t0 = time() + while !woke[] && time() - t0 < 10 + launch_long(kernel, h, A, 1, sizes) + end + @test woke[] + wait(task) + # also with launches from tasks on all threads, of which only one runs timers + stop = Threads.Atomic{Bool}(false) + woke = Threads.Atomic{Bool}(false) + timer = Timer(_ -> (woke[] = true), 0.01) + tasks = map(2:Threads.nthreads()) do _ + Threads.@spawn begin + B = ones(4) + while !stop[] + launch_long(kernel, h, B, 1, sizes) + end + end + end + t0 = time() + while !woke[] && time() - t0 < 10 + launch_long(kernel, h, A, 1, sizes) + end + stop[] = true + foreach(wait, tasks) + close(timer) + @test woke[] + + # concurrent callers need separate argument storage + @sync for _ in 1:4 + Threads.@spawn begin + B = ones(4) + for _ in 1:3 + launch_long(kernel, h, B, 1000, sizes) + end + expected = 1.0 + for _ in 1:3000 + expected = sin(expected) + end + @test all(x -> isapprox(x, expected), B) + end + end +end + +@testset "POCL small host launches" begin + if POCL.device_limits().compute_units > 1 + mod = @eval module $(gensym()) + using KernelAbstractions.POCL + function kernel(A, n) + i = POCL.get_global_id() + x = A[i] + for _ in 1:n + x = sin(x) + end + A[i] = x + return + end + end + s = POCL.session() + nt = s.limits.compute_units + A = ones(nt) + kernel = POCL.clfunction(mod.kernel, POCL.argument_types((A, 1))) + sizes = (; global_size = (nt, 1, 1), local_size = (1, 1, 1)) + h = POCL.host_kernel(kernel, sizes, nothing) + @test h !== nothing + Base.@atomic h.serial_groups_a = 0 + Base.@atomic h.serial_groups_b = 0 + # small launches stay serial unless both recent estimates are slow + @test POCL.host_schedule(h, s, nt, false) == (1, false) + kernel(A, 10^5; sizes...) + @test POCL.host_schedule(h, s, nt, false) == (1, false) + kernel(A, 10^5; sizes...) + @test POCL.host_schedule(h, s, nt, false)[1] == nt + # team runs also estimate serial duration. a run times a team thread, which may have + # just woken up or been descheduled (CI VMs have fewer cores than Julia threads), so + # allow many runs: the first fast one makes the kernel serial again. + for _ in 1:100 + kernel(A, 0; sizes...) + POCL.host_schedule(h, s, nt, false) == (1, false) && break + 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...) + kernel(A, 0; global_size = (1, 1, 1), local_size = (1, 1, 1)) + @test POCL.host_schedule(h, s, nt, false)[1] == nt + + # test team and stealing limits without executing oversized grids + tmax, smax = POCL.host_team_max_groups, POCL.host_steal_max_groups + @test POCL.host_schedule(h, s, tmax, false) == (nt, tmax <= smax) + @test POCL.host_schedule(h, s, tmax + 1, false) == (1, false) + @test POCL.host_schedule(h, s, tmax + 1, true) == (1, false) + @test POCL.host_schedule(h, s, typemax(Int), true) == (1, false) + @test POCL.host_schedule(h, s, min(smax, tmax), true) == (nt, true) + if smax < tmax + @test POCL.host_schedule(h, s, smax + 1, true) == (nt, false) + @test POCL.host_schedule(h, s, tmax, true) == (nt, false) + end + end +end + +@testset "POCL host launch schedule" begin + if POCL.device_limits().compute_units > 1 + mod = @eval module $(gensym()) + using KernelAbstractions.POCL + function kernel(A) + i = POCL.get_global_id() + A[i] += 1 + return + end + end + s = POCL.session() + nt = s.limits.compute_units + A = zeros(nt) + kernel = POCL.clfunction(mod.kernel, POCL.argument_types((A,))) + sizes = (; global_size = (nt, 1, 1), local_size = (1, 1, 1)) + h = POCL.host_kernel(kernel, sizes, nothing) + @test h !== nothing + function last!(groups, duration) + # (heavy enough to run on a team, with nt and nt + 1 work-groups) + for g in (nt + 1, nt) + POCL.record_serial_sample(h, g, typemax(UInt64)) + POCL.record_serial_sample(h, g, typemax(UInt64)) + end + Base.@atomic h.last_groups = groups + Base.@atomic h.last_duration = duration + return + end + + # use static blocks after a short launch of the same grid; otherwise allow stealing + last!(nt, 0) + @test POCL.host_schedule(h, s, nt, false) == (nt, false) + @test POCL.host_schedule(h, s, nt + 1, false) == (nt, true) + @test POCL.host_schedule(h, s, nt, true) == (nt, true) + last!(0, 0) + @test POCL.host_schedule(h, s, nt, false) == (nt, true) + + # launches remember how many work-groups they had, and how long they took + last!(0, 0) + kernel(A; sizes...) + @test (Base.@atomic h.last_groups) == nt + @test (Base.@atomic h.last_duration) < typemax(UInt64) + kernel(A; sizes...) + @test A == fill(2, nt) + + # a short launch on a team lets a queued task run, and such launches back to back + # let a timer fire + function short_team!() + last!(nt, 0) + @assert POCL.host_schedule(h, s, nt, false) == (nt, false) + kernel(A; sizes...) + end + progressed = Ref(false) + task = @async (progressed[] = true) + short_team!() + @test progressed[] + wait(task) + woke = Threads.Atomic{Bool}(false) + task = @async (sleep(0.01); woke[] = true) + t0 = time() + while !woke[] && time() - t0 < 10 + short_team!() + end + @test woke[] + wait(task) + end +end + +@testset "POCL host launches on a team" begin + if POCL.device_limits().compute_units > 1 + @kernel function team_axpy!(y, a, @Const(x)) + i = @index(Global) + @inbounds y[i] = a * x[i] + y[i] + end + @kernel function team_spin!(A, n) + i = @index(Global) + v = A[i] + for _ in 1:n + v = sin(v) + end + A[i] = v + end + @kernel function team_exception!(A, i) + I = @index(Global, Linear) + if I == i + A[0] = 1 + end + end + # serial execution must produce tickets in work-group order + @kernel function team_order!(T, counter) + if @index(Local, Linear) == 1 + @inbounds T[@index(Group, Linear)] = last(KernelAbstractions.@atomic counter[1] += 1) + end + end + # hold the team in group 1 until `release` or `n` checks. `entered` marks its start; + # `after` marks group `later`, which cannot start during the hold in a serial + # launch. + @kernel function team_hold!(entered, after, release, timedout, n, later) + if @index(Local, Linear) == 1 + g = @index(Group, Linear) + g == later && (KernelAbstractions.@atomic after[1] = 1) + if g == 1 + KernelAbstractions.@atomic entered[1] = 1 + i = 0 + while (KernelAbstractions.@atomic release[1]) == 0 && i < n + i += 1 + end + i == n && (KernelAbstractions.@atomic timedout[1] = 1) + end + end + end + # enough work-items to select a team + n = 64 * POCL.host_kernel_serial_items + x = rand(Float32, n) + launch!(y) = team_axpy!(CPU(), 256)(y, 2.0f0, x; ndrange = n) + launch!(zeros(Float32, n)) + quietly(f) = redirect_stdout(f, devnull) + + # nested parallel launches run serially (see `ThreadTeams.foreach_range`) + ngroups = n ÷ 64 + function order!(T) + counter = [0] + team_order!(CPU(), 64)(T, counter; ndrange = n) + return T + end + order!(zeros(Int, ngroups)) + Ts = [zeros(Int, ngroups) for _ in 1:4] + Threads.@threads :static for i in 1:4 + order!(Ts[i]) + end + @test all(==(1:ngroups), Ts) + + # a busy team also forces serial execution. wait for both the held group and the + # last block to start. the hold may occupy any thread, so let the checking task + # migrate; always release the hold. + load(A) = Core.Intrinsics.atomic_pointerref(pointer(A), :acquire) + entered, after, release, timedout = [0], [0], [0], [0] + nt = min(ngroups, POCL.device_limits().compute_units) + later = (nt - 1) * (ngroups ÷ nt) + min(nt - 1, ngroups % nt) + 1 + task = Threads.@spawn team_hold!(CPU(), 64)(entered, after, release, timedout, 10^10, later; ndrange = n) + check = Threads.@spawn try + t0 = time() + while !(load(entered) == 1 && load(after) == 1) && time() - t0 < 30 + yield() + end + T = order!(zeros(Int, ngroups)) + load(entered) == 1 && load(after) == 1 && load(timedout) == 0, T + finally + Core.Intrinsics.atomic_pointerset(pointer(release), 1, :release) + end + held, T = fetch(check) + wait(task) + @test held + @test timedout[1] == 0 + @test T == 1:ngroups + + A = ones(Float32, n) + team_spin!(CPU(), 256)(A, 1000; ndrange = n) + expected = foldl((x, _) -> sin(x), 1:1000; init = 1.0f0) + @test all(a -> isapprox(a, expected; rtol = 1.0e-4), A) + + # report exceptions from any thread without breaking later launches + A = zeros(Float32, n) + for i in (1, n ÷ 2, n) + @test_throws POCL.KernelException quietly(() -> team_exception!(CPU(), 256)(A, i; ndrange = n)) + end + team_exception!(CPU(), 256)(A, 0; ndrange = n) + y = zeros(Float32, n) + launch!(y) + @test y == 2 .* x + end +end + +# static placement matches `Threads.@threads :static`, regardless of the launching task +@testset "POCL host launch placement" begin + nt = POCL.device_limits().compute_units + if nt > 1 + mod = @eval module $(gensym()) + using KernelAbstractions.POCL + # a work-group's local memory lies in the scratch area of the thread that runs it + function where_kernel(T) + mem = POCL.emit_localmemory(UInt8, Val(1)) + if POCL.get_local_id(1) == 1 + @inbounds T[POCL.get_group_id(1)] = reinterpret(UInt, mem) + end + return + end + end + function thread_of(address) + for (tid, s) in enumerate(POCL.host_scratch.slots) + UInt(s.ptr) <= address < UInt(s.ptr) + s.size && return tid + end + return 0 + end + # enough work-items to select a team + items = 64 + groups = cld(4 * POCL.host_kernel_serial_items, items) * nt + 3 + T = zeros(UInt, groups) + k = POCL.clfunction(mod.where_kernel, POCL.argument_types((T,))) + sizes = (; global_size = (groups * items, 1, 1), local_size = (items, 1, 1)) + h = POCL.host_kernel(k, sizes, nothing) + @test h !== nothing + + # expected static placement + tids = Threads.threadpooltids(:default) + q, r = divrem(groups, nt) + block(g) = g <= r * (q + 1) ? cld(g, q + 1) : r + cld(g - r * (q + 1), q) + if nt == Threads.nthreads(:default) + tt = zeros(Int, groups) + Threads.@threads :static for g in 1:groups + tt[g] = Threads.threadid() + end + @test tt == tids[block.(1:groups)] + end + + # count misplaced blocks across `n` launches, excluding whole blocks taken over by + # the dispatcher when their assigned thread starts late. `stolen_chunks()` counts + # these takeovers; `dispatcher` identifies the thread when known. + function misplaced(launch!, dispatcher = nothing; n = 20) + count = 0 + for _ in 1:n + fill!(T, 0) + rescued = POCL.ThreadTeams.stolen_chunks() + launch!() + rescued = POCL.ThreadTeams.stolen_chunks() - rescued + ran = thread_of.(T) + @test all(!=(0), ran) + moved = 0 + for b in 1:nt + on = unique(ran[filter(g -> block(g) == b, 1:groups)]) + on == [tids[b]] && continue + moved += 1 + length(on) == 1 && something(dispatcher, on[1]) == on[1] || (count += 1) + end + count += max(0, moved - rescued) + end + return count + end + # force static team scheduling + function static!(h) + Base.@atomic :monotonic h.last_duration = 0 + Base.@atomic :monotonic h.last_groups = groups + return + end + @test misplaced(() -> (static!(h); k(T; sizes...)), Threads.threadid()) == 0 + + # construct a launch as `host_dispatch` would (one argument, no RNG), with stealing + # disabled + function launch_directly(run) + info = Ref(POCL.ExceptionInfo_st()) + num_groups = Ref(Csize_t.((groups, 1, 1))) + vals = Ref((POCL.kernel_state(false, C_NULL), POCL.clconvert(T))) + GC.@preserve T info num_groups vals begin + info_ptr = Base.unsafe_convert(Ptr{POCL.ExceptionInfo_st}, info) + vals[] = (POCL.kernel_state(false, info_ptr), vals[][2]) + base = Ptr{Cvoid}(Base.unsafe_convert(Ptr{typeof(vals[])}, vals)) + tt = typeof(vals[]) + ptrs = Ref((base + fieldoffset(tt, 1), base + fieldoffset(tt, 2), C_NULL, C_NULL)) + GC.@preserve ptrs begin + launch = POCL.HostLaunch( + h, h, Ptr{Ptr{Cvoid}}(Base.unsafe_convert(Ptr{typeof(ptrs[])}, ptrs)), + Ptr{Csize_t}(Base.unsafe_convert(Ptr{NTuple{3, Csize_t}}, num_groups)), + (groups, 1, 1), (false, false, false), groups, nt, false, + h.scratch_size, h.scratch_alignment, info_ptr + ) + run(launch) + end + end + @test info[].status == 0 + return + end + @test misplaced(() -> launch_directly(l -> l()), Threads.threadid()) == 0 + end +end + @testset "POCL exceptions" begin @kernel function exception_kernel!(A) I = @index(Global, Linear) @@ -566,6 +994,20 @@ end end @test all(failing) @test !any(succeeding) + + # report exceptions from both full and partial workgroups + @kernel function exception_at!(A, i) + I = @index(Global, Linear) + if I == i + A[0] = 1 + end + end + # warm up: the first partial launch is entirely checked + exception_at!(CPU(), 4)(A, 10; ndrange = 9) + for i in (1, 9) + @test_throws POCL.KernelException quietly(() -> exception_at!(CPU(), 4)(A, i; ndrange = 9)) + end + exception_at!(CPU(), 4)(A, 10; ndrange = 9) end @testset "POCL exception output" begin @@ -688,7 +1130,10 @@ end # in a fresh process, to check initialization, and with threads, which the tests # usually don't have julia = Cmd(filter(arg -> !startswith(arg, "--code-coverage"), Base.julia_cmd().exec)) - cmd = `$julia --startup-file=no --threads=4 --project=$(Base.active_project()) + # disable Julia 1.12+'s interactive thread so thread 1 receives SIGINT during team + # launches + threads = VERSION >= v"1.12" ? "4,0" : "4" + cmd = `$julia --startup-file=no --threads=$threads --project=$(Base.active_project()) $(joinpath(@__DIR__, "pocl_session.jl"))` @test success(pipeline(cmd; stdout, stderr)) end @@ -944,6 +1389,23 @@ end @test wgs((1024, 1001)) == (1024, 1) @test wgs((100003,)) == (1024,) @test wgs((0, 7)) == (1, 7) + # below 16 vectors, shrink the first dimension only to a vector-width multiple; + # otherwise keep its size + width = POCL.device_limits().preferred_work_group_size_multiple + small(threads, ndrange) = KernelAbstractions.launch_workgroupsize( + CPU(), KernelAbstractions.NDLaunch{Int}(), threads, ndrange + ) + @test small(8width, (125width,)) == (5width,) + @test small(4width, (125width,)) == (4width,) + @test small(4width, (125width + 1,)) == (4width,) + # (one vector, which has no smaller multiple) + @test small(width, (3width + 1,)) == (width,) + # (just below 16 vectors, and at 16, where any divisor may be taken) + @test small(16width - 1, (15width * (16width - 2),)) == (15width,) + @test small(16width, (15width * (16width - 2),)) == (16width - 2,) + # (searching the work-group counts) + @test small(8width, (9width,)) == (8width,) + @test small(8width, (12width,)) == (6width,) # an explicit workgroup size is kept @kernel function groupsize!(A) @@ -1006,35 +1468,62 @@ end end @testset "POCL bounds checks" begin - function checked(kernel, shape; workgroupsize = nothing) + # record bounds checks after the first launch + function checks(kernel, shape; workgroupsize = nothing) A = fill(-1, shape) kernel(A; ndrange = shape, workgroupsize) - all(==(A[1]), A) || error("inconsistent bounds checks") - return Bool(A[1]) - end - - # a kernel without the bounds check runs launches without partial workgroups - @test !checked(bounds_checked!(CPU()), 64; workgroupsize = 16) - @test checked(bounds_checked!(CPU()), 60; workgroupsize = 16) - @test !checked(bounds_checked!(CPU()), (8, 6); workgroupsize = (4, 3)) - @test checked(bounds_checked!(CPU()), (8, 6); workgroupsize = (4, 4)) - @test !checked(bounds_checked!(CPU()), (4, 6, 8); workgroupsize = (2, 3, 4)) - @test checked(bounds_checked!(CPU()), (4, 6, 9); workgroupsize = (2, 3, 4)) - @test !checked(bounds_checked!(CPU(), 8), 16) - @test checked(bounds_checked!(CPU(), 8), 12) + fill!(A, -1) + kernel(A; ndrange = shape, workgroupsize) + return A + end + # the work-items that need it: those of partial workgroups + function expected(shape, workgroupsize) + shape, wgs = Tuple(shape), Tuple(workgroupsize) + wgs = ntuple(d -> d <= length(wgs) ? wgs[d] : 1, length(shape)) + any(d -> shape[d] % wgs[d] != 0, eachindex(shape)) || return fill(false, shape) + # folding dimensions beyond the third puts partial third-dimension groups inside the + # grid + length(shape) > 3 && shape[3] % wgs[3] != 0 && return fill(true, shape) + return map(CartesianIndices(shape)) do I + any(eachindex(shape)) do d + shape[d] % wgs[d] != 0 && (I[d] - 1) ÷ wgs[d] == cld(shape[d], wgs[d]) - 1 + end + end + end + + @testset "$shape, workgroupsize=$wgs" for (shape, wgs) in ( + (64, 16), (60, 16), ((8, 6), (4, 3)), ((8, 6), (4, 4)), ((7, 8), (4, 4)), + ((7, 7), (4, 4)), ((4, 6, 8), (2, 3, 4)), ((4, 6, 9), (2, 3, 4)), + ((5, 6, 7), (2, 3, 4)), ((5, 7, 7), (2, 3, 4)), ((1, 7, 1), (1, 4, 1)), + ((9, 7, 4, 5), (4, 2, 2)), ((9, 7, 3, 5), (4, 2, 2)), ((9, 7, 3, 5, 2), (4, 1, 2)), + ) + @test checks(bounds_checked!(CPU()), shape; workgroupsize = wgs) == expected(shape, wgs) + end + @test checks(bounds_checked!(CPU(), 8), 16) == expected(16, 8) + @test checks(bounds_checked!(CPU(), 8), 12) == expected(12, 8) # also with a tuned workgroup size, which is a power of two on PoCL, unless a single # workgroup covers the ndrange (e.g. on a single thread). an odd ndrange larger than # the largest workgroup needs partial workgroups, however many threads PoCL uses. - @test !checked(bounds_checked!(CPU()), 1024) - @test checked(bounds_checked!(CPU()), POCL.device_limits().max_work_group_size + 1) - @test !checked(bounds_checked!(CPU()), (64, 32)) + @test all(==(0), checks(bounds_checked!(CPU()), 1024)) + A = checks(bounds_checked!(CPU()), POCL.device_limits().max_work_group_size + 1) + @test A[end] == 1 + @test A[1] == 0 + @test all(==(0), checks(bounds_checked!(CPU()), (64, 32))) # only the kernel that the launch needs is compiled compilations = POCL.compilations[] - @test !checked(tuned_bounds_checked!(CPU()), 4096) + @test all(==(0), checks(tuned_bounds_checked!(CPU()), 4096)) @test POCL.compilations[] == compilations + 1 - @test checked(partial_bounds_checked!(CPU()), 4097) + # check the whole first partial launch so kernels used once compile once. later launches + # compile an unchecked variant for full workgroups. + A = fill(-1, 4097) + partial_bounds_checked!(CPU())(A; ndrange = length(A)) + @test all(==(1), A) @test POCL.compilations[] == compilations + 2 + partial_bounds_checked!(CPU())(A; ndrange = length(A)) + @test A[end] == 1 + @test A[1] == 0 + @test POCL.compilations[] == compilations + 3 # the tuned workgroup size is predicted from the device's limits, which a kernel's can # be smaller than: then, its workgroups may not cover the ndrange, and need the check @@ -1045,6 +1534,55 @@ end @test B == idx end +# a dynamically indexed tuple lives on the stack: 1 KiB per work-item +function stack_tuple_kernel!(B, idx) + i = KernelAbstractions.KernelInterface.get_global_id().x + i > length(B) && return + t = ntuple(j -> Float32(j), Val(256)) + @inbounds B[i] = t[idx[i]] + return +end + +# `stack_tuple_kernel!`'s argument layout, with no stack use +function stack_free_kernel!(B, idx) + i = KernelAbstractions.KernelInterface.get_global_id().x + i > length(B) && return + @inbounds B[i] = -1 + return +end + +@testset "POCL tuned work-groups within the host-kernel stack limit" begin + n = 1 << 16 + B, idx = zeros(Float32, n), rand(1:256, n) + backend = POCL.POCLBackend() + kernel = KernelAbstractions.KernelInterface.@launch backend launch = false stack_tuple_kernel!(B, idx) + fun = kernel.kern.kernel.fun + # 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 + 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)) + @test B == idx + + # explicit work-groups over the limit run on the queue + items = fun.work_group_size + sizes = (; global_size = (n, 1, 1), local_size = (items, 1, 1)) + @test POCL.host_kernel(kernel.kern.kernel, sizes, nothing) === nothing + fill!(B, 0) + kernel(B, idx; workgroupsize = items, numgroups = cld(n, items)) + @test B == idx + + # a split launch whose unchecked variant is over the limit runs every work-group with + # the checked one, as a host kernel + checked = KernelAbstractions.KernelInterface.@launch backend launch = false stack_free_kernel!(B, idx) + @test POCL.host_kernel(checked.kern.kernel.fun, (items, 1, 1), false) !== nothing + fill!(B, 0) + m = n - items ÷ 2 + KernelAbstractions.launch_split(kernel, checked, (m, 1, 1), (cld(m, items), 1, 1), (items, 1, 1), (B, idx)) + @test all(==(-1), view(B, 1:m)) +end + @kernel function muladd_kernel!(D, @Const(A), @Const(B), @Const(C)) i = @index(Global) @inbounds D[i] = muladd(A[i], B[i], C[i])