diff --git a/docs/src/kernels.md b/docs/src/kernels.md index 9599b0ce..242e5997 100644 --- a/docs/src/kernels.md +++ b/docs/src/kernels.md @@ -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 diff --git a/src/compiler/arguments.jl b/src/compiler/arguments.jl new file mode 100644 index 00000000..ee18c81f --- /dev/null +++ b/src/compiler/arguments.jl @@ -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 diff --git a/src/compiler/compilation.jl b/src/compiler/compilation.jl index f2853ad0..e5871a2a 100644 --- a/src/compiler/compilation.jl +++ b/src/compiler/compilation.jl @@ -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 diff --git a/src/compiler/execution.jl b/src/compiler/execution.jl index 50f86caf..e75e2737 100644 --- a/src/compiler/execution.jl +++ b/src/compiler/execution.jl @@ -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. # @@ -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 @@ -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() @@ -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. @@ -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...) diff --git a/src/oneAPI.jl b/src/oneAPI.jl index 617cc5c1..f7e32aef 100644 --- a/src/oneAPI.jl +++ b/src/oneAPI.jl @@ -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") diff --git a/test/execution.jl b/test/execution.jl index cf829e86..67004045 100644 --- a/test/execution.jl +++ b/test/execution.jl @@ -790,6 +790,140 @@ end ############################################################################################ +# Arguments whose total size exceeds the device's `maxArgumentsSize` (2048 bytes on current +# Intel GPUs, which IGC refuses to build kernels beyond) are passed through memory (#497). +# Every element is read back, so that a truncated or garbled argument is detected. +function large_arg_copy!(out, t) + i = get_global_id() + if i <= length(t) + @inbounds out[i] = t[i] + end + return +end +function large_arg_add!(out, a, b) + i = get_global_id() + if i <= length(out) + @inbounds out[i] = a[i] + b[i] + end + return +end +function large_arg_column!(out, t, j) + i = get_global_id() + if i <= length(t) + @inbounds out[i, j] = t[i] + end + return +end +struct LargeArgWithArray{A} + data::NTuple{1024, Float32} + out::A +end +Adapt.@adapt_structure LargeArgWithArray +function large_arg_through_struct!(s) + i = get_global_id() + if i <= length(s.data) + @inbounds s.out[i] = 2 * s.data[i] + end + return +end +large_arg_many(args...) = return +large_arg_first(t) = t[1] +function large_arg_sum!(out, t) + s = 0 + for i in 1:length(t) + s += t[i] + end + out[1] = s + return +end + +@testset "large arguments" begin + limit = oneL0.module_properties(device()).maxArgumentsSize + launch(f, n, args...) = @oneapi items=min(n, 256) groups=cld(n, 256) f(args...) + + # small arguments are passed by value + out = oneArray(zeros(Float32, 4)) + k = @oneapi launch=false large_arg_copy!(out, (1f0, 2f0, 3f0, 4f0)) + @test k.spill === nothing + + # around the limit, after the hidden kernel state and the output vector. (arguments + # that fit can still be spilled, if IGC fails to fit them in registers.) + vec_size = sizeof(typeof(oneAPI.kernel_convert(out))) + fitting = (limit - sizeof(oneAPI.KernelState) - vec_size) ÷ sizeof(Float32) + for N in (fitting, fitting + 1, 1024, 4096, 8192) + t = ntuple(i -> Float32(i) + 0.5f0, N) + out = oneArray(zeros(Float32, N)) + k = @oneapi launch=false large_arg_copy!(out, t) + N > fitting && @test k.spill !== nothing + launch(large_arg_copy!, N, out, t) + @test Array(out) == collect(t) + end + + # several large arguments, only spilling as many as needed + a = ntuple(i -> Float32(i), 1024) + b = ntuple(i -> Float32(-2i), 1024) + out = oneArray(zeros(Float32, 1024)) + k = @oneapi launch=false large_arg_add!(out, a, b) + @test k.spill.mask == [false, false, true, true] + launch(large_arg_add!, 1024, out, a, b) + @test Array(out) == collect(a) .+ collect(b) + c = ntuple(i -> Float32(3i), 360) + out = oneArray(zeros(Float32, 360)) + k = @oneapi launch=false large_arg_add!(out, a, c) + @test k.spill.mask == [false, false, true, false] + launch(large_arg_add!, 360, out, a, c) + @test Array(out) == collect(a)[1:360] .+ collect(c) + + # a large struct holding an array that the kernel writes to + t = ntuple(i -> Float32(i) / 4, 1024) + out = oneArray(zeros(Float32, 1024)) + launch(large_arg_through_struct!, 1024, LargeArgWithArray(t, out)) + @test Array(out) == 2 .* collect(t) + + # a closure capturing a large value + let captured = ntuple(i -> Float32(7i), 2048) + out = oneArray(zeros(Float32, 2048)) + f = function (o) + i = get_global_id() + @inbounds o[i] = captured[i] + return + end + @oneapi items=256 groups=8 f(out) + @test Array(out) == collect(captured) + end + + # arguments below the limit that IGC fails to fit in registers ("Kernel inputs exceed + # total register size" on PVC) are passed through memory when the build fails + t = ntuple(i -> UInt8(i % 7), 1976) + out = oneArray(zeros(Int, 1)) + @oneapi large_arg_sum!(out, t) + @test Array(out)[] == sum(Int, t) + + # launches with different values, and the same ones again, without waiting for the + # previous launches: each must see its own value. more values than the device copies + # that are cached, so that copies are evicted while launches may still use them. + n, m = 1024, oneAPI.MAX_ARGUMENT_BUFFERS + 8 + out = oneArray(zeros(Float32, n, 2m)) + vals = [ntuple(i -> Float32(i + 2048 * j), n) for j in 1:m] + for j in 1:m + launch(large_arg_column!, n, out, vals[j], j) + end + for j in m:-1:1 # the most recent first, so that these hit the cache + launch(large_arg_column!, n, out, vals[j], m + j) + end + expected = reduce(hcat, collect.(vals)) + @test Array(out) == hcat(expected, expected) + + # arguments that don't fit, also when passing the large ones through memory + nargs = cld(limit, sizeof(Int)) + @test_throws "exceeds the device's limit" @oneapi launch=false large_arg_many(ntuple(identity, nargs)...) + + # kernels passing arguments through memory are validated like any other + @test_throws oneAPI.GPUCompiler.KernelError @oneapi launch=false large_arg_first(ntuple(Float32, 1024)) +end + +############################################################################################ + # A chain of N live accumulators forces the register allocator to spill once N exceeds # the register file (256 spills on both PVC and DG2); the reversed index in the update # keeps every element live across the chain, and everything is unrolled through Val so diff --git a/test/kernelabstractions.jl b/test/kernelabstractions.jl index 72640048..b6044006 100644 --- a/test/kernelabstractions.jl +++ b/test/kernelabstractions.jl @@ -75,3 +75,19 @@ end KI.@launch oneAPIBackend(; prefer_blocks=true) ndrange=length(A) ki_store_index!(A) @test Array(A) == 1:1024 end + +KA.@kernel function copy_large_arg!(out, t) + i = KA.@index(Global, Linear) + @inbounds out[i] = t[i] +end + +@testset "large arguments" begin + # passed through memory when they exceed the device's limit (#497) + backend = oneAPIBackend() + for N in (1024, 4096) + t = ntuple(i -> Float32(i) - 0.25f0, N) + out = oneAPI.zeros(Float32, N) + copy_large_arg!(backend, 256)(out, t; ndrange=N) + @test Array(out) == collect(t) + end +end