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
2 changes: 2 additions & 0 deletions docs/src/extras/pocl_debugging.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
The `CPU` backend of KernelAbstractions.jl is implemented on top of
[PoCL](https://portablecl.org/) (`POCLBackend`). Kernels are compiled to SPIR-V
and then handed to PoCL, which JIT-compiles them for the host CPU using LLVM.
[`functional(CPU())`](@ref KernelAbstractions.functional) reports whether the selected PoCL device
accepts SPIR-V programs and supports the host kernels used by this backend.
When a kernel fails to compile — or compiles but misbehaves — it can be useful
to see what PoCL itself is doing.

Expand Down
4 changes: 2 additions & 2 deletions src/pocl/backend.jl
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ function KI.versioninfo(io::IO, ::POCLBackend)
if in("cl_khr_fp64", device.extensions)
push!(tags, "fp64")
end
if in("cl_khr_il_program", device.extensions)
if POCL.supports_spirv(device)
push!(tags, "il")
end
## render
Expand Down Expand Up @@ -164,7 +164,7 @@ function KI.copyto!(backend::POCLBackend, A, B)
return A
end

KI.functional(::POCLBackend) = true
KI.functional(::POCLBackend) = POCL.cached_session() isa POCL.Session
KA.pagelock!(::POCLBackend, x) = nothing
# its work-items are iterations of a loop, which is faster than dividing for any group size
KA.fold_threshold(::POCLBackend) = 1
Expand Down
6 changes: 1 addition & 5 deletions src/pocl/compiler/compilation.jl
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,7 @@ function link_kernel(
@nospecialize(job::CompilerJob), obj::Vector{UInt8}, entry::String,
exception_sites::Vector{GPUCompiler.ExceptionSite}
)
prog = if "cl_khr_il_program" in device().extensions
cl.Program(obj, context())
else
error("Your device does not support SPIR-V, which is currently required for native execution.")
end
prog = cl.Program(obj, context())
cl.build!(prog)
kernel = cl.Kernel(prog, entry)
# cap tuned work-groups to avoid the queue fallback for excessive stack use; fitting to
Expand Down
24 changes: 18 additions & 6 deletions src/pocl/nanoOpenCL.jl
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,10 @@ end
)::cl_int
end

@checked function clReleaseDevice(device)
@gcsafe_ccall libopencl.POclReleaseDevice(device::cl_device_id)::cl_int
end

@checked function clGetDeviceInfo(
device, param_name, param_value_size, param_value,
param_value_size_ret
Expand Down Expand Up @@ -653,7 +657,7 @@ end

# `cl_pocl_host_kernel` runs work-groups on the calling thread (PoCL's
# `include/CL/cl_ext_pocl.h`). all supported pocl_standalone_jll builds provide it;
# `Session()` rejects devices without it.
# The CPU back-end requires this extension when initializing its session.

const cl_host_kernel_pocl = Ptr{Cvoid}

Expand Down Expand Up @@ -959,12 +963,22 @@ function sub_device(d::Device, compute_units::Integer)
return Device(sub[])
end

function with_sub_device(f, d::Device, compute_units::Integer)
device = sub_device(d, compute_units)
try
return f(device)
finally
clReleaseDevice(device)
end
end

@inline function Base.getproperty(d::Device, s::Symbol)
# simple string properties
version_re = r"OpenCL (?<major>\d+)\.(?<minor>\d+)(?<vendor>.+)"
@inline function get_string(prop)
sz = Ref{Csize_t}()
clGetDeviceInfo(d, prop, 0, C_NULL, sz)
iszero(sz[]) && return ""
chars = Vector{Cchar}(undef, sz[])
clGetDeviceInfo(d, prop, sz[], chars, C_NULL)
return GC.@preserve chars unsafe_string(pointer(chars))
Expand All @@ -989,6 +1003,8 @@ end
return get_string(CL_DRIVER_VERSION)
elseif s === :name
return get_string(CL_DEVICE_NAME)
elseif s === :il_version
return get_string(CL_DEVICE_IL_VERSION)
end

# scalar values
Expand Down Expand Up @@ -1032,11 +1048,7 @@ end
end

# boolean properties
@inline function get_bool(prop)
bool = Ref{cl_bool}()
clGetDeviceInfo(d, prop, sizeof(cl_bool), bool, C_NULL)
return bool[] == CL_TRUE
end
@inline get_bool(prop) = isone(get_scalar(prop, cl_uint))
if s === :has_image_support
return get_bool(CL_DEVICE_IMAGE_SUPPORT)
elseif s === :has_local_mem
Expand Down
53 changes: 39 additions & 14 deletions src/pocl/pocl.jl
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,39 @@ function default_sub_group_size(device::cl.Device)
return isempty(common) ? nothing : first(common)
end

function Session()
supports_spirv(device::cl.Device) = any(startswith("SPIR-V_"), split(device.il_version))

function try_init_session()
cl.pocl_standalone_jll.is_available() ||
error("The CPU back-end needs PoCL, which is not available for $(Sys.MACHINE)")
idx = findfirst(p -> p.vendor == "The pocl project", cl.platforms())
idx === nothing && error("POCL not available")
platform = cl.platforms()[idx]
return ErrorException("The CPU back-end needs PoCL, which is not available for $(Sys.MACHINE)")
platforms = cl.platforms()
idx = findfirst(p -> p.vendor == "The pocl project", platforms)
idx === nothing && return ErrorException("POCL not available")
platform = platforms[idx]
device = cl.default_device(platform)
device === nothing && return ErrorException("PoCL has no default device")
device.available || return cl.CLError(cl.CL_DEVICE_NOT_AVAILABLE)
# PoCL's thread pool can only be sized with environment variables, so use a sub-device
# with the requested number of compute units. its other threads stay asleep.
threads = cl.cpu_threads()
if threads !== nothing && threads < device.max_compute_units && device.max_sub_devices > 0
device = cl.sub_device(device, threads)
return cl.with_sub_device(device, threads) do sub
try_device_session(platform, sub)
end
end
return try_device_session(platform, device)
end

function try_device_session(platform, device)
device.available || return cl.CLError(cl.CL_DEVICE_NOT_AVAILABLE)
extensions = device.extensions
"cl_pocl_host_kernel" in extensions ||
return ErrorException("The CPU back-end needs a PoCL build with the cl_pocl_host_kernel extension")
supports_spirv(device) ||
return ErrorException("Your device does not support SPIR-V, which is currently required for native execution.")
context = cl.Context(device)

sizes = device.max_work_item_size
extensions = device.extensions
sub_group_size = default_sub_group_size(device)
limits = (;
max_work_group_size = Int(device.max_work_group_size),
Expand All @@ -95,9 +111,6 @@ function Session()
fp64 = "cl_khr_fp64" in extensions,
)

"cl_pocl_host_kernel" in extensions ||
error("The CPU back-end needs a PoCL build with the cl_pocl_host_kernel extension")

rate = ticks_per_ns()
# 50 µs, which is long compared to the cost of letting other tasks run
host_kernel_long_ticks = round(UInt64, 50_000 * rate)
Expand All @@ -114,12 +127,12 @@ end

# created on first use, so that loading the package doesn't initialize PoCL
mutable struct SessionCache
Base.@atomic session::Union{Nothing, Session}
Base.@atomic session::Union{Nothing, Session, ErrorException}
const lock::ReentrantLock
end
const session_cache = SessionCache(nothing, ReentrantLock())

@inline function session()
@inline function cached_session()
s = Base.@atomic :acquire session_cache.session
s === nothing || return s
return init_session()
Expand All @@ -128,11 +141,23 @@ end
return @lock session_cache.lock begin
s = Base.@atomic :acquire session_cache.session
if s === nothing
s = Session()
s = try
try_init_session()
catch err
err isa cl.CLError && err.code == cl.CL_DEVICE_NOT_AVAILABLE || rethrow()
err
end
s isa cl.CLError && return s
Base.@atomic :release session_cache.session = s
end
s
end::Session
end::Union{Session, ErrorException}
end

@inline function session()
s = cached_session()
s isa Session && return s
throw(s)
end

platform() = session().platform
Expand Down
77 changes: 77 additions & 0 deletions test/pocl_functional.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using KernelAbstractions
using Test
import KernelAbstractions.POCL: cl

@testset "PoCL functionality" begin
function default_pocl_device()
cl.pocl_standalone_jll.is_available() || return nothing
platforms = cl.platforms()
idx = findfirst(p -> p.vendor == "The pocl project", platforms)
return isnothing(idx) ? nothing : cl.default_device(platforms[idx])
end
function device_accepts_kernels(device)
device.available && "cl_pocl_host_kernel" in device.extensions || return false
size = Ref{Csize_t}()
cl.clGetDeviceInfo(device, cl.CL_DEVICE_IL_VERSION, 0, C_NULL, size)
iszero(size[]) && return false
version = zeros(UInt8, size[])
cl.clGetDeviceInfo(device, cl.CL_DEVICE_IL_VERSION, length(version), version, C_NULL)
return any(startswith("SPIR-V_"), split(chop(String(version); tail = 1)))
end
device = default_pocl_device()
threads = cl.cpu_threads()
expected = if isnothing(device) || !device.available
false
elseif threads !== nothing && threads < device.max_compute_units && device.max_sub_devices > 0
sub = cl.sub_device(device, threads)
try
device_accepts_kernels(sub)
finally
@test ccall((:POclReleaseDevice, cl.libopencl), Cint, (cl.cl_device_id,), sub) == cl.CL_SUCCESS
end
else
device_accepts_kernels(device)
end
@test KernelAbstractions.functional(CPU()) === expected

if device !== nothing && device.available && device.max_sub_devices > 0
function refcount(d)
count = Ref{Cuint}()
cl.clGetDeviceInfo(d, cl.CL_DEVICE_REFERENCE_COUNT, sizeof(Cuint), count, C_NULL)
return count[]
end
for _ in 1:2
context, selected, count = Ref{cl.Context}(), Ref{cl.Device}(), Ref{Cuint}()
@test_throws cl.CLError(cl.CL_DEVICE_NOT_AVAILABLE) cl.with_sub_device(device, 1) do sub
context[] = cl.Context(sub)
selected[] = sub
count[] = refcount(sub)
throw(cl.CLError(cl.CL_DEVICE_NOT_AVAILABLE))
end
@test refcount(selected[]) == count[] - 1
finalize(context[])
end
end

julia = Cmd(filter(arg -> !startswith(arg, "--code-coverage"), Base.julia_cmd().exec))
script = """
using KernelAbstractions, Test
@kernel function fill_one!(a)
a[@index(Global, Linear)] = 1
end
@test !KernelAbstractions.functional(CPU())
@test_throws r"PoCL has no default device|POCL not available|The CPU back-end needs PoCL" fill_one!(CPU())(zeros(Int32, 1); ndrange = 1)
import KernelAbstractions.POCL
POCL.reset_session_state!()
const device_error = Ref(POCL.cl.CL_DEVICE_NOT_AVAILABLE)
@eval POCL try_init_session() = throw(cl.CLError(Main.device_error[]))
@test !KernelAbstractions.functional(CPU())
@test_throws POCL.cl.CLError(device_error[]) fill_one!(CPU())(zeros(Int32, 1); ndrange = 1)
device_error[] = POCL.cl.CL_DEVICE_NOT_FOUND
@test_throws POCL.cl.CLError(device_error[]) KernelAbstractions.functional(CPU())
"""
cmd = `$julia --startup-file=no --project=$(Base.active_project()) -e $script`
child = addenv(cmd, "POCL_DEVICES" => "nonexistent")
@test success(pipeline(child; stdout, stderr))
end
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ include("linenumbers.jl")
include("coverage.jl")
include("testsuite.jl")
include("codegen.jl")
include("pocl_functional.jl")

@testset "Quality assurance" begin
quality_assurance_testsuite()
Expand Down
Loading