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
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ AMDGPU = "2"
Adapt = "0.4, 1.0, 2.0, 3.0, 4"
Atomix = "1.5"
EnzymeCore = "0.8.25"
GPUCompiler = "2.20"
GPUCompiler = "2.23"
GPUToolbox = "3.6"
KernelInterface = "0.4"
LLVM = "10"
Expand Down
6 changes: 3 additions & 3 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,9 @@ end
concrete backend types, or on a capability such as `KernelAbstractions.supports_float64`.
- An exception thrown in a kernel on the `CPU` backend is reported as a
`KernelAbstractions.POCL.KernelException` when the kernel has completed, like on GPU
backends, and no longer as the original exception (e.g., a `BoundsError`). Depending on
the debug level (`julia -g`), the kernel prints which exception it threw, on which
work-item, and with `-g2` a backtrace.
backends, and no longer as the original exception (e.g., a `BoundsError`). It names the
work-item that threw, and depending on the debug level (`julia -g`) which exception it
threw, and with `-g2` a backtrace.
- The `CPU` backend runs kernels on as many threads as Julia was started with (`julia -t`),
like the thread-based `CPU` backend of 0.9 did, and no longer on one thread per hardware
thread. Set `JULIA_KA_CPU_THREADS` to use a different number of threads; see [`CPU`](@ref).
Expand Down
17 changes: 13 additions & 4 deletions src/pocl/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,15 @@ mutable struct OpenCLResults
obj::Union{Nothing, Vector{UInt8}} # SPIR-V binary
entry::Union{Nothing, String}
device_rng::Bool
exception_sites::Vector{GPUCompiler.ExceptionSite}
kernels::Vector{Tuple{cl.Context, cl.Kernel}} # session-local; linear-scanned
OpenCLResults() = new(nothing, nothing, false, Tuple{cl.Context, cl.Kernel}[])
OpenCLResults() = new(
nothing, nothing, false, GPUCompiler.ExceptionSite[], Tuple{cl.Context, cl.Kernel}[]
)
end

GPUCompiler.runtime_module(::CompilerJob{<:Any, OpenCLCompilerParams}) = POCL
GPUCompiler.uses_exception_sites(::CompilerJob{<:Any, OpenCLCompilerParams}) = true

# SPIR-V doesn't support 128-bit integers, so keep 64-bit integer math (e.g. `Rational`
# comparisons) that Base computes with them out of Int128. Some of Base's error paths format
Expand Down Expand Up @@ -282,7 +286,8 @@ const initialization_world = Ref{UInt}(typemax(UInt))

invoke_frozen(f, args...) = Base.invoke_in_world(initialization_world[], f, args...)

# run inference + LLVM codegen + SPIR-V emission. returns `(obj, entry, device_rng)`,
# run inference + LLVM codegen + SPIR-V emission. returns `(obj, entry, device_rng,
# exception_sites)`,
# all session-portable so they survive precompilation when stored on a cached `CodeInstance`.
const compilations = Threads.Atomic{Int}(0)
function compile_to_obj(@nospecialize(job::CompilerJob))
Expand All @@ -295,13 +300,16 @@ function compile_to_obj(@nospecialize(job::CompilerJob))
@dispose ir = meta.ir begin
entry = meta.entry.name
device_rng = haskey(meta.entry.function_attributes, "julia.opencl.rng")
(; obj, entry, device_rng)
(; obj, entry, device_rng, meta.exception_sites)
end
end
end

# link the SPIR-V bytes into a session-local `cl.Kernel` on the active context.
function link_kernel(@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry::String)
function link_kernel(
@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry::String,
exception_sites::Vector{GPUCompiler.ExceptionSite}
)
prog = if "cl_khr_il_program" in device().extensions
cl.Program(obj, context())
else
Expand All @@ -312,5 +320,6 @@ function link_kernel(@nospecialize(job::CompilerJob), obj::Vector{UInt8}, 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))
kernel.exception_sites = exception_sites
return kernel
end
62 changes: 49 additions & 13 deletions src/pocl/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ function launch_and_wait(
event = launch_queued(with_fun(kernel, partial), converted, info_ptr; kwargs...)
wait_for_kernel(event)
end
check_exception(info)
info[].status == 0 || throw_kernel_exception(info[], something(partial, kernel.fun))
else
global_size = values(kwargs).global_size
num_groups = something(groups, global_size .÷ hp.local_size)
Expand All @@ -211,8 +211,8 @@ function launch_and_wait(
info_ptr = Base.unsafe_convert(Ptr{ExceptionInfo_st}, info)
host_launch_converted(kernel, converted, info_ptr, hp, num_groups, h, extent)
end
# passing the status avoids allocating `info`
check_exception(info[].status)
info[].status == 0 ||
throw_host_exception(info[], kernel.fun, partial, h === hp, hp.local_size, extent)
end
end
return nothing
Expand All @@ -228,12 +228,26 @@ end
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
# the exception that `fun` reported in `info`
@noinline function throw_kernel_exception(info::ExceptionInfo_st, fun::cl.Kernel)
sites = fun.exception_sites
site = 1 <= info.site <= length(sites) ? sites[info.site] : nothing
throw(KernelException(device(), site, ntuple(d -> info.item[d], Val(3))))
end

# work-groups extending beyond `extent` ran `partial`, as did all of them if there was no
# full variant (`all_partial`). each variant has throw sites of its own.
@noinline function throw_host_exception(
info::ExceptionInfo_st, fun::cl.Kernel, partial::Union{Nothing, cl.Kernel},
all_partial::Bool, local_size::Dims{3}, extent::Dims{3}
)
if partial !== nothing
item = info.item
edge = any(d -> cld(item[d], local_size[d]) * local_size[d] > extent[d], 1:3)
(all_partial || edge) && (fun = partial)
end
throw_kernel_exception(info, fun)
end
@noinline throw_kernel_exception() = throw(KernelException(device()))

@inline launch_tuple(
kernel::AbstractKernel, args::Tuple, exception_info::Ptr;
Expand Down Expand Up @@ -302,15 +316,36 @@ end
"""
KernelException

An exception thrown during kernel execution on device `dev`. The kernel prints details about
the exception when it occurs, depending on the debug level (see Julia's `-g` option).
An exception thrown during kernel execution on device `dev`, by the work-item with global id
`item`. If the debug level is 1 or higher (see Julia's `-g` option), `site` describes what was
thrown: the exception's name, the reason, and at debug level 2 a backtrace.
"""
struct KernelException <: Exception
dev::cl.Device
site::Union{Nothing, GPUCompiler.ExceptionSite}
item::Dims{3}
end

Base.showerror(io::IO, err::KernelException) =
print(io, "KernelException: exception thrown during kernel execution on device ", err.dev.name)
function Base.showerror(io::IO, err::KernelException)
site = err.site
if site === nothing
print(
io, "KernelException: exception thrown during kernel execution on work-item ",
err.item, " of device ", err.dev.name
)
return
end
print(io, "KernelException: ", site.name, " during kernel execution on work-item ", err.item)
isempty(site.reason) || print(io, ": ", site.reason)
return if isempty(site.frames)
print(io, "\nRun Julia on debug level 2 for a device stack trace.")
else
print(io, "\nStacktrace:")
for (i, frame) in enumerate(site.frames)
print(io, "\n [", i, "] ", frame.func, " at ", frame.file, ":", frame.line)
end
end
end

# 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.
Expand Down Expand Up @@ -387,7 +422,7 @@ end
end
end
kernel = if cached === nothing
linked = link_kernel(job, res.obj::Vector{UInt8}, res.entry::String)
linked = link_kernel(job, res.obj::Vector{UInt8}, res.entry::String, res.exception_sites)
# Don't cache session-local kernel handles while precompiling: the
# results struct is serialized into the package image along with its
# CodeInstance, and the handles would come back dangling.
Expand Down Expand Up @@ -428,6 +463,7 @@ end
res.obj = compiled.obj
res.entry = compiled.entry
res.device_rng = compiled.device_rng
res.exception_sites = compiled.exception_sites
end
return res
end
Expand Down
13 changes: 2 additions & 11 deletions src/pocl/device/quirks.jl
Original file line number Diff line number Diff line change
@@ -1,14 +1,5 @@
# throw a device-side exception of type `name`, reporting it with `reason`
macro gputhrow(name::String, reason::String)
escape(str) = replace(str, "%" => "%%")
fmt = "ERROR: $(escape(name)) during kernel execution on work-item (%ld, %ld, %ld): $(escape(reason)).\n"
return quote
if GPUCompiler.kernel_debug_level() >= 1 && claim_output() == 1
SPIRVIntrinsics.@printf($fmt, get_global_id(1), get_global_id(2), get_global_id(3))
end
throw(nothing)
end
end
# throw a device-side exception of type `name`, reported with `reason`
using GPUCompiler: @gputhrow

# GPUToolbox's shared overrides throw through this function
@device_override @generated function GPUToolbox.Overlays.device_throw(::Type{E}, ::Val{reason}) where {E <: Exception, reason}
Expand Down
91 changes: 17 additions & 74 deletions src/pocl/device/runtime.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
# CPU device can access directly, and the task that launched the kernel checks it once the
# kernel has completed.
struct ExceptionInfo_st
# set when a work-item has thrown
# set by the first work-item that throws, which then records the rest
status::Int32
# claimed by the work-item that reports the exception, see `claim_output`
output_lock::Int32
owner::NTuple{4, Int} # padded: SPIR-V has no vectors of 6 elements, in case of merges
# the throw site, see `GPUCompiler.uses_exception_sites`
site::Int32
# the global id of the work-item that threw
item::NTuple{4, Int} # padded: SPIR-V has no vectors of 6 elements, in case of merges

ExceptionInfo_st() = new(0, 0, (0, 0, 0, 0))
ExceptionInfo_st(status = 0 % Int32, site = 0 % Int32, item = (0, 0, 0, 0)) = new(status, site, item)
end

# a pointer to one of the fields of the launch's `ExceptionInfo_st`
Expand All @@ -24,89 +25,31 @@ end
# host methods, and a sysimage that references device intrinsics fails to load
# (JuliaGPU/GPUCompiler.jl#611).

# the record is shared by all work-items on the device, so these need device scope, which
# UnsafeAtomics' primitives emit as given (SPIRVIntrinsics' atomics are relaxed)
@device_function @inline function atomic_store_device!(ptr::LLVMPtr{Int32, AS.CrossWorkgroup}, val::Int32)
UnsafeAtomics.Internal.llvm_store!(
ptr, val, Val(:release), Val(:device), Val(false), Val(sizeof(Int32)), Val(())
)
return
end
# not a compare-and-swap: PoCL's builtin for it returns the old value through a stack slot.
# `claim_output` reads work-item ids, so PoCL inlines it into every throw site before forming
# the work-item loops, which give each copy of the slot an array over the work-group. LLVM 22
# can't forward stores across the cmpxchg, so these arrays stay: megabytes of stack for a
# kernel with many bounds checks (JuliaGPU/KernelAbstractions.jl#974). LLVM 23 removes them
# (llvm/llvm-project#193939).
# the record is shared by all work-items on the device, so this needs device scope, which
# UnsafeAtomics' primitives emit as given (SPIRVIntrinsics' atomics are relaxed). not a
# compare-and-swap: PoCL's builtin for it returns the old value through a stack slot, which
# PoCL's work-item loops can widen into an array over the work-group
# (JuliaGPU/KernelAbstractions.jl#974).
@device_function @inline function atomic_max_device!(ptr::LLVMPtr{Int32, AS.CrossWorkgroup}, val::Int32)
return UnsafeAtomics.Internal.llvm_rmw!(
ptr, Val(:max), val, Val(:acq_rel), Val(:device), Val(false), Val(sizeof(Int32)), Val(())
)
end

# only one work-item reports the exception, or the output of all work-items that throw
# would be interleaved. it can do so over several calls (e.g., a quirk printing the exception,
# and GPUCompiler printing a backtrace). returns 1 when the output was just claimed, 2 when
# it was claimed by an earlier call of this work-item, and 0 when it belongs to another.
# the work-item that threw stops executing after this. the first one to throw records where;
# the host knows what was thrown there.
#
# nothing reachable from the throw overrides may throw, not even a checked conversion like
# `Int32(0)`: the resulting inference cycle through `throw_inexacterror` taints Base's
# conversions on Julia 1.12+, which then can't be constant-folded (e.g. in `reinterpret`)
@device_function @noinline function claim_output()
lock = exception_field(Val(:output_lock))
me = (get_global_id(1), get_global_id(2), get_global_id(3), 0)
# 0 → 1 claims the output; 1 and 2 stay
state = atomic_max_device!(lock, 1 % Int32)
if state == 0
unsafe_store!(exception_field(Val(:owner)), me)
# publish the owner before other work-items compare against it
atomic_store_device!(lock, 2 % Int32)
return 1
end
# don't wait for the owner to be published: it may be a work-item that only executes
# after this one, e.g., in the same loop over a work-group
return state == 2 && unsafe_load(exception_field(Val(:owner))) == me ? 2 : 0
end

@device_function function report_exception(ex)
claim = claim_output()
if claim == 1
SPIRVIntrinsics.@printf(
"ERROR: %s during kernel execution on work-item (%ld, %ld, %ld).\n", ex, get_global_id(1), get_global_id(2), get_global_id(3)
)
end
if claim != 0
SPIRVIntrinsics.@printf("Run Julia on debug level 2 for a device stack trace.\n")
@device_function function exception_site(site::Int32)
if atomic_max_device!(exception_field(Val(:status)), 1 % Int32) == 0
unsafe_store!(exception_field(Val(:site)), site)
unsafe_store!(exception_field(Val(:item)), (get_global_id(1), get_global_id(2), get_global_id(3), 0))
end
return
end

@device_function function report_exception_name(ex)
claim = claim_output()
if claim == 1
SPIRVIntrinsics.@printf(
"ERROR: %s during kernel execution on work-item (%ld, %ld, %ld).\n", ex, get_global_id(1), get_global_id(2), get_global_id(3)
)
end
if claim != 0
SPIRVIntrinsics.@printf("Stacktrace:\n")
end
return
end

@device_function function report_exception_frame(idx, func, file, line)
if claim_output() != 0
SPIRVIntrinsics.@printf(" [%d] %s at %s:%d\n", idx, func, file, line)
end
return
end

# the work-item that threw stops executing after this
@device_function function signal_exception()
atomic_store_device!(exception_field(Val(:status)), 1 % Int32)
return
end

# these use no device intrinsics, so they can stay host methods. as overlays, inference could
# constant-fold calls to them by running the host method, which throws.
malloc(sz) = C_NULL
Expand Down
5 changes: 4 additions & 1 deletion src/pocl/nanoOpenCL.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import pocl_standalone_jll

using GPUToolbox: GPUToolbox, @gcsafe_ccall, cooperative_wait
using KernelInterface: inline_body
using GPUCompiler: ExceptionSite

using Printf

Expand Down Expand Up @@ -1340,6 +1341,8 @@ mutable struct Kernel
const private_mem_size::Int
# the largest work-group of tuned launches (see `POCL.link_kernel`)
tuned_work_group_size::Int
# the throw sites of its code, which the exceptions it reports refer to
exception_sites::Vector{ExceptionSite}

function Kernel(k::cl_kernel)
function get(param, T = Csize_t)
Expand All @@ -1352,7 +1355,7 @@ mutable struct Kernel
new(
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
get(CL_KERNEL_PRIVATE_MEM_SIZE, cl_ulong), work_group_size, ExceptionSite[]
)
catch
clReleaseKernel(k)
Expand Down
11 changes: 5 additions & 6 deletions test/codegen_checks.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,19 +123,18 @@ end
end
end

# Without `@inbounds` the kernel carries the out-of-bounds path: a printf of the error
# and the GPUCompiler exception signalling. `@inbounds` must remove all of it.
# Without `@inbounds` the kernel carries the out-of-bounds path, which records the throw
# site and work-item for the host, starting with an atomic max on the status.
# `@inbounds` must remove all of it.
@testset "bounds checks" begin
@test @filecheck begin
@check "define spir_kernel void @{{.*}}gpu_codegen_mul2"
@check "@printf"
@check "gpu_report_exception"
@check "gpu_signal_exception"
@check "__spirv_AtomicSMax"
@device_code_llvm debuginfo = :none codegen_mul2(backend)(A, ndrange = 64)
KernelAbstractions.synchronize(backend)
end

@test @filecheck implicit_check_not = ["gpu_report_exception", "@printf"] begin
@test @filecheck implicit_check_not = ["__spirv_AtomicSMax", "@printf"] begin
@check "define spir_kernel void @{{.*}}gpu_codegen_mul2_inbounds"
@check "ret void"
@device_code_llvm debuginfo = :none codegen_mul2_inbounds(backend)(A, ndrange = 64)
Expand Down
Loading
Loading