GPUToolbox.jl

API

GPUToolbox.LazyInitialized — Type
LazyInitialized{T}()

A thread-safe, lazily-initialized wrapper for a value of type T. Initialize and fetch the value by calling get!. The constructor is ensured to only be called once.

This type is intended for lazy initialization of e.g. global structures, without using __init__. It is similar to protecting accesses using a lock, but is much cheaper.

Any value of type T, including nothing when allowed by T, may be stored.

source
GPUToolbox.Literal — Type
Literal{T}

Construct an object that can be used to convert literals to other types. One can use the object in suffix form 1*i8 or 1i8 to perform the conversion.

Exported constants

  • i8: Convert to Int8
  • i16: Convert to Int16
  • i32: Convert to Int32
  • u8: Convert to UInt8
  • u16: Convert to UInt16
  • u32: Convert to UInt32
source
GPUToolbox.cooperative_wait — Method
cooperative_wait(wait, obj; subscribe=nothing, isdone=nothing, spin=true,
                 cancellable=false)

Wait for obj to complete without blocking the calling thread, so that other tasks can run on it in the meantime.

wait(obj) should perform a blocking wait for obj. By default, it is executed on a separate thread (in the caller's world, i.e., seeing the same method definitions as a direct call), so it should block in a GC-safe manner (e.g., using @gcsafe_ccall) and set up any thread-local state it relies on (e.g., the active context).

Alternatively, if the driver can notify completion by calling back, pass a function subscribe(obj, payload::Ptr{Cvoid}) that registers such a callback, which in turn calls GPUToolbox.signal_completion(payload). This avoids involving a worker thread, which matters for devices that execute on the host's CPU cores, where waking a worker delays the operation. wait is then only used where the calling thread cannot switch tasks (see below). The callback:

  • has to be called exactly once, also when the operation fails, and may be called before subscribe returns;
  • must not be registered if subscribe throws;
  • may be called from any thread, but must not let exceptions escape into the driver.

signal_completion does not run finalizers on the calling thread, except on debug builds of Julia, so with those, drivers that hold locks while invoking callbacks may deadlock if a finalizer calls into the driver. Don't use subscribe with such drivers there.

Registering the callback, and any other driver call that may wait for callbacks to finish, should be GC-safe (e.g., using @gcsafe_ccall): a thread calling back into Julia may have to wait for the garbage collector, which waits for all threads executing Julia code. For example, with OpenCL:

function notify_completion(event::cl_event, status::Cint, payload::Ptr{Cvoid})    GPUToolbox.signal_completion(payload)    returnendsubscribe(event, payload) =    clSetEventCallback(event, CL_COMPLETE,                       @cfunction(notify_completion, Cvoid, (cl_event, Cint, Ptr{Cvoid})),                       payload)

If the wait can be interrupted (see cancellable), the callback may be called after cooperative_wait has returned, so it should not use anything else the caller may release by then.

isdone(obj), if given, should return whether obj has completed without blocking. It is used to detect short operations without involving another thread, and to poll obj while all worker threads are busy. Objects that cannot be polled get an additional thread instead.

spin determines how obj is polled before waiting as described above. By default, it is polled for a while, first busy-waiting and then yielding to other tasks. For devices that execute on the host's CPU cores, that competes with the operation for those cores, so pass a duration in seconds (e.g., spin=10e-6) to only busy-wait for at most that long. With spin=false, obj is not polled at all.

Returns Some(wait(obj)), or nothing if wait was not called because polling or a notification found obj to have completed. In that case, calling wait(obj) should not block for long (it may have to wait for the notification callback to return), and may still be needed, e.g., to synchronize memory or to check for errors. Errors thrown by wait, subscribe or isdone are rethrown.

If the wait is interrupted (i.e., an InterruptException is thrown) or the task is cancelled, the default is to keep waiting, and only throw once obj has completed: the operation may be using memory that the caller would release when unwinding. Note that wait(obj) may not have been called by then. Waits with cancellable=true throw immediately, while the operation may still be executing.

In finalizers, where it is not possible to switch tasks, and while generating output (e.g., during precompilation), wait(obj) is called on the calling thread instead.

source
GPUToolbox.parse_launch_macro — Method
parse_launch_macro(ex::Tuple; name::String, options=(:launch,))

Parse the arguments ex of a kernel launch macro, like @cuda threads=n kernel(a, b): keyword arguments followed by a function call. name is the name of the macro, used in error messages, and options lists the keywords that configure the macro itself rather than the kernel's compilation or launch.

Returns a NamedTuple with these fields, all expressions to be used in the macro's expansion (they are not escaped):

  • bindings: a block that evaluates each argument of the call once, binding it to a fresh variable. Include it in the expansion before using args or roots.
  • callee: the function being called, as written. It is not evaluated by bindings, so the macro decides when to do so.
  • args: the bound arguments, to be used as the arguments of a call. A splatted argument xs... becomes var..., and is iterated anew at each use.
  • roots: the variables bound to the arguments, to keep alive with GC.@preserve.
  • options: a Dict from the keywords in options that were written out to their values, as written. The macro has to validate these itself, e.g. that a value is a literal Bool. Each can only be written once.
  • kwargs: the remaining keyword arguments, as key=value expressions or splats x..., in the order they were written, with key shorthand expanded to key=key.

The names in a splat are only known at run time, so the macro should route all of kwargs then, with partition_kwargs: build one NamedTuple from them, which evaluates them and resolves repeated names in order like the keyword arguments of a function call, and partition it. A splat can contain an option, which the macro has to reject:

macro mylaunch(ex...)    p = GPUToolbox.parse_launch_macro(ex; name="@mylaunch", options=(:launch,))    launch = get(p.options, :launch, true)    launch isa Bool || throw(ArgumentError("`launch` to @mylaunch should be a literal Bool"))    esc(quote        let            $(p.bindings)            options, launch_kwargs, compiler_kwargs =                $(GPUToolbox.partition_kwargs)((; $(p.kwargs...)), (:launch,), (:threads, :blocks))            isempty(options) || throw(ArgumentError("options to @mylaunch cannot be splatted"))            args = ($(p.args...),)            kernel = $compile($(p.callee), args...; compiler_kwargs...)            $launch && kernel(args...; launch_kwargs...)            kernel        end    end)end

Here, compile stands for the back-end's compiler. A real macro should use variables made with gensym instead of names like options, as the expansion is evaluated in the caller's scope. Interpolate functions, like partition_kwargs above, so that the caller doesn't need to have imported them.

source
GPUToolbox.partition_kwargs — Method
partition_kwargs(kwargs, groups...) -> (group_1::NamedTuple, ..., rest::NamedTuple)

Partition keyword arguments by name: each of groups, a collection of Symbols, claims the keyword arguments it lists that an earlier group did not, and rest holds those that no group claims. Each result keeps the order of kwargs, which can be a NamedTuple or anything else that can be splatted as keyword arguments, like the kwargs... of a function.

When the type of kwargs is a concrete NamedTuple, and the groups are tuples whose values are known to the compiler, like constants, the partition happens at compile time: the call is type stable and doesn't allocate. Use tuples rather than vectors for groups used when launching a kernel.

julia> GPUToolbox.partition_kwargs((; threads=32, maxregs=16, blocks=4), (:threads, :blocks))((threads = 32, blocks = 4), (maxregs = 16,))
source
GPUToolbox.signal_completion — Method
GPUToolbox.signal_completion(payload::Ptr{Cvoid})

Signal that the operation a subscribe function (see cooperative_wait) registered a notification for has completed, waking up the waiting task. This can be called from a thread that is not managed by Julia (e.g., one owned by the driver), and does not throw.

source
GPUToolbox.@checked — Macro
@checked function foo(...)
    rv = ...
    return rv
end

Macro for wrapping a function definition returning a status code. Two versions of the function will be generated: foo, with the function execution wrapped by an invocation of the check function (to be implemented by the caller of this macro), and unchecked_foo where no such invocation is present and the status code is returned to the caller.

source
GPUToolbox.@gcsafe_ccall — Macro
@gcsafe_ccall ...

Call a foreign function just like @ccall, but marking it safe for the GC to run. This is useful for functions that may block, so that the GC isn't blocked from running, but may also be required to prevent deadlocks (see JuliaGPU/CUDA.jl#2261).

Note that this is generally only safe with non-Julia C functions that do not call back into the Julia directly.

source
GPUToolbox.@memoize — Macro
@memoize [key=expr::K | index=expr] begin
    # expensive computation
end::T

Low-level, no-frills memoization macro that stores values in a process-local, typed cache. The types of the caches are derived from the syntactical type assertions. All return values, including nothing, are memoized correctly.

With no leading argument, a single value is memoized. Use key=expr::K for dictionary memoization keyed by values of type K. Use index=expr for array-backed memoization with small, dense, positive integer indices; sparse or large keys should use dictionary mode instead. Index mode grows the backing array on demand. On Julia 1.11+, index-mode slots use atomic per-element access. Atomic slot access is lock-free for pointer-representable values; other values may use Julia's internal per-element atomic fallback.

source