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
118 changes: 65 additions & 53 deletions lib/cl/kernel.jl
Original file line number Diff line number Diff line change
Expand Up @@ -269,63 +269,68 @@ function call(
)
return Base.@lock k begin
_set_args!(k, args)
if !isempty(indirect_memory)
svm_pointers = CLPtr{Cvoid}[]
usm_pointers = CLPtr{Cvoid}[]
bda_pointers = CLPtr{Cvoid}[]
device_access = host_access = shared_access = false
for memory in indirect_memory
ptr = pointer(memory)
if ptr == C_NULL || ptr == CL_NULL
continue
end
isempty(indirect_memory) || set_indirect_memory!(k, indirect_memory)
enqueue_kernel(k, global_size, local_size; global_work_offset, wait_on, rng_state,
nargs=length(args))
end
end

if memory isa SharedVirtualMemory
# system memory is not an SVM allocation and needs no registration:
# indirect access to it is governed by `SVM_FINE_GRAIN_SYSTEM`, which
# defaults to true on devices that support it.
is_system(memory) || push!(svm_pointers, ptr)
elseif memory isa Buffer
push!(bda_pointers, ptr)
elseif memory isa UnifiedDeviceMemory
device_access = true
push!(usm_pointers, ptr)
elseif memory isa UnifiedHostMemory
host_access = true
push!(usm_pointers, reinterpret(CLPtr{Cvoid}, ptr))
elseif memory isa UnifiedSharedMemory
shared_access = true
push!(usm_pointers, ptr)
else
throw(ArgumentError("Unknown memory type"))
end
# register the memory that the kernel accesses through pointers that aren't arguments.
# kept out of `call`, which is compiled for every kernel signature.
@noinline function set_indirect_memory!(k::Kernel, indirect_memory::Vector{AbstractMemory})
svm_pointers = CLPtr{Cvoid}[]
usm_pointers = CLPtr{Cvoid}[]
bda_pointers = CLPtr{Cvoid}[]
device_access = host_access = shared_access = false
for memory in indirect_memory
ptr = pointer(memory)
if ptr == C_NULL || ptr == CL_NULL
continue
end

# configure USM access
if device_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
end
if host_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
end
if shared_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
if memory isa SharedVirtualMemory
# system memory is not an SVM allocation and needs no registration:
# indirect access to it is governed by `SVM_FINE_GRAIN_SYSTEM`, which
# defaults to true on devices that support it.
is_system(memory) || push!(svm_pointers, ptr)
elseif memory isa Buffer
push!(bda_pointers, ptr)
elseif memory isa UnifiedDeviceMemory
device_access = true
push!(usm_pointers, ptr)
elseif memory isa UnifiedHostMemory
host_access = true
push!(usm_pointers, reinterpret(CLPtr{Cvoid}, ptr))
elseif memory isa UnifiedSharedMemory
shared_access = true
push!(usm_pointers, ptr)
else
throw(ArgumentError("Unknown memory type"))
end
end

# set the pointers
if !isempty(svm_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_SVM_PTRS, sizeof(svm_pointers), svm_pointers)
end
if !isempty(bda_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_DEVICE_PTRS_EXT, sizeof(bda_pointers), bda_pointers)
end
if !isempty(usm_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_USM_PTRS_INTEL, sizeof(usm_pointers), usm_pointers)
end
# configure USM access
if device_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_DEVICE_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
end
enqueue_kernel(k, global_size, local_size; global_work_offset, wait_on, rng_state,
nargs=length(args))
if host_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_HOST_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
end
if shared_access
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_INDIRECT_SHARED_ACCESS_INTEL, sizeof(cl_bool), Ref{cl_bool}(true))
end

# set the pointers
if !isempty(svm_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_SVM_PTRS, sizeof(svm_pointers), svm_pointers)
end
if !isempty(bda_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_DEVICE_PTRS_EXT, sizeof(bda_pointers), bda_pointers)
end
if !isempty(usm_pointers)
clSetKernelExecInfo(k, CL_KERNEL_EXEC_INFO_USM_PTRS_INTEL, sizeof(usm_pointers), usm_pointers)
end
return
end

# From `julia/base/reflection.jl`, adjusted to add specialization on `t`.
Expand Down Expand Up @@ -426,8 +431,15 @@ end

function set_arg!(k::Kernel, idx::Integer, arg::T) where {T}
ref = Ref(arg)
tsize = sizeof(ref)
err = unchecked_clSetKernelArg(k, idx - 1, tsize, ref)
GC.@preserve ref begin
set_arg_value!(k, Int(idx), sizeof(ref), Base.unsafe_convert(Ptr{Cvoid}, ref))
end
return k
end

# kept out of `set_arg!`, which is compiled for every argument type
@noinline function set_arg_value!(k::Kernel, idx::Int, size::Int, ptr::Ptr{Cvoid})
err = unchecked_clSetKernelArg(k, idx - 1, size, ptr)
if err == CL_INVALID_ARG_SIZE
error("""Mismatch between Julia and OpenCL type for kernel argument $idx.

Expand All @@ -441,7 +453,7 @@ function set_arg!(k::Kernel, idx::Integer, arg::T) where {T}
elseif err != CL_SUCCESS
throw(CLError(err))
end
return k
return
end

function set_arg!(k::Kernel, idx::Integer, arg::Nothing)
Expand Down
35 changes: 24 additions & 11 deletions src/OpenCLKernels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ KI.argconvert(::OpenCLBackend, arg) = kernel_convert(arg)
# again at every launch, because the converted callable only holds pointers to the arrays
# it captures
function KI.kernel_function(backend::OpenCLBackend, f::F, tt::TT=Tuple{}; name = nothing, kwargs...) where {F,TT}
activate(backend)
@noinline activate(backend) # this method is compiled for every kernel
check_sub_group_size(backend, kwargs)
kern = GC.@preserve f clfunction(kernel_convert(f), tt; source=f, name, kwargs...)
KI.Kernel{OpenCLBackend, typeof(kern)}(backend, kern)
Expand All @@ -197,59 +197,72 @@ function check_sub_group_size(backend::OpenCLBackend, kwargs)
return
end

# these helpers take the `cl.Kernel` instead of the `KI.Kernel`, whose type depends on the
# kernel's function and argument types, so that they are compiled once instead of per kernel

# the context that a kernel was compiled for
function kernel_context(kernel::KI.Kernel{OpenCLBackend})
function kernel_context(kernel::cl.Kernel)
ctx = Ref{cl.cl_context}()
cl.clGetKernelInfo(kernel.kern.fun, cl.CL_KERNEL_CONTEXT, sizeof(cl.cl_context), ctx, C_NULL)
cl.clGetKernelInfo(kernel, cl.CL_KERNEL_CONTEXT, sizeof(cl.cl_context), ctx, C_NULL)
return ctx[]
end

function kernel_device(kernel::KI.Kernel{OpenCLBackend})
function kernel_device(kernel::cl.Kernel)
ctx = kernel_context(kernel)
ctx == cl.context().id && return cl.device()
return context_device(cl.Context(ctx; retain=true))
end

@noinline function throw_device_mismatch(kernel)
@noinline function throw_device_mismatch(kernel::cl.Kernel)
throw(ArgumentError("Cannot launch a kernel compiled for $(kernel_device(kernel).name) on $(cl.device().name)"))
end

@noinline function throw_geometry_keyword()
throw(ArgumentError("KernelInterface kernels take `numgroups`, `workgroupsize` or `ndrange`, not `global_size` or `local_size`"))
end

# activate the backend, and check that the kernel was compiled for its device. kept out of
# `KI.launch`, which is compiled for every kernel.
@noinline function prepare_launch(backend::OpenCLBackend, fun::cl.Kernel)
activate(backend)
kernel_context(fun) == cl.context().id || throw_device_mismatch(fun)
return
end

# passes the arguments on as a tuple, like calling the `HostKernel` does
function KI.launch(kernel::KI.Kernel{OpenCLBackend}, groups::Dims{3}, items::Dims{3},
args::Tuple; kwargs...)
# KernelInterface has validated the launch geometry
if haskey(kwargs, :global_size) || haskey(kwargs, :local_size)
throw_geometry_keyword()
end
activate(kernel.backend)
kernel_context(kernel) == cl.context().id || throw_device_mismatch(kernel)
prepare_launch(kernel.backend, kernel.kern.fun)
OpenCL.launch_tuple(kernel.kern, args; local_size = items, global_size = items .* groups,
kwargs...)
return
end

function KI.max_work_group_size(kernel::KI.Kernel{OpenCLBackend})::Int
wginfo = cl.work_group_info(kernel.kern.fun, kernel_device(kernel))
# KernelAbstractions calls this from its launch code, which is compiled for every kernel
KI.max_work_group_size(kernel::KI.Kernel{OpenCLBackend}) = max_work_group_size(kernel.kern.fun)
@noinline function max_work_group_size(fun::cl.Kernel)
wginfo = cl.work_group_info(fun, kernel_device(fun))
Int(wginfo.size)
end


## Device Properties

# querying the device allocates, so cache what launches and kernels need. the cache is
# keyed on the device, because the task-local device can be switched.
# keyed on the device, because the task-local device can be switched. not inlined, as the
# device queries are used in launch code that is compiled for every kernel.
const DeviceProperties = @NamedTuple{
max_work_group_size::Int, max_work_group_dims::NTuple{3, Int}, compute_units::Int,
float64::Bool, unified::Bool,
# 0 if the device doesn't support sub-groups of a fixed width
sub_group_size::Int, shuffle::Bool, float16::Bool,
linear_sub_groups::Bool, independent_sub_groups::Bool, partitionable_sub_groups::Bool,
}
function device_properties(dev::cl.Device)
@noinline function device_properties(dev::cl.Device)
cache = get!(task_local_storage(), :CLDeviceProperties) do
Dict{cl.Device, DeviceProperties}()
end::Dict{cl.Device, DeviceProperties}
Expand Down
45 changes: 32 additions & 13 deletions src/compiler/exceptions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -179,26 +179,45 @@ end
function launch_with_exception_mailbox(kernel::cl.Kernel, args::Tuple;
indirect_memory::Vector{cl.AbstractMemory},
rng_state::Bool, kwargs...)
mailbox, queue = current_exception_mailbox()
Base.@lock mailbox.lock begin
state = next_kernel_state(mailbox, indirect_memory, rng_state)
result = cl.call(kernel, prepend(state, args); indirect_memory, rng_state, kwargs...)
# only publish the launch once it has been submitted, so that `check_exceptions`
# can tell whether kernels have been submitted while it waited without the lock
publish_launch(mailbox, queue, state.launch_id)
return result
end
end

# the parts of the launch that don't depend on the arguments, kept out of the function above,
# which is compiled for every kernel signature

@noinline function current_exception_mailbox()
ctx, dev, queue = cl.context(), cl.device(), cl.queue()
mailbox = Base.@lock exception_mailboxes_lock begin
get!(exception_mailboxes, (ctx, dev)) do
allocate_exception_mailbox(ctx)
end
end
Base.@lock mailbox.lock begin
mailbox.mem === nothing || push!(indirect_memory, mailbox.mem)
launch_id = (Base.@atomic mailbox.launch_id) + UInt64(1)
state = KernelState(rng_state ? Base.rand(UInt32) : UInt32(0), mailbox.address,
launch_id)
result = cl.call(kernel, prepend(state, args); indirect_memory, rng_state, kwargs...)
# only publish the launch once it has been submitted, so that `check_exceptions`
# can tell whether kernels have been submitted while it waited without the lock
Base.@atomic mailbox.launch_id = launch_id
if mailbox.mem !== nothing
push!(mailbox.pending, queue)
end
return result
return mailbox, queue
end

@noinline function next_kernel_state(mailbox::ExceptionMailbox,
indirect_memory::Vector{cl.AbstractMemory},
rng_state::Bool)
mailbox.mem === nothing || push!(indirect_memory, mailbox.mem)
launch_id = (Base.@atomic mailbox.launch_id) + UInt64(1)
return KernelState(rng_state ? Base.rand(UInt32) : UInt32(0), mailbox.address, launch_id)
end

@noinline function publish_launch(mailbox::ExceptionMailbox, queue::cl.CmdQueue,
launch_id::UInt64)
Base.@atomic mailbox.launch_id = launch_id
if mailbox.mem !== nothing
push!(mailbox.pending, queue)
end
return
end

"""
Expand Down
10 changes: 8 additions & 2 deletions src/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,15 @@ end
const clfunction_lock = ReentrantLock()

function clfunction(f::F, tt::TT=Tuple{}; source=f, kwargs...) where {F,TT}
kernel, device_rng = clfunction_link(methodinstance(F, tt); kwargs...)
HostKernel{F,typeof(source),tt}(f, source, kernel, device_rng)
end

# the part of `clfunction` that doesn't depend on the kernel's function and argument types,
# kept separate so that it's compiled once rather than for every kernel
function clfunction_link(mi::Core.MethodInstance; kwargs...)
Base.@lock clfunction_lock begin
config = compiler_config(cl.device(); kwargs...)::OpenCLCompilerConfig
mi = methodinstance(F, tt)
job = CompilerJob(mi, config)

res = compile_or_lookup(job)::OpenCLResults
Expand All @@ -282,7 +288,7 @@ function clfunction(f::F, tt::TT=Tuple{}; source=f, kwargs...) where {F,TT}
end
end

HostKernel{F,typeof(source),tt}(f, source, kernel, res.device_rng)
return kernel, res.device_rng
end
end

Expand Down
Loading