Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 34 additions & 18 deletions src/backend_launch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -271,21 +289,19 @@ 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))))

# 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`
Expand Down
29 changes: 27 additions & 2 deletions src/nditeration.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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()
Expand Down
22 changes: 13 additions & 9 deletions src/pocl/backend.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -277,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(
Expand Down Expand Up @@ -313,7 +319,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
Expand All @@ -325,7 +331,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)
Expand Down Expand Up @@ -356,18 +362,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`)
Expand Down
Loading
Loading