Skip to content
Open
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
18 changes: 18 additions & 0 deletions docs/src/kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,24 @@ reduce performance. Avoid repeated allocations in loops: even short-lived object
heap space until the work-item exits.


## Large Arguments

Kernel arguments are passed by value, and Level Zero limits their total size to the
device's `oneL0.module_properties(device()).maxArgumentsSize`, 2048 bytes on current Intel
GPUs. When a kernel's arguments exceed it, the largest ones are passed through memory
instead: each launch passes a pointer to a copy of the value in device memory, which the
kernel loads before running. The kernel sees the same values either way. Copies are cached
by content, so launching a kernel again with the same value doesn't copy it again; copying
a new value waits for the task's queue to finish its work on discrete GPUs. Kernels whose
arguments fit are not affected. If the arguments don't fit even then, e.g. with many small
ones, compiling the kernel throws an `ArgumentError` that lists their sizes.

A kernel that indexes such a value dynamically, or passes it to a function that isn't
inlined, keeps a copy of it in private memory for each work-item. That counts against the
scratch space a kernel can use; a kernel that needs more than the device supports fails to
build with "total scratch space exceeds HW supported limit".


## Exceptions

A work-item that throws an exception, e.g. on an out-of-bounds access, exits without
Expand Down
218 changes: 218 additions & 0 deletions src/compiler/arguments.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
# kernel arguments that are too large to pass by value
#
# Level Zero limits the total size of a kernel's arguments to the device's
# `maxArgumentsSize`, 2048 bytes on current Intel GPUs. On PVC that is a hardware limit, as
# the arguments are loaded into a block of registers when a thread starts, and IGC refuses
# to build a module with a kernel that exceeds it. Julia kernels pass their arguments by
# value, though, including large isbits structs like the expression trees of ExaModels.
#
# A kernel whose arguments don't fit is therefore compiled as a wrapper, `SpilledKernel`,
# that takes the largest of them by reference instead: through a device pointer to a copy
# of the value in device memory, which the wrapper loads before calling the kernel with
# the value. The kernel's code is the same either way; kernels whose arguments fit are
# compiled and launched as before. Fields the kernel accesses statically are loaded from
# the copy directly; where it indexes the value dynamically, or passes it to a function
# that isn't inlined, the loaded value is kept in private memory, which counts against
# the scratch space a kernel can use.
#
# IGC can also fail to fit arguments that are within the limit into registers, so kernels
# with large arguments whose build fails are built again with them passed through memory.
#
# The copies are cached by content (see `argument_buffer`), as kernels are typically
# launched over and over with the same large argument, and a copy to device memory waits
# for the stream on discrete GPUs.

# The arguments `zefunction` passes through memory, by position in (f, args...).
struct ArgumentSpill
mask::Vector{Bool}
end

# The type of the kernel argument that Level Zero receives for a Julia argument of type
# `T`, or `nothing` if it isn't passed (see `call_arguments`).
function kernel_argument_type(@nospecialize(T))
(isghosttype(T) || Core.Compiler.isconstType(T)) && return nothing
return isbitstype(T) ? T : Ptr{Any}
end

# The size of the arguments of a kernel taking arguments of the given types, after the
# hidden kernel state. Each argument is aligned to its alignment, as IGC lays them out.
function kernel_arguments_size(types)
size = sizeof(KernelState)
for T in types
T === nothing && continue
align = Base.datatype_alignment(T)
size = cld(size, align) * align + sizeof(T)
end
return size
end

# A short name for error messages, the full type of a kernel can be huge
function kernel_name(@nospecialize(F))
name = isdefined(F, :instance) ? nameof(F.instance) : nameof(F)
return string(name)
end

# Determine which arguments of a kernel with function type `F` and argument types `TT` to
# pass through memory, if their total size exceeds `limit`: as few as possible, the largest
# first. Returns `nothing` if all arguments can be passed by value. Throws if they don't fit
# even then, or with `strict=false` returns `nothing`.
function argument_spill(@nospecialize(F), @nospecialize(TT), limit::Int; strict::Bool=true)
types = Any[F, TT.parameters...]
args = Any[kernel_argument_type(T) for T in types]
size = kernel_arguments_size(args)
# (a driver that doesn't report a limit leaves it to the compiler)
(limit <= 0 || size <= limit) && return nothing

mask = Bool[false for _ in types]
candidates = filter(i -> args[i] !== nothing && isbitstype(args[i]) &&
sizeof(args[i]) > sizeof(Ptr{Cvoid}), eachindex(types))
sort!(candidates; by = i -> sizeof(args[i]), rev = true)
for i in candidates
mask[i] = true
args[i] = LLVMPtr{types[i], AS.CrossWorkgroup}
kernel_arguments_size(args) <= limit && return ArgumentSpill(mask)
end
strict || return nothing

sizes = join(("$(i == 1 ? "function" : "argument $(i-1)") ($(types[i])): $(sizeof(args[i])) bytes"
for i in eachindex(types) if args[i] !== nothing && sizeof(args[i]) > 0),
"\n ")
throw(ArgumentError("""The arguments of kernel `$(kernel_name(F))` take $size bytes, which \
exceeds the device's limit of $limit bytes, also when passing the \
ones larger than a pointer through memory. Sizes after doing so \
(not counting the $(sizeof(KernelState))-byte kernel state):
$sizes"""))
end

# The function and argument types that a kernel is compiled for when passing arguments
# through memory as `spill` determines.
function spilled_signature(@nospecialize(F), @nospecialize(TT), spill::ArgumentSpill)
types = Any[F, TT.parameters...]
for i in eachindex(types)
spill.mask[i] && (types[i] = LLVMPtr{types[i], AS.CrossWorkgroup})
end
return SpilledKernel{types[1], Tuple(spill.mask)}, Tuple{types[2:end]...}
end


## device side

# A kernel `f` with the arguments for which `Mask` is true (the first entry being for `f`
# itself) passed as pointers to their value.
struct SpilledKernel{F, Mask}
f::F
end

# the alignment of the copies of spilled arguments (see `argument_buffer`)
const SPILL_ALIGNMENT = 64

@generated function (kernel::SpilledKernel{F, Mask})(args::Vararg{Any, N}) where {F, Mask, N}
load(ex) = :(unsafe_load($ex, 1, Val($SPILL_ALIGNMENT)))
f = Mask[1] ? load(:(kernel.f)) : :(kernel.f)
call_args = Any[Mask[i+1] ? load(:(args[$i])) : :(args[$i]) for i in 1:N]
quote
Base.@_inline_meta
f = $f
# (returned, so that GPUCompiler rejects kernels that return a value as usual)
return @inline f($(call_args...))
end
end


## host side

# Device copies of spilled arguments, by content. Never written to after the upload, so
# that a launch can use the copy while another launch with the same value is in flight.
struct ArgumentBuffer
hash::UInt
bytes::Vector{UInt8}
buf::oneArray{UInt8, 1, oneL0.DeviceBuffer}
end

# per context and device, least recently used first
const argument_buffers = Dict{Tuple{ZeContext, ZeDevice}, Vector{ArgumentBuffer}}()
const argument_buffers_lock = ReentrantLock()

# how many copies to keep around, and how much memory they may take
const MAX_ARGUMENT_BUFFERS = 256
const MAX_ARGUMENT_BUFFER_BYTES = 64 * 2^20

# A device copy of the value `x`, from the cache or uploaded. Returns an array of its own,
# taken while holding the lock, so that another task evicting the copy from the cache
# doesn't free it before the launch has taken ownership.
function argument_buffer(ctx::ZeContext, dev::ZeDevice, x::T) where {T}
bytes = Base.zeros(UInt8, sizeof(T))
GC.@preserve bytes unsafe_store!(convert(Ptr{T}, pointer(bytes)), x)
h = hash(bytes)

@lock argument_buffers_lock begin
cache = get!(Vector{ArgumentBuffer}, argument_buffers, (ctx, dev))
for i in length(cache):-1:1
entry = cache[i]
if entry.hash == h && entry.bytes == bytes
deleteat!(cache, i)
push!(cache, entry)
return oneArray{UInt8, 1}(entry.buf.data, size(entry.buf))
end
end
end

# upload outside of the lock, as this waits for the stream on discrete GPUs
data = DataRef(release, alloc_managed(oneL0.DeviceBuffer, ctx, dev, length(bytes),
SPILL_ALIGNMENT))
buf = oneArray{UInt8, 1}(data, (length(bytes),))
unsafe_free!(data)
unsafe_copyto!(ctx, dev, buf, 1, bytes, 1, length(bytes))

ret = oneArray{UInt8, 1}(buf.data, size(buf))
evicted = @lock argument_buffers_lock begin
cache = argument_buffers[(ctx, dev)]
push!(cache, ArgumentBuffer(h, bytes, buf))
total = sum(entry -> length(entry.bytes), cache)
evicted = ArgumentBuffer[]
while length(cache) > 1 && (length(cache) > MAX_ARGUMENT_BUFFERS ||
total > MAX_ARGUMENT_BUFFER_BYTES)
entry = popfirst!(cache)
total -= length(entry.bytes)
push!(evicted, entry)
end
evicted
end
# (freeing memory can wait for the GPU, so not while holding the lock.) launches that
# still use the memory keep it alive, as they do for any array.
foreach(entry -> unsafe_free!(entry.buf), evicted)

return ret
end

# `launch_managed` for a kernel that passes arguments through memory: replace those by
# pointers to their device copy, and launch the wrapper the kernel was compiled as.
# Not specialized, as the argument types depend on which arguments are spilled.
@noinline function launch_spilled(kernel, source, args::Tuple, converted::Tuple,
refs::Vector{DataRef}, queue, kwargs::NamedTuple)
mask = kernel.spill.mask
ctx = kernel.fun.mod.context
dev = kernel.fun.mod.device
vals = Any[kernel.f, converted...]
buffers = oneArray{UInt8, 1, oneL0.DeviceBuffer}[]
for i in eachindex(vals)
mask[i] || continue
buf = argument_buffer(ctx, dev, vals[i])
push!(buffers, buf)
# the launch takes ownership of the copy as it does of the arrays it uses
push!(refs, buf.data)
vals[i] = reinterpret(LLVMPtr{typeof(vals[i]), AS.CrossWorkgroup}, device_pointer(buf))
end
f = SpilledKernel{Core.Typeof(vals[1]), Tuple(mask)}(vals[1])
wrapper_args = Tuple(vals[2:end])
wrapper = HostKernel{typeof(f), Tuple{map(Core.Typeof, wrapper_args)...}}(f, kernel.fun)

managed = Managed[ref[] for ref in refs]
ret = GC.@preserve source args with_ownership(queue, managed) do
call(wrapper, wrapper_args; queue, roots=refs, kwargs...)
end
# the submitted work owns the copies now, as it would after freeing any array
foreach(unsafe_free!, buffers)
release_pending!()
return ret
end
4 changes: 2 additions & 2 deletions src/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,8 @@ 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,
exception_sites::Vector{GPUCompiler.ExceptionSite},
ctx::ZeContext, dev::ZeDevice)
mod = ZeModule(ctx, dev, image)
ctx::ZeContext, dev::ZeDevice; log::Bool=true)
mod = ZeModule(ctx, dev, image; log)
kernel = kernels(mod)[entry]
kernel.exception_sites = exception_sites

Expand Down
55 changes: 46 additions & 9 deletions src/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,15 @@ struct HostKernel{F,TT} <: AbstractKernel{F,TT}
# only set on the kernels `@oneapi launch=false` returns, as the cached ones are shared
# by every callable that converts to `f`.
source::Any

# which arguments `fun` takes through memory, as they are too large to pass by value
# (see `ArgumentSpill`)
spill::Union{Nothing, ArgumentSpill}
end
HostKernel{F,TT}(f, fun::ZeKernel) where {F,TT} = HostKernel{F,TT}(f, fun, nothing)
HostKernel{F,TT}(f, fun::ZeKernel) where {F,TT} = HostKernel{F,TT}(f, fun, nothing, nothing)

with_source(kernel::HostKernel{F,TT}, source) where {F,TT} =
HostKernel{F,TT}(kernel.f, kernel.fun, source)
HostKernel{F,TT}(kernel.f, kernel.fun, source, kernel.spill)

# Upper bound on the spill (scratch) memory a single work-group may require, in bytes.
#
Expand Down Expand Up @@ -333,9 +337,10 @@ const zefunction_lock = ReentrantLock()
function zefunction(f::F, tt::TT=Tuple{}; kwargs...) where {F,TT}
# the kernel also depends on the task's context and device, see `zefunction_link`
kw = values(kwargs)
fun = GPUCompiler.cached_lookup(KernelLinker(F, tt, kw), ZeKernel, F, tt,
(context(), device(), kw))
return HostKernel{F,tt}(f, fun)
fun, spill = GPUCompiler.cached_lookup(KernelLinker(F, tt, kw),
Tuple{ZeKernel, Union{Nothing, ArgumentSpill}},
F, tt, (context(), device(), kw))
return HostKernel{F,tt}(f, fun, nothing, spill)
end

# What `zefunction` calls when the kernel isn't cached: a callable struct rather than a
Expand All @@ -346,11 +351,41 @@ struct KernelLinker{K}
tt::Type
kw::K
end
(l::KernelLinker)() = zefunction_link(methodinstance(l.ft, l.tt); l.kw...)
function (l::KernelLinker)()
limit = oneL0.module_properties(device()).maxArgumentsSize
spill = argument_spill(l.ft, l.tt, limit)
if spill === nothing
source = methodinstance(l.ft, l.tt)
# XXX: IGC can also fail to fit arguments below the limit into registers ("Kernel
# inputs exceed total register size"), e.g. a 1 KB tuple that is indexed
# dynamically, on DG2 and PVC alike. if the arguments are large, retry building
# with the larger ones through memory.
fallback = argument_spill(l.ft, l.tt, limit ÷ 2; strict=false)
fallback === nothing && return (zefunction_link(source; l.kw...), nothing)
try
return (zefunction_link(source, false; l.kw...), nothing)
catch err
err isa oneL0.ZeError &&
err.code == oneL0.ZE_RESULT_ERROR_MODULE_BUILD_FAILURE || rethrow()
spill = fallback
end
end

# compile the wrapper that loads the spilled arguments, under the name the kernel
# would have had
ft, tt = spilled_signature(l.ft, l.tt, spill)
kw = l.kw
if get(kw, :name, nothing) === nothing
kw = merge(kw, (; name = GPUCompiler.mangle_sig(Tuple{l.ft, l.tt.parameters...})))
end
@debug "Passing $(count(spill.mask)) arguments of kernel $(kw.name) through memory, as they don't fit by value (the device's limit is $limit bytes)"
return (zefunction_link(methodinstance(ft, tt); kw...), spill)
end

# the parts of `zefunction` that don't depend on the type of the function, kept separate so
# that they are compiled once rather than for every kernel
function zefunction_link(source::Core.MethodInstance; kwargs...)
# that they are compiled once rather than for every kernel. `log` is whether to report the
# build log of a module that fails to build.
function zefunction_link(source::Core.MethodInstance, log::Bool=true; kwargs...)
Base.@lock zefunction_lock begin
ctx = context()
dev = device()
Expand All @@ -370,7 +405,7 @@ function zefunction_link(source::Core.MethodInstance; kwargs...)
end
if fun === nothing
fun = link_kernel(res.image::Vector{UInt8}, res.entry::String,
res.exception_sites, ctx, dev)
res.exception_sites, ctx, dev; log)
# 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 @@ -511,6 +546,8 @@ end
refs = DataRef[]
source === nothing || kernel_convert(source, refs)
converted = map(arg -> kernel_convert(arg, refs), args)
kernel.spill === nothing ||
return launch_spilled(kernel, source, args, converted, refs, queue, values(kwargs))
managed = Managed[ref[] for ref in refs]
ret = GC.@preserve source args with_ownership(queue, managed) do
call(kernel, converted; queue, roots=refs, kwargs...)
Expand Down
1 change: 1 addition & 0 deletions src/oneAPI.jl
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ include("array.jl")

# compiler implementation
include("compiler/compilation.jl")
include("compiler/arguments.jl")
include("compiler/execution.jl")
include("compiler/exceptions.jl")
include("compiler/reflection.jl")
Expand Down
Loading
Loading