diff --git a/docs/src/installation.md b/docs/src/installation.md index 5da810db..fdfc1748 100644 --- a/docs/src/installation.md +++ b/docs/src/installation.md @@ -81,6 +81,10 @@ using Preferences, UUIDs set_preferences!(UUID("8f75cd03-7ff8-4ecb-9b8f-daf728133b1b"), "precompile" => false) ``` +The `direct_submission` preference, which lowers the latency of launching kernels with some +kernel drivers at a cost to other processes using the GPU, is described in the +[Performance Guide](usage/performance.md#Launch-Latency-and-Direct-Submission). + ## Using System Libraries (Advanced) !!! warning diff --git a/docs/src/usage/performance.md b/docs/src/usage/performance.md index ba5e641d..b6a3f4af 100644 --- a/docs/src/usage/performance.md +++ b/docs/src/usage/performance.md @@ -377,6 +377,59 @@ result = result ./ e # Four separate passes over data! ``` +## Launch Latency and Direct Submission + +Launching a small kernel and waiting for it costs more on some systems than others, +because of how the driver hands work to the GPU. By default, every submission is a system +call to the kernel driver. With *direct submission*, the driver instead writes the work +into a ring buffer that the GPU keeps polling. Intel's driver enables direct submission by +itself where the kernel driver supports it: on Linux, with the `xe` kernel driver, or with +Intel's out-of-tree i915 driver. With the upstream `i915` kernel driver, e.g. for an Arc +A-series GPU on most Linux distributions, it stays off, and launching a trivial kernel and +synchronizing takes about 55 µs, often twice that. + +oneAPI.jl can force direct submission on with the `direct_submission` preference, e.g. in +`LocalPreferences.toml`: + +```toml +[oneAPI] +direct_submission = true +``` + +or with Preferences.jl, by oneAPI.jl's UUID: + +```julia +using Preferences, UUIDs +set_preferences!(UUID("8f75cd03-7ff8-4ecb-9b8f-daf728133b1b"), "direct_submission" => true) +``` + +The `ONEAPI_DIRECT_SUBMISSION` environment variable (`1` or `0`) overrides the preference +for a process and the processes it starts, unless they set it differently. A preference +applies to every process that uses the project, worker processes included, so to try it +out, or to enable it for one process only, prefer the environment variable. On an Arc A770 with i915, this brings launching a trivial kernel and +synchronizing down to about 12 µs, without the slow outliers. + +This is only worth it for a process that is limited by launch latency, and that has the GPU +mostly to itself: + +- The GPU's scheduler sees a polling ring buffer as busy, so while a process has one, every + other process using the same GPU gets its work delayed by a time slice (1 ms with i915's + defaults) per such process, each time they take turns. The driver stops polling once the + process has been idle for a while, which it checks every 5 ms by default. Don't + enable it for many processes sharing a GPU, such as parallel test workers. +- With i915, the driver uses a variant meant for kernel drivers without VM_BIND, which Intel + only enables for some integrated GPUs. It has to stop and restart the ring buffer when + memory is allocated or freed, which oneAPI.jl's memory pool mostly avoids. +- It relies on debug settings of the driver (`NEOReadDebugKeys=1` and + `EnableDirectSubmission=1`), which oneAPI.jl sets while it initializes the driver, and + removes again so that child processes don't inherit them. With `NEOReadDebugKeys=1`, the + driver also reads any of its other debug settings from the environment. If either variable + is already set, oneAPI.jl leaves both alone. + +The driver reads those settings when it is loaded, so they can't be changed once oneAPI.jl +has been initialized. If oneAPI.jl warns that the driver was already loaded, set the two +environment variables before starting Julia instead. + ## Common Performance Issues ### Issue 1: Too Many Small Kernels diff --git a/lib/level-zero/oneL0.jl b/lib/level-zero/oneL0.jl index c5a694d9..e83ea5cd 100644 --- a/lib/level-zero/oneL0.jl +++ b/lib/level-zero/oneL0.jl @@ -8,6 +8,8 @@ using Printf using Libdl +import ..Preferences + using GPUCompiler: ExceptionSite if Sys.iswindows() @@ -165,6 +167,42 @@ function parse_env_bool(name::AbstractString, default::Bool) return default end +# Direct submission makes NEO submit work by writing to a ring buffer the GPU polls, instead +# of with a system call. Where the kernel driver lacks VM_BIND (upstream i915, so e.g. DG2 +# with i915), NEO only enables it for OpenVINO, so we offer to force it on through NEO's debug +# keys (see the performance guide). NEO reads those when it is loaded, at the latest by +# `zeInit`, so they have to be set before. +const direct_submission_forced = Ref(false) + +# the driver libraries the Level Zero loader will use +driver_libraries() = filter(!isempty, strip.(split(get(ENV, "ZE_ENABLE_ALT_DRIVERS", ""), ','))) + +# Returns the environment variables it set, for the caller to remove once NEO has read them, +# so that child processes don't inherit them (and the preference decides for them too). +function configure_direct_submission() + # precompilation doesn't need it, and shouldn't depend on the preference + ccall(:jl_generating_output, Cint, ()) == 0 || return String[] + pref = Preferences.load_preference(parentmodule(@__MODULE__), "direct_submission", false) + parse_env_bool("ONEAPI_DIRECT_SUBMISSION", pref) || return String[] + direct_submission_forced[] && return String[] + keys = ["NEOReadDebugKeys", "EnableDirectSubmission"] + # NEO's own settings take precedence + any(key -> haskey(ENV, key), keys) && return String[] + drivers = driver_libraries() + loaded = filter(lib -> Libdl.dlopen(lib, RTLD_NOLOAD; throw_error=false) !== nothing, + drivers) + if !isempty(loaded) + @warn """Direct submission was requested, but the NEO driver has already been loaded, + so it can't be enabled anymore. Set the environment variables + `NEOReadDebugKeys=1` and `EnableDirectSubmission=1` before starting Julia + instead.""" loaded + end + length(loaded) == length(drivers) && return String[] + foreach(key -> ENV[key] = "1", keys) + direct_submission_forced[] = true + return keys +end + function __init__() # precompilation processes only initialize the driver when a workload asks for it (see # `oneAPI.can_precompile`) @@ -176,6 +214,7 @@ end # initialize the driver, setting `functional`. `quiet` doesn't report why it isn't functional. function initialize(; quiet::Bool=false) functional[] = false + forced = String[] # Driver handles are process-local, so nothing keyed on one may survive into another # process through a precompiled image. @@ -211,21 +250,32 @@ function initialize(; quiet::Bool=false) if !haskey(ENV, "ZE_ENABLE_ALT_DRIVERS") ENV["ZE_ENABLE_ALT_DRIVERS"] = NEO_jll.libze_intel_gpu end + + forced = configure_direct_submission() + + # NEO_jll doesn't load NEO, so that it reads the settings above. Load it ourselves + # when the loader is to use it, so that libsycl (loaded later for oneMKL), which + # carries its own Level Zero loader that loads NEO by soname, finds this module + # also when no system NEO is installed. + if driver_libraries() == [NEO_jll.libze_intel_gpu] + Libdl.dlopen(NEO_jll.libze_intel_gpu, RTLD_LAZY | RTLD_DEEPBIND; throw_error=false) + end end - try + initialized = try zeInit(0) + true catch err # Handle the specific case where no oneAPI device is available - if err isa ZeError && err.code == RESULT_ERROR_UNINITIALIZED - functional[] = false - return + if !(err isa ZeError && err.code == RESULT_ERROR_UNINITIALIZED) + # For other errors, still report them as errors + quiet || @error "Failed to initialize oneAPI" exception=(err,catch_backtrace()) end - # For other errors, still report them as errors - quiet || @error "Failed to initialize oneAPI" exception=(err,catch_backtrace()) - functional[] = false - return + false + finally + foreach(key -> delete!(ENV, key), forced) end + initialized || return # Check if there are actually any drivers/devices available try diff --git a/src/oneAPI.jl b/src/oneAPI.jl index 617cc5c1..17581868 100644 --- a/src/oneAPI.jl +++ b/src/oneAPI.jl @@ -15,8 +15,6 @@ import KernelInterface using LLVM, LLVM.IR, LLVM.Build, LLVM.Interop using Core: LLVMPtr -import Libdl - import IntelITT # Load both SPIR-V codegen back-ends: GPUCompiler resolves the tool from the target's @@ -205,19 +203,10 @@ function __init__() # ensure that the OpenCL loader finds the ICD files from our artifacts ENV["OCL_ICD_FILENAMES"] = oneL0.NEO_jll.libigdrcl - # libsycl (loaded later for oneMKL) carries its own bundled Level Zero loader - # that rediscovers the NEO driver by dlopen'ing it by soname rather than - # reusing our JLL-loaded module. dlopen NEO here by full path so it is already - # resident in this process before libsycl loads: a later - # dlopen("libze_intel_gpu.so.1") then resolves to this module by soname without - # needing a search path. Required when no system NEO is installed. - # - # Don't extend LD_LIBRARY_PATH instead: glibc reads it only at startup, and - # child processes (precompile workers, `Pkg.test`) would inherit it. With a - # system NEO in e.g. /usr/lib, that directory then overrides every JLL's - # RUNPATH there (#778). A child that needs NEO loads oneAPI.jl, whose - # __init__ performs this dlopen itself. - Libdl.dlopen(oneL0.NEO_jll.libze_intel_gpu; throw_error = false) + # oneL0's initialization loads NEO itself. Don't extend LD_LIBRARY_PATH for + # child processes either: with a system NEO in e.g. /usr/lib, that directory + # would override every JLL's RUNPATH in precompile workers and `Pkg.test` + # (#778). A child that needs NEO loads oneAPI.jl, which loads NEO itself. end end diff --git a/test/level-zero.jl b/test/level-zero.jl index cceaadb2..3a8d554b 100644 --- a/test/level-zero.jl +++ b/test/level-zero.jl @@ -541,3 +541,48 @@ system_driver = !startswith(NEO_jll.libze_intel_gpu, NEO_jll.artifact_dir) @test success(pipeline(cmd, stdout=stdout, stderr=stderr)) skip=system_driver end + +@testset "direct submission" begin + +# NEO reads the debug keys that force direct submission when it is loaded, so oneAPI.jl can +# only set them if NEO isn't loaded yet; otherwise it warns. NEO_jll loads it itself unless +# it was built not to. Either way, the keys aren't passed on to child processes, and the GPU +# has to remain usable. +function run_direct_submission(preload::Bool) + script = """ + import NEO_jll + loaded = NEO_jll.libze_intel_gpu_handle != C_NULL + if $preload + Base.Libc.Libdl.dlopen(NEO_jll.libze_intel_gpu) + loaded = true + end + using oneAPI + oneAPI.functional() || error("oneAPI is not functional") + forced = oneAPI.oneL0.direct_submission_forced[] + forced == !loaded || error("direct submission forced: \$forced, NEO loaded: \$loaded") + any(key -> haskey(ENV, key), ["NEOReadDebugKeys", "EnableDirectSubmission"]) && + error("NEO's debug keys were left in the environment") + a = oneArray(Float32[1, 2]) + a .+= 1 + Array(a) == Float32[2, 3] || error("wrong result") + print(loaded) + """ + cmd = `$(Base.julia_cmd()) --project=$(Base.active_project()) -e $script` + # use our NEO, which the preload case loads + cmd = addenv(cmd, "ONEAPI_DIRECT_SUBMISSION" => "1", "ZE_ENABLE_ALT_DRIVERS" => nothing, + "NEOReadDebugKeys" => nothing, "EnableDirectSubmission" => nothing) + out, err = IOBuffer(), IOBuffer() + proc = run(pipeline(ignorestatus(cmd); stdout=out, stderr=err)) + log = String(take!(err)) + success(proc) || (print(stderr, log); error("direct submission test process failed")) + loaded = parse(Bool, String(take!(out))) + return loaded, occursin("NEO driver has already been loaded", log) +end + +loaded, warned = run_direct_submission(false) +@test warned == loaded + +loaded, warned = run_direct_submission(true) +@test loaded && warned + +end