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
31 changes: 20 additions & 11 deletions src/backend_launch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,14 @@ argconvert(kernel::Kernel{<:KI.Backend}, arg) = KI.argconvert(backend(kernel), a
Core.kwcall(kwargs::NamedTuple, obj::Kernel{<:KI.Backend}, args::Vararg{Any, N}) where {N} =
launch_tuple(obj, args; kwargs...)

# strip singleton functions (like those of `@kernel`) to share launch code across kernels
# with the same backend and static sizes. hooks can't dispatch on such a function's type;
# callables with state keep theirs (see `test/launch.jl`).
@inline sizes_only(obj::Kernel{B, WS, ND, F}) where {B, WS, ND, F} =
Base.issingletontype(F) ? similar(obj, nothing) : obj

function launch_tuple(obj::Kernel, args::Tuple; ndrange = nothing, workgroupsize = nothing)
setup = launch_setup(obj, ndrange, workgroupsize)
setup = launch_setup(sizes_only(obj), ndrange, workgroupsize)
# nothing to launch (or compile) for an empty ndrange
setup === nothing && return nothing
ndrange, workgroupsize, iterspace = setup
Expand All @@ -105,7 +111,7 @@ function launch_tuple(obj::Kernel, args::Tuple; ndrange = nothing, workgroupsize
# depend on the tuned workgroup size, so the context (and thus the kernel) doesn't either.
# (not done by `launch_setup`: the launch mode isn't inferred concretely, so returning
# it would box the result)
launch = @noinline select_launch(obj, workgroupsize, iterspace)
launch = @noinline select_launch(sizes_only(obj), workgroupsize, iterspace)
T = narrow_index_type(backend(obj))
if launch === NDLaunch{T}()
# the common case, specialized statically
Expand Down Expand Up @@ -157,18 +163,22 @@ function launch_kernel(
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)
# (which of the types it is is hidden from inference, which would compile the lookup for
# both)
compiled_tt = Base.compilerbarrier(:type, unchecked ? without_bounds_check(tt) : tt)::Type
kernel = kernel_function_as(b, obj.f, compiled_tt, tt; compiler_options(obj)...)
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
kernel_function_as(b, obj.f, compiled_tt, tt; compiler_options(obj)...)
else
# infer the kernel's type, avoiding dynamic dispatch in the rest of the launch
KI.kernel_function(b, obj.f, tt; compiler_options(obj)...)
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
nothing
end
ctx, groups, items = launch_geometry(obj, launch, subgroups, ndrange, iterspace, ctx, threads)
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
Expand All @@ -191,11 +201,10 @@ skip_bounds_check(backend) = backend isa POCL.POCLBackend

`KI.kernel_function(backend, f, compiled_tt; kwargs...)`, as a kernel that is launched with
arguments of the types `tt`, which only differ from `compiled_tt` in the type parameters of
the context. Backends for which `skip_bounds_check` holds implement it, and shouldn't
specialize on `compiled_tt`; for others, `compiled_tt` is always `tt`.
the context. Backends for which `skip_bounds_check` holds implement it, without
specializing on `compiled_tt`.
"""
Base.@nospecializeinfer kernel_function_as(backend, f, @nospecialize(compiled_tt), tt; kwargs...) =
KI.kernel_function(backend, f, tt; kwargs...)
function kernel_function_as end

"""
expected_workgroupsize(backend, nitems)
Expand Down
45 changes: 21 additions & 24 deletions src/pocl/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -202,33 +202,30 @@ end
global_size = (1,), local_size = nothing
) = launch_converted(kernel, args, exception_info, global_size, local_size)

# 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)))),
]
for (dt, ex) in zip(params, exprs)
# filter out ghost arguments that shouldn't be passed
pass_arg(dt) || continue
# replace non-isbits arguments (they should be unused, or compilation would have
# failed)
push!(call_t, isbitstype(dt) ? dt : Ptr{Any})
push!(call_args, isbitstype(dt) ? ex : :C_NULL)
end
return Base.to_tuple_type(call_t), call_args
end

@inline @generated function launch_converted(
kernel::AbstractKernel{F, TT}, args::Tuple, exception_info, global_size, local_size
) where {F, TT}
sig = Tuple{F, TT.parameters...} # Base.signature_type with a function type
args = (:(kernel.f), (:(clconvert(args[$i])) for i in 1:fieldcount(args))...)

# filter out ghost arguments that shouldn't be passed
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]]

# replace non-isbits arguments (they should be unused, or compilation would have failed)
for (i, dt) in enumerate(call_t)
if !isbitstype(dt)
call_t[i] = Ptr{Any}
call_args[i] = :C_NULL
end
end

pushfirst!(call_t, KernelState)
pushfirst!(
call_args,
:(KernelState(kernel.rng_state ? Base.rand(UInt32) : UInt32(0), UInt64(UInt(exception_info))))
)

# finalize types
call_tt = Base.to_tuple_type(call_t)
call_tt, call_args = kernel_call_arguments(F, TT, fieldcount(args))

# the converted arguments only hold pointers to the arrays in `args`
return quote
Expand Down
2 changes: 1 addition & 1 deletion src/precompile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

@kernel function precompile_kernel(A, @Const(B))
i = @index(Global, Linear)
@inbounds A[i] = 2 * B[i] + 1
@inbounds A[i] = fma(2, B[i], 1)
end

# on Julia 1.11, the launch leaks GPUCompiler's runtime into the package image, which then
Expand Down
24 changes: 24 additions & 0 deletions test/launch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,22 @@ end
end
end

# a kernel function with state, whose `partition` hook fixes the workgroup size
# (laid out like a closure, as AMDGPU only compiles functions, and adapts them as closures)
struct FixedGroups{F, I} <: Function
f::F
items::I
end
(g::FixedGroups)(args...) = g.f(args...)
KernelAbstractions.partition(
kernel::KernelAbstractions.Kernel{<:Any, <:Any, <:Any, <:FixedGroups}, ndrange::Tuple, workgroupsize
) = invoke(KernelAbstractions.partition, Tuple{Any, Any, Any}, kernel, ndrange, (kernel.f.items,))

@kernel function launch_groupsize!(A)
I = @index(Global, Linear)
@inbounds A[I] = @groupsize()[1]
end

default_launcher(kernel, args...; ndrange, workgroupsize = nothing) =
kernel(args...; ndrange, workgroupsize)

Expand Down Expand Up @@ -202,6 +218,14 @@ function launch_testsuite(backend, AT; launcher = default_launcher, skip_tests =
@test all(p -> position[listed[p]] == p, eachindex(listed))
end

@testset "partition for the kernel function" begin
kernel = launch_groupsize!(backend())
A = AT(zeros(Int, 10))
launcher(similar(kernel, FixedGroups(kernel.f, 3)), A; ndrange = length(A))
synchronize(backend())
@test all(==(3), Array(A))
end

@testset "synchronize with padding lanes" begin
for (shape, wgs) in (((37,), (8,)), ((7, 6), (4, 4)), ((5, 3, 3), (2, 2, 2)), ((8, 6), (4, 3)))
A = AT(zeros(Int, shape))
Expand Down
28 changes: 28 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,34 @@ struct NewBackend <: KernelAbstractions.Backend end
@test KernelAbstractions.functional(backend) === missing
end

# a GPU back-end, whose kernel type depends on the function and argument types
struct StaticBackend <: KernelAbstractions.GPU end
struct StaticKernel{F, TT} end
const KI = KernelAbstractions.KernelInterface
KI.argconvert(::StaticBackend, x) = x
KI.kernel_function(b::StaticBackend, ::F, ::Type{TT}; kwargs...) where {F, TT} =
KI.Kernel{StaticBackend, StaticKernel{F, TT}}(b, StaticKernel{F, TT}())
KI.launch(::KI.Kernel{StaticBackend}, groups, items, args) = nothing
KI.max_work_group_size(::Union{StaticBackend, KI.Kernel{StaticBackend}}) = 1024
KI.max_work_group_dims(::StaticBackend) = (1024, 1024, 64)
KI.max_num_groups(::StaticBackend) = (2^31 - 1, 65535, 65535)
KI.launch_configuration(::KI.Kernel{StaticBackend}; kwargs...) = (; workgroupsize = 256)
@testset "Kernel type is inferred" begin
KA = KernelAbstractions
kernel = mapped_indices!(StaticBackend())
@testset "workgroupsize $ws" for ws in (nothing, 8)
ndrange, _, iterspace, _ = KA.launch_config(kernel, 10, ws)
tt = Tuple{
typeof(kernel), Nothing, Nothing, typeof(ndrange), typeof(ws), typeof(iterspace),
Tuple{Vector{Int}}, Bool,
}
ci, _ = only(code_typed(KA.launch_kernel, tt; optimize = false))
kernels = filter(T -> T !== Union{} && T <: KI.Kernel, map(Core.Compiler.widenconst, ci.ssavaluetypes))
@test !isempty(kernels)
@test all(isconcretetype, kernels)
end
end

@testset "Deprecated GPU alias" begin
@test KernelAbstractions.GPU === KernelAbstractions.Backend
@test CPU() isa KernelAbstractions.GPU
Expand Down
Loading