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
114 changes: 114 additions & 0 deletions src/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,120 @@ function compile_to_obj(@nospecialize(job::CompilerJob))
end
end

# Whether a SPIR-V module can tell the sub-group width it is compiled for: it uses sub-group
# operations or built-in variables, or synchronizes or communicates at sub-group scope.
# Modules that can't behave the same at any width, which leaves the choice free (see
# `zefunction_link`). Anything that isn't known not to involve sub-groups counts: missing a
# use would let a kernel run at a width it doesn't expect. So every capability has to be one
# that adds no sub-group functionality, and the instructions that the remaining ones allow
# to take a scope have to use a constant one other than `Subgroup`.
function observes_sub_group_width(image::Vector{UInt8})
length(image) % 4 == 0 || return true
words = reinterpret(UInt32, image)
length(words) >= 5 && words[1] == 0x07230203 || return true
constants = Dict{UInt32, UInt32}()
scopes = UInt32[]
i = 6 # after the header
while i <= length(words)
count = Int(words[i] >> 16)
opcode = words[i] & 0xffff
count == 0 && return true
i + count - 1 <= length(words) || return true
operands = @view words[i+1:i+count-1]
n = length(operands)
if opcode == SpvOpCapability
n >= 1 && operands[1] in width_agnostic_capabilities || return true
elseif opcode == SpvOpDecorate
n >= 2 || return true
operands[2] == SpvDecorationBuiltIn &&
(n < 3 || operands[3] in sub_group_builtins) && return true
elseif opcode == SpvOpMemberDecorate
n >= 3 || return true
operands[3] == SpvDecorationBuiltIn &&
(n < 4 || operands[4] in sub_group_builtins) && return true
elseif opcode == SpvOpExecutionMode || opcode == SpvOpExecutionModeId
n >= 2 && !(operands[2] in sub_group_execution_modes) || return true
elseif opcode == SpvOpConstant
n >= 3 || return true
constants[operands[2]] = operands[3]
elseif opcode in sub_group_queries
return true
else
for pos in get(scope_operands, opcode, ())
pos <= n || return true
push!(scopes, operands[pos])
end
end
i += count
end
# a scope that isn't a constant could be anything
return any(scope -> get(constants, scope, SpvScopeSubgroup) == SpvScopeSubgroup, scopes)
end

const SpvOpExecutionMode = 16
const SpvOpCapability = 17
const SpvOpConstant = 43
const SpvOpDecorate = 71
const SpvOpMemberDecorate = 72
const SpvOpExecutionModeId = 331
const SpvDecorationBuiltIn = 11
const SpvScopeSubgroup = 3

# Capabilities that kernels use without sub-groups. `SubgroupDispatch` is the one that the
# required sub-group size itself needs; the instructions and execution modes it adds are
# checked separately.
const width_agnostic_capabilities = (
4, # Addresses
5, # Linkage
6, # Kernel
7, # Vector16
8, # Float16Buffer
9, # Float16
10, # Float64
11, # Int64
12, # Int64Atomics
22, # Int16
38, # GenericPointer
39, # Int8
58, # SubgroupDispatch
5116, # BFloat16TypeKHR
5612, # AtomicFloat32MinMaxEXT
5613, # AtomicFloat64MinMaxEXT
5616, # AtomicFloat16MinMaxEXT
5629, # ExpectAssumeKHR
6033, # AtomicFloat32AddEXT
6034, # AtomicFloat64AddEXT
6095, # AtomicFloat16AddEXT
6115, # BFloat16ConversionINTEL
)

# SubgroupSize, SubgroupMaxSize, NumSubgroups, NumEnqueuedSubgroups, SubgroupId,
# SubgroupLocalInvocationId, and Subgroup{Eq,Ge,Gt,Le,Lt}Mask
const sub_group_builtins = (36, 37, 38, 39, 40, 41, 4416, 4417, 4418, 4419, 4420)

# SubgroupsPerWorkgroup and SubgroupsPerWorkgroupId
const sub_group_execution_modes = (36, 37)

# The instructions that `SubgroupDispatch` allows, and the device-side enqueue ones that it
# implies, which include queries of a kernel's sub-group and preferred work-group sizes
const sub_group_queries = (35, 37, 291:304..., 325, 326)

# The (1-based) operands that are a scope, of the instructions the capabilities above allow
const scope_operands = Dict{UInt32, Tuple{Vararg{Int}}}(
224 => (1, 2), # OpControlBarrier
225 => (1,), # OpMemoryBarrier
227 => (4,), # OpAtomicLoad
228 => (2,), # OpAtomicStore
(op => (4,) for op in 229:242)..., # OpAtomicExchange through OpAtomicXor
259 => (3,), # OpGroupAsyncCopy
260 => (1,), # OpGroupWaitEvents
318 => (4,), # OpAtomicFlagTestAndSet
319 => (2,), # OpAtomicFlagClear
5614 => (4,), # OpAtomicFMinEXT
5615 => (4,), # OpAtomicFMaxEXT
6035 => (4,), # OpAtomicFAddEXT
)

# 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},
Expand Down
80 changes: 55 additions & 25 deletions src/compiler/execution.jl
Original file line number Diff line number Diff line change
Expand Up @@ -349,38 +349,68 @@ end
(l::KernelLinker)() = zefunction_link(methodinstance(l.ft, l.tt); l.kw...)

# 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.
#
# With `narrow_on_spill`, a kernel that spills at its `sub_group_size` is compiled again for a
# sub-group size of 16, unless it can observe its width. Narrower sub-groups need fewer
# registers per hardware thread, which avoids (or reduces) spilling at the cost of
# throughput: a register-blocked matrix multiplication that spills at SIMD32 runs 1.6-5x
# faster at SIMD16 on Xe-LP and Xe-HPG, while kernels that don't spill are faster at the
# wider width (JuliaGPU/oneAPI.jl#772). Without a required size, IGC instead picks SIMD8 for
# such kernels on those GPUs, which is slower, and keeps a spilling SIMD32 on Xe-HPC.
function zefunction_link(source::Core.MethodInstance; narrow_on_spill::Bool=false, kwargs...)
Base.@lock zefunction_lock begin
ctx = context()
dev = device()
config = compiler_config(dev; kwargs...)::oneAPICompilerConfig
job = CompilerJob(source, config)

res = compile_or_lookup(job)::oneAPIResults

# Resolve the ZeKernel for the active context and device. Linear scan over the
# session-local cache; almost always n=1, so this is one `===`/`==` compare.
fun = nothing
@inbounds for (cached_ctx, cached_dev, cached_kernel) in res.kernels
if cached_ctx == ctx && cached_dev == dev
fun = cached_kernel
break
end
end
if fun === nothing
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.
if ccall(:jl_generating_output, Cint, ()) != 1
push!(res.kernels, (ctx, dev, fun))
fun, res = link_job(source, ctx, dev; kwargs...)

sub_group_size = get(kwargs, :sub_group_size, nothing)
if narrow_on_spill && sub_group_size !== nothing && sub_group_size > 16 &&
16 in oneL0.compute_properties(dev).subGroupSizes &&
oneL0.spill_mem_size(fun) > 0 && !observes_sub_group_width(res.image::Vector{UInt8})
narrow, _ = link_job(source, ctx, dev; kwargs..., sub_group_size = 16)
if narrow_kernel_fits(oneL0.max_group_size(fun), oneL0.max_group_size(narrow))
fun = narrow
end
end

return fun::ZeKernel
return fun
end
end

# With a large register file, the driver can limit narrower kernels to smaller work-groups;
# keep the wider one then, so that work-group sizes that worked keep working. Drivers without
# the MAX_GROUP_SIZE extension still enforce such a limit, but don't report it.
narrow_kernel_fits(wide_limit, narrow_limit) =
wide_limit !== missing && narrow_limit !== missing && narrow_limit >= wide_limit

function link_job(source::Core.MethodInstance, ctx::ZeContext, dev::ZeDevice; kwargs...)
config = compiler_config(dev; kwargs...)::oneAPICompilerConfig
job = CompilerJob(source, config)

res = compile_or_lookup(job)::oneAPIResults

# Resolve the ZeKernel for the active context and device. Linear scan over the
# session-local cache; almost always n=1, so this is one `===`/`==` compare.
fun = nothing
@inbounds for (cached_ctx, cached_dev, cached_kernel) in res.kernels
if cached_ctx == ctx && cached_dev == dev
fun = cached_kernel
break
end
end
if fun === nothing
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.
if ccall(:jl_generating_output, Cint, ()) != 1
push!(res.kernels, (ctx, dev, fun))
end
end

return fun::ZeKernel, res
end

# Look up cached compile artifacts for `job`, compiling on miss. Storage is managed
Expand Down
9 changes: 6 additions & 3 deletions src/oneAPIKernels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,15 @@ struct oneAPIKernel{F, H <: oneAPI.HostKernel}
end

function KI.kernel_function(backend::oneAPIBackend, f::F, tt::TT=Tuple{}; name = nothing, kwargs...) where {F,TT}
# compile for the sub-group width that `KI.sub_group_size` promises
# compile for the sub-group width that `KI.sub_group_size` promises. Kernels that can't
# tell the width may get a narrower one, if that avoids spilling (see `zefunction_link`).
sub_group_size = KI.sub_group_size(backend)
if get(kwargs, :sub_group_size, sub_group_size) != sub_group_size
throw(ArgumentError("KernelInterface kernels are compiled for a sub-group size of $sub_group_size, got $(kwargs[:sub_group_size])"))
end
host = if sub_group_size > 0
zefunction(kernel_convert(f), tt; name, backend.always_inline, kwargs..., sub_group_size)
zefunction(kernel_convert(f), tt; name, backend.always_inline, kwargs..., sub_group_size,
narrow_on_spill = true)
else
zefunction(kernel_convert(f), tt; name, backend.always_inline, kwargs...)
end
Expand Down Expand Up @@ -208,7 +210,8 @@ end
module_props = oneAPI.oneL0.module_properties(dev)
# the sub-group width that `kernel_function` compiles for: 32, like a CUDA warp, if
# the device supports it, and 0 if the device has no sub-groups. Only widths of up to
# 64, so that `KI.sub_group_ballot` (a `UInt64` mask) covers every lane.
# 64, so that `KI.sub_group_ballot` (a `UInt64` mask) covers every lane. Kernels that
# can't observe the width may be compiled for a narrower one.
sg_sizes = filter(<=(64), props.subGroupSizes)
sub_group_size = 32 in sg_sizes ? 32 : maximum(sg_sizes; init = 0)
limits = (; max_work_group_size = props.maxTotalGroupSize,
Expand Down
151 changes: 151 additions & 0 deletions test/kernelinterface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,154 @@ end
@testset "versioninfo" begin
@test occursin("oneAPI.jl", sprint(KI.versioninfo, oneAPIBackend()))
end

using oneAPI: SPIRVIntrinsics
using .SPIRVIntrinsics: UnsafeAtomics

# Kernels that use any of these can tell the sub-group width they run at, so they have to be
# compiled for the width that `KI.sub_group_size` promises
const sub_group_ops = [
"get_sub_group_size" => (x, p) -> x + KI.get_sub_group_size(),
"get_max_sub_group_size" => (x, p) -> x + KI.get_max_sub_group_size(),
"get_num_sub_groups" => (x, p) -> x + KI.get_num_sub_groups(),
"get_sub_group_id" => (x, p) -> x + KI.get_sub_group_id(),
"get_sub_group_local_id" => (x, p) -> x + KI.get_sub_group_local_id(),
"sub_group_barrier()" => (x, p) -> (KI.sub_group_barrier(); x),
"sub_group_barrier(width)" => (x, p) -> (KI.sub_group_barrier(8); x),
"shfl" => (x, p) -> KI.shfl(x, 1),
"shfl_down" => (x, p) -> KI.shfl_down(x, 1),
"shfl_up" => (x, p) -> KI.shfl_up(x, 1),
"shfl_xor" => (x, p) -> KI.shfl_xor(x, 1),
"sub_group_any" => (x, p) -> x + KI.sub_group_any(x > UInt32(3)),
"sub_group_all" => (x, p) -> x + KI.sub_group_all(x > UInt32(3)),
"sub_group_ballot" => (x, p) -> x + KI.sub_group_ballot(x > UInt32(3)) % UInt32,
"sub_group_any(width)" => (x, p) -> x + KI.sub_group_any(x > UInt32(3), 8),
"sub_group_ballot(width)" => (x, p) -> x + KI.sub_group_ballot(x > UInt32(3), 8) % UInt32,
"sub_group_reduce(+)" => (x, p) -> KI.sub_group_reduce(+, x),
"sub_group_reduce(max)" => (x, p) -> KI.sub_group_reduce(max, x),
"sub_group_reduce(*)" => (x, p) -> KI.sub_group_reduce(*, x),
"sub_group_reduce(+, width)" => (x, p) -> KI.sub_group_reduce(+, x, 8),
"sub_group_scan(+)" => (x, p) -> KI.sub_group_scan(+, x),
"sub_group_scan(+, width)" => (x, p) -> KI.sub_group_scan(+, x, 8),
"sub_group_exclusive_scan(+)" => (x, p) -> KI.sub_group_exclusive_scan(+, x, UInt32(0)),
"sub-group fence" => (x, p) -> (SPIRVIntrinsics.atomic_work_item_fence(
SPIRVIntrinsics.GLOBAL_MEM_FENCE,
SPIRVIntrinsics.memory_order_acq_rel,
SPIRVIntrinsics.memory_scope_sub_group); x),
"sub-group atomic" => (x, p) -> first(UnsafeAtomics.Internal.llvm_modify!(
p, +, x, Val(:monotonic), Val(:subgroup), Val(false),
Val(4), Val(()))),
]
# while these behave the same at any width
const work_group_ops = [
"arithmetic" => (x, p) -> x * UInt32(3) + UInt32(1),
"work-item indices" => (x, p) -> x + KI.get_local_id().x + KI.get_group_id().x,
"barrier" => (x, p) -> (KI.barrier(); x),
"atomic" => (x, p) -> SPIRVIntrinsics.atomic_add!(p, x),
]

function ki_op_kernel(op, out)
i = KI.get_global_id().x
@inbounds out[i] = op(UInt32(i), pointer(out))
return
end

@testset "sub-group width detection" begin
width = KI.sub_group_size(oneAPIBackend())
DevVec = oneDeviceVector{UInt32, oneAPI.AS.CrossWorkgroup}
function observes(op)
# as compiled for the promised width, which adds the `SubgroupDispatch` capability
kwargs = width > 0 ? (; sub_group_size = width) : (;)
config = oneAPI.compiler_config(device(); kernel = true, kwargs...)
job = oneAPI.CompilerJob(oneAPI.methodinstance(typeof(ki_op_kernel),
Tuple{typeof(op), DevVec}), config)
return oneAPI.observes_sub_group_width(oneAPI.compile_to_obj(job).image)
end
@testset "$name" for (name, op) in sub_group_ops
@test observes(op)
end
@testset "$name" for (name, op) in work_group_ops
@test !observes(op)
end

# anything that can't be parsed counts
spirv(instructions...) = collect(reinterpret(UInt8, UInt32[0x07230203, 0x00010500, 0, 16, 0,
instructions...]))
@test !oneAPI.observes_sub_group_width(spirv(0x00020011, 6)) # OpCapability Kernel
@test oneAPI.observes_sub_group_width(spirv(0x00020011, 18)) # OpCapability Groups
@test oneAPI.observes_sub_group_width(spirv(0x00010011)) # OpCapability without one
@test oneAPI.observes_sub_group_width(spirv(0x00050011, 6)) # truncated instruction
@test oneAPI.observes_sub_group_width(spirv(0x00000011)) # zero word count
@test oneAPI.observes_sub_group_width(spirv(0x00020011, 6)[1:end-1])
@test oneAPI.observes_sub_group_width(UInt8[])
end

@inline spill_step(acc::NTuple{N}, x) where {N} =
ntuple(k -> muladd(acc[k], x, acc[mod1(k + 1, N)]), Val(N))

# keeps `N` values live across the loop, which spills at SIMD32 on Xe-LP and Xe-HPG for N=32
function ki_spill_kernel(out, widths, x, ::Val{N}, ::Val{observe}) where {N, observe}
i = KI.get_global_id().x
acc = ntuple(k -> @inbounds(x[k]) * i, Val(N))
for j in eachindex(x)
acc = spill_step(acc, @inbounds(x[j]))
end
@inbounds out[i] = sum(acc)
if observe
@inbounds widths[i] = KI.get_max_sub_group_size()
end
return
end

@testset "narrower sub-groups for spilling kernels" begin
backend = oneAPIBackend()
width = KI.sub_group_size(backend)
x = oneArray(rand(Float32, 64) ./ 2)
out = oneArray{Float32}(undef, 256)
widths = oneArray{Int}(undef, 256)
simd(kernel::oneAPI.HostKernel) = oneL0.properties(kernel.fun).maxSubgroupSize
simd(kernel::KI.Kernel) = simd(kernel.kern.host)
spill(kernel::oneAPI.HostKernel) = oneL0.spill_mem_size(kernel.fun)
launch(kernel, args...) = kernel(args...; ndrange = length(out))

# the narrower kernel isn't used if it would be limited to smaller work-groups
@test oneAPI.narrow_kernel_fits(1024, 1024)
@test oneAPI.narrow_kernel_fits(512, 1024)
@test !oneAPI.narrow_kernel_fits(1024, 512)
@test !oneAPI.narrow_kernel_fits(missing, 1024)
@test !oneAPI.narrow_kernel_fits(1024, missing)

if width > 16 && 16 in oneL0.compute_properties(device()).subGroupSizes
args = (out, widths, x, Val(32), Val(false))
pinned = @oneapi launch=false sub_group_size=width ki_spill_kernel(args...)
if spill(pinned) > 0
# a kernel that can't tell its width is compiled for 16 when it spills
kernel = KI.@launch backend launch=false ki_spill_kernel(args...)
@test simd(kernel) == 16
launch(kernel, args...)
want = Array(out)
pinned(args...; items = 32, groups = length(out) ÷ 32)
@test Array(out) ≈ want
# which doesn't affect kernels compiled for an explicit width
@test simd(@oneapi launch=false sub_group_size=width ki_spill_kernel(args...)) == width

# a kernel that can tell keeps the promised width, although it spills too
args = (out, widths, x, Val(32), Val(true))
@test spill(@oneapi launch=false sub_group_size=width ki_spill_kernel(args...)) > 0
kernel = KI.@launch backend launch=false ki_spill_kernel(args...)
@test simd(kernel) == width
launch(kernel, args...)
@test all(==(width), Array(widths))
@test Array(out) ≈ want
else
@test_skip "ki_spill_kernel doesn't spill at a sub-group size of $width"
end

# as does a kernel that doesn't spill
args = (out, widths, x, Val(2), Val(false))
@test spill(@oneapi launch=false sub_group_size=width ki_spill_kernel(args...)) == 0
@test simd(KI.@launch backend launch=false ki_spill_kernel(args...)) == width
else
@test_skip "the device has no sub-group size of 16 narrower than $width"
end
end
Loading