Skip to content
Draft
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
4 changes: 4 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ oneAPI_Level_Zero_Headers_jll = "f4bc562b-d309-54f8-9efb-476e56f0410d"
oneAPI_Level_Zero_Loader_jll = "13eca655-d68d-5b81-8367-6d99d727ab01"
oneAPI_Support_jll = "b049733a-a71d-5ed3-8eba-7d323ac00b36"

[sources]
KernelAbstractions = {url = "https://github.com/JuliaGPU/KernelAbstractions.jl", rev = "ccr-c54f0813-yayzye"}
KernelInterface = {url = "https://github.com/JuliaGPU/KernelAbstractions.jl", rev = "ccr-c54f0813-yayzye", subdir = "lib/KernelInterface"}

[compat]
AbstractFFTs = "1.5.0"
Adapt = "4"
Expand Down
32 changes: 30 additions & 2 deletions lib/level-zero/module.jl
Original file line number Diff line number Diff line change
Expand Up @@ -91,16 +91,24 @@ mutable struct ZeKernel
# MAX_GROUP_SIZE extension. Read on every KernelInterface launch.
max_group_size::Int

# cached localMemSize, the bytes of local memory the kernel allocates statically, seeded
# by `properties`; -1 while unqueried.
local_mem_size::Int

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

# whether the last two arguments are the kernel's dynamic local memory and its size,
# which launches have to set (see `oneAPI.set_dynamic_localmemory!`)
dynamic_localmemory::Bool

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, ExceptionSite[])
obj = new(mod, handle_ref[], ReentrantLock(), -1, -1, -1, ExceptionSite[], false)

finalizer(obj) do obj
zeKernelDestroy(obj)
Expand Down Expand Up @@ -206,7 +214,7 @@ end

## arguments

export arguments
export arguments, set_local_memory_argument!

struct ZeKernelArgumentList
kernel::ZeKernel
Expand All @@ -229,6 +237,19 @@ end
zeKernelSetArgumentValue(kernel, index-1, size, ptr)
end

"""
set_local_memory_argument!(kernel::ZeKernel, index::Integer, bytes::Integer)

Size the local memory that argument `index` of `kernel` points to, a pointer to memory that
is shared by the work-items of a work-group. Such an argument doesn't take a value: its size
is the number of bytes of local memory that the driver allocates for every work-group of
the launches that follow (`zeKernelSetArgumentValue`: "If argument is SLM (size), then SLM
size in bytes for this resource is provided as argument size and argument value is null").
"""
function set_local_memory_argument!(kernel::ZeKernel, index::Integer, bytes::Integer)
zeKernelSetArgumentValue(kernel, index-1, bytes, C_NULL)
end


## attributes

Expand Down Expand Up @@ -287,6 +308,7 @@ function properties(kernel::ZeKernel)

props = props_ref[]
kernel.spill = Int(props.spillMemSize)
kernel.local_mem_size = Int(props.localMemSize)
kernel.max_group_size = max_group_size_props_ref === nothing ? 0 :
Int(max_group_size_props_ref[].maxGroupSize)
return (
Expand Down Expand Up @@ -316,6 +338,12 @@ function spill_mem_size(kernel::ZeKernel)
return s >= 0 ? s : Int(properties(kernel).spillMemSize)
end

# Cached access to the bytes of local memory a kernel allocates statically.
function local_mem_size(kernel::ZeKernel)
s = kernel.local_mem_size
return s >= 0 ? s : Int(properties(kernel).localMemSize)
end

# Cached access to a kernel's maxGroupSize, `missing` without the MAX_GROUP_SIZE extension.
function max_group_size(kernel::ZeKernel)
s = kernel.max_group_size
Expand Down
44 changes: 37 additions & 7 deletions src/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ 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` and `exception_sites` after codegen, and `kernels` after the
session-local link onto a Level Zero module. The first three are session-portable (cached
`image` (SPIR-V bytes), `entry`, `dynamic_localmemory` and `exception_sites` after codegen,
and `kernels` after the session-local link onto a Level Zero module. The former 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.
Expand All @@ -28,9 +28,10 @@ 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}
dynamic_localmemory::Bool # has the arguments for it
exception_sites::Vector{GPUCompiler.ExceptionSite}
kernels::Vector{Tuple{ZeContext, ZeDevice, ZeKernel}} # session-local; linear-scanned
oneAPIResults() = new(nothing, nothing, GPUCompiler.ExceptionSite[],
oneAPIResults() = new(nothing, nothing, false, GPUCompiler.ExceptionSite[],
Tuple{ZeContext, ZeDevice, ZeKernel}[])
end

Expand Down Expand Up @@ -88,6 +89,33 @@ function GPUCompiler.finish_module!(job::oneAPICompilerJob, mod::LLVM.Module,
return entry
end

function GPUCompiler.finish_linked_module!(job::oneAPICompilerJob, mod::LLVM.Module)
for f in GPUCompiler.kernels(mod)
add_dynamic_localmemory!(job, mod, f)
end
return
end

const dynamic_localmemory_attr = "julia.oneapi.dynamic_localmemory"

# Give a kernel that uses dynamic local memory the arguments for it: a pointer to the local
# memory, followed by the size the launch asked for. Launches have to set these, so note
# that the kernel has them. They are added one by one, and both whenever the kernel uses
# either, so that they are always the last two arguments in that order.
function add_dynamic_localmemory!(job::oneAPICompilerJob, mod::LLVM.Module, f::LLVM.Function)
args = (
(; name = "dynamic_localmemory", typ = LLVMPtr{UInt8, AS.Workgroup}),
(; name = "dynamic_localmemory_size", typ = Int),
)
any(arg -> haskey(mod.functions, "julia.oneapi.$(arg.name)"), args) || return f
for arg in args
additional_arg_intr(mod, convert(LLVMType, arg.typ), arg.name)
f = GPUCompiler.add_input_arguments!(job, mod, f, Dict("julia.oneapi.$(arg.name)" => arg))
end
push!(f.function_attributes, StringAttribute(dynamic_localmemory_attr, ""))
return f
end

function GPUCompiler.finish_ir!(job::oneAPICompilerJob, mod::LLVM.Module,
entry::LLVM.Function)
# GPUCompiler adds the kernel state parameter during optimization. Initialize the heap
Expand Down Expand Up @@ -262,21 +290,23 @@ end
CompilerConfig(target, params; kernel, name, always_inline, debug_level)
end

# 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`.
# run inference + LLVM codegen + SPIR-V emission. returns `(image, entry, dynamic_localmemory,
# exception_sites)`, all session-portable so they survive precompilation when stored on a cached `CodeInstance`.
function compile_to_obj(@nospecialize(job::CompilerJob))
return GPUCompiler.compile(:obj, job) do asm, meta
(image = asm, entry = meta.entry.name, meta.exception_sites)
dynamic_localmemory = haskey(meta.entry.function_attributes, dynamic_localmemory_attr)
(image = asm, entry = meta.entry.name, dynamic_localmemory, meta.exception_sites)
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,
exception_sites::Vector{GPUCompiler.ExceptionSite},
ctx::ZeContext, dev::ZeDevice)
ctx::ZeContext, dev::ZeDevice, dynamic_localmemory::Bool=false)
mod = ZeModule(ctx, dev, image)
kernel = kernels(mod)[entry]
kernel.exception_sites = exception_sites
kernel.dynamic_localmemory = dynamic_localmemory

# 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
34 changes: 31 additions & 3 deletions src/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export @oneapi, zefunction, kernel_convert

const MACRO_KWARGS = [:launch]
const COMPILER_KWARGS = [:kernel, :name, :always_inline, :atomics, :sub_group_size, :debug_level]
const LAUNCH_KWARGS = [:groups, :items, :queue]
const LAUNCH_KWARGS = [:groups, :items, :queue, :localmem]

"""
@oneapi [kwargs...] kernel(args...)
Expand Down Expand Up @@ -45,6 +45,8 @@ launches the kernel on the GPU.
- `queue=global_stream(...)`: Submission target — the task's `oneStream` by default. An
explicit `ZeCommandQueue` is also accepted and submits each launch as a command list;
exceptions thrown by such launches are not reported.
- `localmem::Int=0`: Size in bytes of the block of dynamic local memory that every workgroup
gets, for kernels that use `KernelInterface.dynamic_localmemory`.

# Examples

Expand Down Expand Up @@ -370,7 +372,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, res.dynamic_localmemory)
# 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 @@ -400,24 +402,50 @@ end
res = @something res GPUCompiler.cached_results(oneAPIResults, job)
res.image = compiled.image
res.entry = compiled.entry
res.dynamic_localmemory = compiled.dynamic_localmemory
res.exception_sites = compiled.exception_sites
end
return res
end

@inline function onecall(kernel::ZeKernel, tt, args::Tuple; groups::ZeDim=1, items::ZeDim=1,
queue::Union{oneStream, ZeCommandQueue}=global_stream(context(), device()),
roots=nothing)
roots=nothing, localmem::Int=0)
Base.@lock kernel begin
# unrolled, as iterating a heterogeneous tuple would dispatch at run time
ntuple(Val(length(args))) do i
oneL0.arguments(kernel)[i] = args[i]
return
end
# (a kernel that doesn't use dynamic local memory ignores what the launch asks for)
kernel.dynamic_localmemory && set_dynamic_localmemory!(kernel, length(args), localmem)
launch_kernel(kernel, groups, items, queue, roots)
end
end

# Size the dynamic local memory of a kernel that uses it, for a launch asking for `localmem`
# bytes: the arguments for it follow the `nargs` other ones (see `add_dynamic_localmemory!`).
# Every launch has to, also one that asks for none. The allocation is larger than what was
# asked for, so that the kernel can align the block (see `dynamic_localmemory`), which also
# keeps it from being empty.
@noinline function set_dynamic_localmemory!(kernel::ZeKernel, nargs::Int, localmem::Int)
localmem >= 0 ||
throw(ArgumentError("Dynamic local memory must not be negative, got $localmem bytes"))
# (queried before the argument is set, which the driver may count as well)
oneL0.local_mem_size(kernel)
set_local_memory_argument!(kernel, nargs + 1, localmem + DYNAMIC_LOCALMEMORY_ALIGNMENT)
oneL0.arguments(kernel)[nargs + 2] = localmem
return
end

# The most dynamic local memory a launch of `kernel` can ask for: the local memory of a
# work-group, less what the kernel allocates statically and what aligning the block takes.
function max_dynamic_localmemory(kernel::ZeKernel,
max_local_memory::Int=oneL0.compute_properties(kernel.mod.device).maxSharedLocalMemory)
available = max_local_memory - oneL0.local_mem_size(kernel) - DYNAMIC_LOCALMEMORY_ALIGNMENT
return max(available, 0)
end

# kept out of `onecall`, which is compiled for every kernel signature, as none of this
# depends on it
@noinline function launch_kernel(kernel::ZeKernel, groups::ZeDim, items::ZeDim,
Expand Down
44 changes: 44 additions & 0 deletions src/device/runtime.jl
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,50 @@ KernelState(exception_report::UInt64=UInt64(0), exception_claim::UInt64=UInt64(0
@device_function @inline @generated kernel_state() = GPUCompiler.kernel_state_value(KernelState)


## additional kernel arguments

# Intrinsics that `finish_linked_module!` turns into additional arguments of the kernel,
# which are passed on to the functions that use them.

function additional_arg_intr(mod::LLVM.Module, T::LLVMType, name)
return get!(mod.functions, "julia.oneapi.$name") do
intr = LLVM.Function(mod, "julia.oneapi.$name", LLVM.FunctionType(T))
intr.memory_effects = MemoryEffects(:none)
intr
end
end

@llvmgenerated builder function additional_arg_value(::Type{T}, ::Val{name})::T where {T, name}
intr = additional_arg_intr(current_module(builder), convert(LLVMType, T), name)
call!(builder, intr.function_type, intr, Value[], String(name))
end


## dynamic local memory

# The block of local memory whose size is chosen at launch (see `KI.dynamic_localmemory`) is
# a kernel argument that points to local memory, which Level Zero allocates when the launch
# sets the size of the argument. A second argument has the size the launch asked for. Only
# kernels that use the block have these arguments, see `add_dynamic_localmemory!`.

# what the block is aligned to
const DYNAMIC_LOCALMEMORY_ALIGNMENT = 16

# Nothing specifies how the driver aligns the memory of a local memory argument, so launches
# allocate `DYNAMIC_LOCALMEMORY_ALIGNMENT` bytes more than they were asked for, and the
# block starts at the first aligned address.
@device_function @inline function dynamic_localmemory()
ptr = additional_arg_value(LLVMPtr{UInt8, AS.Workgroup}, Val(:dynamic_localmemory))
mask = (DYNAMIC_LOCALMEMORY_ALIGNMENT - 1) % UInt
padding = (-reinterpret(UInt, ptr)) & mask
return ptr + (padding % Int)
end

# the bytes of dynamic local memory the launch asked for
@device_function @inline dynamic_localmemory_size() =
additional_arg_value(Int, Val(:dynamic_localmemory_size))


## dynamic memory allocation

# Julia's boxed objects use address-space-0 pointers, which SPIR-V maps to private
Expand Down
29 changes: 26 additions & 3 deletions src/oneAPIKernels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ KI.synchronize(::oneAPIBackend) = oneAPI.oneL0.synchronize()
KI.supports_float64(::oneAPIBackend) = device_limits().supports_float64
KI.supports_unified(::oneAPIBackend) = true
KI.supports_atomics(::oneAPIBackend) = true
KI.supports_dynamic_localmemory(::oneAPIBackend) = true
KI.supports_subgroups(::oneAPIBackend) = device_limits().sub_group_size > 0
# Intel's GPU compiler forms sub-groups from consecutive work-items (which the KernelInterface
# testsuite checks), and they execute independently
Expand Down Expand Up @@ -137,7 +138,8 @@ function KI.launch(obj::KI.Kernel{oneAPIBackend}, groups::Dims{3}, items::Dims{3
throw(ArgumentError("KernelInterface kernels take `numgroups`, `workgroupsize` or `ndrange`, not `items` or `groups`"))
end
# kernels are compiled for a context and device, and by default launched on the task's
# stream for the active ones
# stream for the active ones. `localmem`, which only launches asking for dynamic local
# memory pass, is one of the launch options (see `oneAPI.set_dynamic_localmemory!`).
(; f, host) = obj.kern
check_target(host.fun.mod, get(kwargs, :queue, nothing))
oneAPI.launch_managed(host, f, args; items, groups, kwargs...)
Expand All @@ -164,9 +166,17 @@ function KI.max_work_group_size(kernel::KI.Kernel{oneAPIBackend})::Int
max_group_size === missing || return max_group_size
return device_limits(fun.mod.device).max_work_group_size
end

# what the device has, less the kernel's static local memory
KI.max_dynamic_localmemory(kernel::KI.Kernel{oneAPIBackend})::Int =
let fun = kernel.kern.host.fun
oneAPI.max_dynamic_localmemory(fun, device_limits(fun.mod.device).max_local_memory)
end

# (the amount of local memory doesn't limit the work-group size)
function KI.launch_configuration(
kernel::KI.Kernel{oneAPIBackend}; nitems::Union{Integer, Nothing} = nothing,
max_work_group_size::Integer = typemax(Int)
max_work_group_size::Integer = typemax(Int), localmem = nothing
)
items = min(oneAPI.launch_configuration(kernel.kern.host), max_work_group_size)
if kernel.backend.prefer_blocks && nitems !== nothing
Expand All @@ -184,6 +194,7 @@ end
const DeviceLimits = @NamedTuple{
max_work_group_size::Int, max_work_group_dims::NTuple{3, Int}, max_num_groups::NTuple{3, Int},
sub_group_size::Int, supports_float16::Bool, supports_float64::Bool,
max_local_memory::Int,
}
const DeviceLimitsDict = Base.ImmutableDict{oneAPI.oneL0.ZeDevice, DeviceLimits}
mutable struct DeviceLimitsCache
Expand Down Expand Up @@ -216,7 +227,8 @@ end
max_num_groups = (props.maxGroupCountX, props.maxGroupCountY, props.maxGroupCountZ),
sub_group_size,
supports_float16 = module_props.flags & oneAPI.oneL0.ZE_DEVICE_MODULE_FLAG_FP16 != 0,
supports_float64 = module_props.flags & oneAPI.oneL0.ZE_DEVICE_MODULE_FLAG_FP64 != 0)::DeviceLimits
supports_float64 = module_props.flags & oneAPI.oneL0.ZE_DEVICE_MODULE_FLAG_FP64 != 0,
max_local_memory = props.maxSharedLocalMemory)::DeviceLimits
@atomic :release device_limits_cache.limits = DeviceLimitsDict(cache, dev, limits)
return limits
end
Expand Down Expand Up @@ -284,6 +296,17 @@ end
oneDeviceArray(Dims, ptr)
end

# every array is in the one block that the launch sized (see `oneAPI.dynamic_localmemory`)
@device_override Base.@propagate_inbounds function KI.dynamic_localmemory(
::Type{T}, dims::Dims{N}, offset::Int
) where {T, N}
KI.check_dynamic_localmemory(T, dims, offset)
ptr = reinterpret(Core.LLVMPtr{T, oneAPI.AS.Workgroup}, oneAPI.dynamic_localmemory() + offset)
return oneDeviceArray{T, N, oneAPI.AS.Workgroup}(dims, ptr)
end

@device_override @inline KI.dynamic_localmemory_size() = oneAPI.dynamic_localmemory_size()


## Synchronization and Printing

Expand Down
2 changes: 2 additions & 0 deletions test/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ oneAPI = "8f75cd03-7ff8-4ecb-9b8f-daf728133b1b"
oneAPI_Support_jll = "b049733a-a71d-5ed3-8eba-7d323ac00b36"

[sources]
KernelAbstractions = {url = "https://github.com/JuliaGPU/KernelAbstractions.jl", rev = "ccr-c54f0813-yayzye"}
KernelInterface = {url = "https://github.com/JuliaGPU/KernelAbstractions.jl", rev = "ccr-c54f0813-yayzye", subdir = "lib/KernelInterface"}
oneAPI = {path = ".."}

[compat]
Expand Down
Loading
Loading