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 @@ -41,7 +41,7 @@ Adapt = "4"
CEnum = "0.5, 1"
Crayons = "4"
GPUArrays = "12.1"
GPUCompiler = "2.18"
GPUCompiler = "2.23"
GPUToolbox = "3.5"
IntelITT = "0.2"
KernelAbstractions = "0.10"
Expand Down
4 changes: 2 additions & 2 deletions docs/src/api/kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ launches the kernel on the GPU.
### `KernelException`

Thrown when synchronizing a stream on which a kernel threw an exception. It carries the
exception's `name` and `reason` (from debug level 1), and the `work_item` and `work_group`
that threw it along with a `backtrace` (from debug level 2).
`work_item` and `work_group` that threw it, the exception's `name` and `reason` (from debug
level 1), and a `backtrace` (from debug level 2).

### `zefunction(f, tt; kwargs...)`

Expand Down
8 changes: 4 additions & 4 deletions docs/src/kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,14 @@ julia> a = oneArray{Int}(undef, 1);
julia> @oneapi kernel(a)

julia> synchronize()
ERROR: KernelException: A BoundsError was thrown on Intel(R) Arc(TM) A770 Graphics: Out-of-bounds array access
ERROR: KernelException: A BoundsError was thrown by work-item 1×1×1 in work-group 1×1×1 on Intel(R) Arc(TM) A770 Graphics: Out-of-bounds array access
For more details, run Julia with `-g2`, or launch the kernel with `@oneapi debug_level=2`.
```

The amount of detail depends on the debug level the kernel is compiled with, which defaults
to Julia's `-g` level. At level 0 only the fact that an exception was thrown is reported; at
level 1 (the default) also its type and reason; at level 2 also the work-item that threw it
and a backtrace. Only one exception is reported per synchronization. If the task that
to Julia's `-g` level. At level 0 only the fact that an exception was thrown, and by which
work-item, is reported; at level 1 (the default) also its type and reason; at level 2 also a
backtrace. Only one exception is reported per synchronization. If the task that
launched the kernel finishes without synchronizing, the exception is reported by the next
`synchronize()` of another task, unless something waited for the kernel's results first.
Exceptions in kernels launched on an explicitly created `ZeCommandQueue` are not reported.
Expand Down
5 changes: 4 additions & 1 deletion lib/level-zero/module.jl
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,16 @@ mutable struct ZeKernel
# MAX_GROUP_SIZE extension. Read on every KernelInterface launch.
max_group_size::Int

# the throw sites of the kernel's code, which the exceptions it reports refer to
exception_sites::Vector{ExceptionSite}

function ZeKernel(mod, name)
GC.@preserve name begin
desc_ref = Ref(ze_kernel_desc_t(; pKernelName=pointer(name)))
handle_ref = Ref{ze_kernel_handle_t}()
zeKernelCreate(mod, desc_ref, handle_ref)
end
obj = new(mod, handle_ref[], ReentrantLock(), -1, -1)
obj = new(mod, handle_ref[], ReentrantLock(), -1, -1, ExceptionSite[])

finalizer(obj) do obj
zeKernelDestroy(obj)
Expand Down
2 changes: 2 additions & 0 deletions lib/level-zero/oneL0.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ using Printf

using Libdl

using GPUCompiler: ExceptionSite

if Sys.iswindows()
const libze_loader = "ze_loader"
else
Expand Down
23 changes: 15 additions & 8 deletions src/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ const oneAPICompilerJob = CompilerJob{SPIRVCompilerTarget,oneAPICompilerParams}

Cached compilation results for a oneAPI kernel job, managed by
`GPUCompiler.cached_results`. Fields are populated through the compile pipeline:
`image` (SPIR-V bytes) + `entry` after codegen, and `kernels` after the session-local
link onto a Level Zero module. The first two are session-portable (cached through
precompilation); `kernels` is session-local and never populated during precompilation.
`image` (SPIR-V bytes), `entry` and `exception_sites` after codegen, and `kernels` after the
session-local link onto a Level Zero module. The first three are session-portable (cached
through precompilation); `kernels` is session-local and never populated during
precompilation.
`image === nothing` identifies a job that has not been compiled yet.

`kernels` is a small linear cache of `(ZeContext, ZeDevice, ZeKernel)` tuples. The cache
Expand All @@ -27,11 +28,14 @@ workload that bounces between a handful of contexts or devices.
mutable struct oneAPIResults
image::Union{Nothing, Vector{UInt8}} # SPIR-V binary
entry::Union{Nothing, String}
exception_sites::Vector{GPUCompiler.ExceptionSite}
kernels::Vector{Tuple{ZeContext, ZeDevice, ZeKernel}} # session-local; linear-scanned
oneAPIResults() = new(nothing, nothing, Tuple{ZeContext, ZeDevice, ZeKernel}[])
oneAPIResults() = new(nothing, nothing, GPUCompiler.ExceptionSite[],
Tuple{ZeContext, ZeDevice, ZeKernel}[])
end

GPUCompiler.runtime_module(::oneAPICompilerJob) = oneAPI
GPUCompiler.uses_exception_sites(::oneAPICompilerJob) = true

GPUCompiler.kernel_state_type(::oneAPICompilerJob) = KernelState

Expand Down Expand Up @@ -249,23 +253,26 @@ end
CompilerConfig(target, params; kernel, name, always_inline, debug_level)
end

# run inference + LLVM codegen + SPIR-V emission. returns `(image, entry)`, both
# session-portable so they survive precompilation when stored on a cached `CodeInstance`.
# run inference + LLVM codegen + SPIR-V emission. returns `(image, entry, exception_sites)`,
# all session-portable so they survive precompilation when stored on a cached `CodeInstance`.
function compile_to_obj(@nospecialize(job::CompilerJob))
# TODO: on 1.9, this actually creates a context. cache those.
return JuliaContext() do ctx
asm, meta = GPUCompiler.compile(:obj, job)
# the IR belongs to us: dispose of it, or it leaks along with the context
@dispose ir = meta.ir begin
(image = asm, entry = meta.entry.name)
(image = asm, entry = meta.entry.name, meta.exception_sites)
end
end
end

# link the SPIR-V bytes into a session-local `ZeKernel` on the given context and device.
function link_kernel(image::Vector{UInt8}, entry::String, ctx::ZeContext, dev::ZeDevice)
function link_kernel(image::Vector{UInt8}, entry::String,
exception_sites::Vector{GPUCompiler.ExceptionSite},
ctx::ZeContext, dev::ZeDevice)
mod = ZeModule(ctx, dev, image)
kernel = kernels(mod)[entry]
kernel.exception_sites = exception_sites

# Kernels receive their arrays as `oneDeviceArray` structs, so to Level Zero every USM
# pointer they dereference is an indirect access. Without declaring that, the driver
Expand Down
126 changes: 57 additions & 69 deletions src/compiler/exceptions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ export KernelException
An exception thrown by a kernel on device `dev`, reported when synchronizing the stream it
was launched on (e.g. by `synchronize()`, or a copy to the host such as `Array(x)`).

What is known about the exception depends on the debug level the kernel was compiled with
(Julia's `-g` level, or `@oneapi debug_level=...`):
The position of the work-item that threw is always known (`work_item` is its local id,
`work_group` the id of its work-group). What else is known depends on the debug level the
kernel was compiled with (Julia's `-g` level, or `@oneapi debug_level=...`):

- `0`: only that an exception was thrown;
- `1`: also the `name` of its type and the `reason`, for exceptions thrown by Julia's
runtime (e.g. bounds errors, or domain errors in math functions);
- `2`: also the position of the work-item that threw (`work_item` is its local id,
`work_group` the id of its work-group), and its `backtrace` as `(function, file, line)`
tuples.
- `2`: also the `backtrace` of the throw, as `(function, file, line)` tuples.

Fields that were not recorded are empty, or zero. Only one exception is reported per
synchronization, and the other work-items of the kernel keep running.
Expand All @@ -41,7 +40,7 @@ function Base.showerror(io::IO, err::KernelException)
end
print(io, " on ", oneL0.properties(err.dev).name)
isempty(err.reason) || print(io, ": ", err.reason)
if err.work_item == (0, 0, 0)
if isempty(err.backtrace)
print(io, "\nFor more details, run Julia with `-g2`, or launch the kernel with `@oneapi debug_level=2`.")
else
print(io, "\nStacktrace:")
Expand All @@ -52,55 +51,6 @@ function Base.showerror(io::IO, err::KernelException)
end
end

const EXCEPTION_STRING_MAX = 4096

# buffers that copies may still be writing to, as their list could not be synchronized
const unsynchronized_string_buffers = Any[]
const unsynchronized_string_buffers_lock = ReentrantLock()

# Read the strings at `addresses`, as reported by a kernel, returning a dictionary that maps
# the addresses that could be read to their contents. The addresses come from memory the
# kernel could have corrupted, so they are only read if they fall within an allocation,
# such as a module's constants, and only up to the end of it. Freed modules are not read.
function read_device_strings(list, ctx::ZeContext, addresses)
buffers = Dict{UInt64, Vector{UInt8}}()
for address in addresses
(address == 0 || haskey(buffers, address)) && continue
base = Ref{Ptr{Cvoid}}()
size = Ref{Csize_t}()
res = oneL0.unchecked_zeMemGetAddressRange(ctx, Ptr{Cvoid}(address), base, size)
res == oneL0.RESULT_SUCCESS || continue
available = UInt64(UInt(base[]) + size[]) - address
available > 0 || continue
buffers[address] = Vector{UInt8}(undef, min(available, EXCEPTION_STRING_MAX))
end
isempty(buffers) && return Dict{UInt64, String}()
copied = false
GC.@preserve buffers try
for (address, buffer) in buffers
append_copy!(list, pointer(buffer), ZePtr{UInt8}(address), length(buffer))
end
copied = true
catch err
bt = catch_backtrace()
@error "Failed to read the strings of a kernel exception" exception=(err, bt)
finally
# copies appended before a failure still write to the buffers
if oneL0.unchecked_zeCommandListHostSynchronize(list, typemax(UInt64)) !=
oneL0.RESULT_SUCCESS
@lock unsynchronized_string_buffers_lock begin
push!(unsynchronized_string_buffers, buffers)
end
copied = false
end
end
copied || return Dict{UInt64, String}()
return Dict(address => String(buffer[1:something(findfirst(iszero, buffer),
length(buffer) + 1) - 1])
for (address, buffer) in buffers)
end


## per-stream report

# Reports are carved out of slabs shared by a device's streams, as kernels access memory
Expand All @@ -109,10 +59,24 @@ const REPORTS_PER_SLAB = 64

const free_report_slots = Dict{Tuple{ZeContext, ZeDevice}, Vector{ReportSlot}}()

KernelState(s::oneStream) = KernelState(UInt(s.exceptions.report) % UInt64,
UInt(s.exceptions.claim) % UInt64)
KernelState(s::oneStream, kernel::ZeKernel) =
KernelState(UInt(s.exceptions.report) % UInt64, UInt(s.exceptions.claim) % UInt64,
kernel_id(kernel))
# explicitly created queues have no report
KernelState(::ZeCommandQueue) = KernelState()
KernelState(::ZeCommandQueue, ::ZeKernel) = KernelState()

# how a launch identifies its kernel in the report. the stream keeps the kernels it launched
# alive until it has checked the report (see `note_launch!`), so the id is not reused.
kernel_id(kernel::ZeKernel) = UInt(pointer_from_objref(kernel)) % UInt64

# Remember that `kernel` was launched on `s`, to look up the exceptions it reports. The
# caller must hold `s.lock`.
@inline function note_launch!(s::oneStream, kernel::ZeKernel)
s.last_launched === kernel && return
push!(s.launched, kernel)
s.last_launched = kernel
return
end

# the pattern resetting a claim; a global, as Level Zero does not specify how long a fill's
# pattern has to remain valid
Expand Down Expand Up @@ -185,23 +149,47 @@ end
# The caller must hold `s.lock`, and have checked that the stream is idle.
function check_exception!(s::oneStream)
slot = s.exceptions
unsafe_load(convert(Ptr{Int32}, slot.report)) == 0 && return nothing # `status`
if unsafe_load(convert(Ptr{Int32}, slot.report)) == 0 # `status`
forget_launches!(s)
return nothing
end
report = unsafe_load(slot.report)

# reset the claim first: if that fails, the exception is still reported later
reset_claim!(s.immediate, slot)
clear_report!(slot)

nframes = clamp(Int(report.num_frames), 0, EXCEPTION_MAX_FRAMES)
frames = report.frames[1:nframes]
strings = read_device_strings(s.immediate, s.ctx,
[report.name; report.reason;
[frame.func for frame in frames];
[frame.file for frame in frames]])
str(address) = get(strings, address, "")
backtrace = Tuple{String, String, Int}[(str(frame.func), str(frame.file),
Int(frame.line)) for frame in frames]
return KernelException(s.dev, str(report.name), str(report.reason),
# the report was written by the device, so it is only trusted to identify a kernel
# launched since the last check, and a site in that kernel's table
kernel = nothing
for k in s.launched
if kernel_id(k) == report.kernel
kernel = k
break
end
end
forget_launches!(s)
sites = kernel === nothing ? GPUCompiler.ExceptionSite[] : kernel.exception_sites
site = get(sites, Int(report.site), nothing)
name, reason, backtrace = if site === nothing
"", "", Tuple{String, String, Int}[]
else
site.name, site.reason,
Tuple{String, String, Int}[(frame.func, frame.file, frame.line)
for frame in site.frames]
end
return KernelException(s.dev, name, reason,
Int.(report.work_item[1:3]), Int.(report.work_group[1:3]),
backtrace)
end

# Forget the kernels launched on `s`, once the report was checked, unless some may still
# execute: those recorded in a batch, or in batches that failed to submit. The caller must
# hold `s.lock`, and have checked that the stream is idle.
function forget_launches!(s::oneStream)
if s.batch === nothing && isempty(s.failed)
empty!(s.launched)
s.last_launched = nothing
end
return
end
7 changes: 5 additions & 2 deletions src/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ function call_arguments(@nospecialize(F), @nospecialize(TT), nargs::Int)

# Add GPUCompiler's hidden state argument here so `onecall` can also call foreign kernels.
call_t = Type[KernelState]
call_args = Any[:(KernelState(queue))]
call_args = Any[:(KernelState(queue, kernel.fun))]

for (dt, ex) in zip(params, exprs)
# filter out ghost arguments that shouldn't be passed
Expand Down Expand Up @@ -369,7 +369,8 @@ function zefunction_link(source::Core.MethodInstance; kwargs...)
end
end
if fun === nothing
fun = link_kernel(res.image::Vector{UInt8}, res.entry::String, ctx, dev)
fun = link_kernel(res.image::Vector{UInt8}, res.entry::String,
res.exception_sites, ctx, dev)
# 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 @@ -399,6 +400,7 @@ end
res = @something res GPUCompiler.cached_results(oneAPIResults, job)
res.image = compiled.image
res.entry = compiled.entry
res.exception_sites = compiled.exception_sites
end
return res
end
Expand Down Expand Up @@ -442,6 +444,7 @@ end
direct |= !s.batching || s.idle || oneL0.sync_each_submission()
batch = direct ? nothing : open_batch!(s)
register_pending!(s)
note_launch!(s, kernel)
if batch === nothing
flush_batch!(s)
append_launch!(s.immediate, kernel, groups)
Expand Down
8 changes: 6 additions & 2 deletions src/context.jl
Original file line number Diff line number Diff line change
Expand Up @@ -296,8 +296,11 @@ mutable struct oneStream
scratch_hwm::Int
const priority::oneL0.ze_command_queue_priority_t

# where kernels report exceptions, see `check_exception!`
# where kernels report exceptions, and the kernels launched since it was last checked,
# which identify the exception (see `check_exception!`), protected by `lock`
const exceptions::ReportSlot
const launched::Base.IdSet{ZeKernel}
last_launched::Union{Nothing, ZeKernel}
end

function create_stream(ctx::ZeContext, dev::ZeDevice,
Expand All @@ -324,7 +327,8 @@ function create_stream(ctx::ZeContext, dev::ZeDevice,
slot = allocate_report_slot(ctx, dev, list)
s = oneStream(ctx, dev, list, ReentrantLock(),
batching, nothing, Batch[], Batch[], 0, nothing, true, nothing, DataRef[],
Batch[], nothing, nothing, false, 0, priority, slot)
Batch[], nothing, nothing, false, 0, priority, slot,
Base.IdSet{ZeKernel}(), nothing)
finalizer(release_report_slot, s)
return register_stream!(ctx, dev, s)
end
Expand Down
Loading
Loading