Overlays

GPUToolbox.Overlays — Module
GPUToolbox.Overlays

Method tables with device overrides of Base functionality, shared by GPU back-ends.

Some of Base's methods are unsuited for GPUs, e.g., because they compute single-precision results in double precision, which many GPUs don't support. Back-ends replace such methods with overlay methods in their own method table. The tables in this module collect overrides that aren't specific to a back-end, so that back-ends can share them by stacking them underneath their own method table.

Usage

A back-end uses a table by stacking it underneath its own method table when it creates the method table view for a compiler job, e.g.:

function GPUCompiler.method_table_view(job::MyCompilerJob)    if job.config.target.supports_fp64        GPUCompiler.StackedMethodTable(job.world, method_table)    else        GPUCompiler.StackedMethodTable(job.world, method_table,                                       GPUToolbox.Overlays.float64_overrides)    endend

As shown here, the tables to use can depend on the target device. The choice may only depend on the job's target and parameters, though, as GPUCompiler shares inference results between jobs with equal targets and parameters.

Lookup order

The tables in a stack are searched from the top: the first table with a method that covers the signature of a call provides the implementation, even if a table further down the stack, or Base, has a more specific method. The stack should be ordered from the most to the least device-specific knowledge:

  1. the back-end's own method table, with implementations that use the device's hardware or vendor libraries;
  2. tables shared by a family of back-ends, like the one from SPIRVIntrinsics.jl, used by the back-ends targeting OpenCL environments;
  3. the tables in this module;
  4. Base.

Because of that, the overrides here only act as fallbacks: a back-end replaces one by defining its own method with the same signature. Calls made by an override are again looked up from the top of the stack, so shared overrides use the back-end's implementations of the functions they call.

Rules

To keep the order of the stack from affecting correctness, overrides in this module:

  • implement the Base method they replace completely and correctly for their signature, so that the back-end's methods only have to be better, not different;
  • consist of generic Julia code, without calls to device-specific functionality;
  • use concrete signatures, so as not to hide more specific methods further down the stack;
  • replace a method in Base, or extend a Base function for a type defined in this module (checked by audit);
  • don't overlap with the overrides in other tables in this module, so that the relative order of these tables doesn't matter;
  • document which functions they expect the stack to provide (e.g., Float64-free elementary functions);
  • throw exceptions with device_throw (see below).

Back-ends can check their stack with audit, e.g., as part of their tests.

Exceptions

GPU compilers can't throw exception objects: they only report that an exception occurred, and at most which function threw it. Back-ends therefore replace Base's methods that throw with methods that report the exception with a constant type name and message, using their own runtime. Shared overrides can't call into that runtime, so they throw with device_throw instead, passing the exception type and message as constants. Each back-end replaces that function in its own method table, which makes the exceptions thrown by shared overrides report like the back-end's own.

Device-only functionality

Back-ends also define methods that only work on the device, in their own method table, with the macros built on device_override (replacing a host method) and device_function (a function that throws on the host). Their methods with device code must stay out of the global method table: sysimage builds compile every method there with a concrete signature for the host, and an image that refers to device symbols doesn't load (nor does a package image on Windows). Back-ends can check that with host_leaks, e.g., as part of their tests.

Bindings

A Base method can also be unsuited for a device because of a global it reads: stdout, or a lookup table stored in a Vector. @binding_overlay gives such a binding a constant to read in device code, so that the method doesn't have to be replaced. Binding overlays are declared in a method table and stacked like method overlays.

Tables

  • float64_overrides: overrides of Base methods that use Float64 to compute single- or half-precision results.
  • int128_overrides: overrides of Base methods that use 128-bit integers to compute results for narrower ones.
  • lookup_table_overrides: binding overlays that make the lookup tables of Base and Random constants in device code.
  • throw_overrides: overrides of Base methods that throw exceptions with messages built at run time.
source
GPUToolbox.Overlays.float64_overrides — Constant
GPUToolbox.Overlays.float64_overrides

Method table with overrides of Base methods that use Float64 to compute single- or half-precision results, for devices that don't support Float64 or where it is slow.

The overrides only replace Base's generic code, and call functions like sin, cos, sinpi, cospi and ^(::Float32, ::Float32), which Base also implements using Float64. Back-ends stacking this table should provide Float64-free implementations of those (e.g., using their hardware's math library) in a table higher up the stack.

See GPUToolbox.Overlays for how to use this table.

source
GPUToolbox.Overlays.int128_overrides — Constant
GPUToolbox.Overlays.int128_overrides

Method table with overrides of Base methods that use Int128 or UInt128 to compute results for narrower integers, for devices that don't support 128-bit integers.

This currently covers the comparisons of Rationals with each other, with integers and with floating-point numbers, which Base performs on the 128-bit products of their 64-bit numerators and denominators.

See GPUToolbox.Overlays for how to use this table.

source
GPUToolbox.Overlays.lookup_table_overrides — Constant
GPUToolbox.Overlays.lookup_table_overrides

Method table with binding overlays (see @binding_overlay) that make the lookup tables of Base and Random, which are global Vectors that device code can't read, constant tuples in device code. That makes the methods that read them work on a device: ndigits, which reads Base.powers_of_ten, and the Ziggurat samplers behind randn and randexp, which read Random's ki, wi, fi (normal distribution) and ke, we, fe (exponential distribution). A tuple compiles to a constant in the device code, which is indexed at run time. The table only supplies the data: the back-end still has to support what these methods do otherwise, e.g. provide a random number generator.

See GPUToolbox.Overlays for how to use this table.

source
GPUToolbox.Overlays.throw_overrides — Constant
GPUToolbox.Overlays.throw_overrides

Method table with overrides of Base's helper functions that throw an exception with a message built at run time, e.g., by interpolating values into a string. GPU compilers can't compile that code, so these overrides throw the same exception with a constant message instead, using device_throw.

This covers Base.throw_domerr_powbysq, which integer exponentiation calls for a negative power, and two helpers that Rational arithmetic calls on Julia 1.10 and 1.11, whose messages include the integer type (Julia 1.11 removed one of them, and Julia 1.12 builds the message of the other lazily).

See GPUToolbox.Overlays for how to use this table.

source
GPUToolbox.Overlays.audit — Function
Overlays.audit(tables::Core.MethodTable...; world=Base.get_world_counter())

Check a stack of method tables, ordered from highest to lowest priority, and return a vector of (; table, method, issue, by) named tuples describing problems with the methods in these tables:

  • issue = :dead: the method overrides a function from Base, but no method of that function matches its signature (e.g., because Base changed the function's signature). Methods of other functions, and methods for types defined in the table's module, aren't checked.
  • issue = :shadowed or issue = :partly_shadowed: a method in table by, higher up the stack, covers all or part of the method's signature, so that (some) calls won't reach it. This is often intentional, e.g., when a back-end replaces a shared fallback.
source
GPUToolbox.Overlays.device_throw — Function
Overlays.device_throw(::Type{E}, ::Val{reason}) where {E<:Exception, reason}

Throw an exception of type E with the message String(reason). The overrides in this module throw their exceptions with this function (as @device_throw ArgumentError("...")), so that back-ends can report them like the exceptions they throw themselves: GPU compilers drop the exception object, so a plain throw(E(msg)) is only reported as an exception of unknown type.

This method throws E(String(reason)), which assumes that E has a constructor that takes the message (as ArgumentError, OverflowError and ErrorException do). A DomainError, whose one-argument constructor takes the offending value, is thrown as DomainError(nothing, String(reason)), as the value isn't known.

Back-ends replace it in their own method table. Both arguments are constants, so a back-end's method can pass them to a reporting function that expects compile-time constants, e.g.:

@device_override @noinline function GPUToolbox.Overlays.device_throw(::Type{E}, ::Val{reason}) where {E, reason}    record_exception(Val(nameof(E)), Val(reason))    throw(nothing)end

or, when the reporting is done by a macro that requires string literals, using a generated function:

@device_override @generated function GPUToolbox.Overlays.device_throw(::Type{E}, ::Val{reason}) where {E, reason}    :(@gputhrow $(String(nameof(E))) $(String(reason)))end

A back-end's method must throw, like this one does.

source
GPUToolbox.Overlays.device_override — Function
Overlays.device_override(mod::Module, table, ex) -> Expr

Rewrite the method definition ex into an overlay of an existing host method, in method table table. This is the implementation of back-ends' @device_override macros:

macro device_override(ex)    esc(GPUToolbox.Overlays.device_override(__module__, GlobalRef(MyBackend, :method_table), ex))end

The overlay must be consistent with the host method it replaces: for the same arguments, it returns an identical value, or throws when the host method throws. In return, inference can keep constant-evaluating calls with the host method, which e.g. keyword-argument handling relies on. Overrides that aren't consistent, like math functions that are less accurate than Base's, should use Base.Experimental.@overlay instead.

source
GPUToolbox.Overlays.device_function — Function
Overlays.device_function(mod::Module, table, ex) -> Expr

Rewrite the method definition ex, or every definition in the block ex, into a method that throws when called on the host, and an overlay with the actual implementation in method table table. This is the implementation of back-ends' @device_function macros:

macro device_function(ex)    esc(GPUToolbox.Overlays.device_function(__module__, GlobalRef(MyBackend, :method_table), ex))end

Use it for functions that only work on the device, i.e., that (indirectly) call device-specific functionality, like intrinsics or the back-end's runtime. Code compiled for the host, e.g., by sysimage builds or ahead-of-time compilers that compile every method, then only contains the throwing method. See host_leaks to find functions that should be device functions.

The overlay is not consistent with the host method (see device_override), or inference could constant-fold calls to the host method's error. Docstrings document the host method, i.e., the function. Definitions can be @generated. In a block, definitions in conditionals are rewritten, but not those in other constructs, like loops.

source
GPUToolbox.Overlays.host_leaks — Function
Overlays.host_leaks(mod::Module) -> Vector{@NamedTuple{method::Method, symbol::String}}

Find the methods of mod and its submodules that sysimage builds compile for the host, and whose code may reach device-only functionality. Such methods should be device functions (see device_function).

This considers the methods that Julia 1.12+ compiles when building a sysimage: those with a compileable signature, or the compileable signatures obtained by splitting unions in their arguments and type parameters, and that aren't @generated. It follows calls that aren't inlined into other methods of mod, and reports the device symbol it finds first:

  • a function that an llvmcall declares, other than an LLVM intrinsic: on the host, it only resolves if the dynamic linker happens to find a symbol with that name. Device code uses these for intrinsics that the GPU compiler lowers, like julia.gpu.state_getter, or that the device's runtime provides, like __spirv_BuiltInGlobalInvocationId;
  • an LLVM intrinsic of a GPU target, like llvm.nvvm.read.ptx.sreg.tid.x.

The check is conservative: it reports declarations in llvmcall IR without checking that the IR uses them. It doesn't follow calls into other packages, so it misses device code in a dependency that is only compiled when called from mod, e.g., because the method that contains it doesn't have a concrete signature (and thus is no root of the dependency's own check).

On Julia 1.10 and 1.11, which have no global method table to search, only the methods of functions that are bound in mod or its submodules are considered.

source
GPUToolbox.Overlays.@binding_overlay — Macro
Overlays.@binding_overlay table Mod.name = value

Give the global binding Mod.name the constant value in code compiled with method table table: where that code reads the binding by name, it reads value instead. This is to bindings what Base.Experimental.@overlay is to methods, and lets Base's own methods work on a device when they read a global that is of no use there:

struct MyDeviceIO <: IO end     # `stdout` is declared `::IO`# Base's `print(xs...) = print(stdout, xs...)` now prints to the device's stream@binding_overlay method_table Base.stdout = MyDeviceIO()# Base's `ndigits` reads a `Vector`, which device code can't; a tuple compiles to a constant@binding_overlay method_table Base.powers_of_ten = Tuple(Base.powers_of_ten)
Warning

Binding overlays are experimental. Their semantics may change in a minor release.

table has to be a method table declared with Base.Experimental.@MethodTable, and is checked before value is evaluated. It and Mod are names (a global, or a path of modules like A.B.table), which are evaluated again after value. A table is identified by its module and name, so redefining the constant that holds it is not supported. Mod.name is the binding to replace, the source. It has to be a binding that Mod owns (not one it imports), and one of:

  • a global that isn't constant, like Base.stdout. Any name that refers to the global reads value: stdout in a module that uses Base, or Base.stdout. value has to be of the global's declared type, which the code that reads it relies on.
  • a constant that holds a mutable object, like a Vector. Any name that is bound to that object reads value, also in another module, or under another name (const T = Mod.name). The type of value is free, so code that reads the constant has to work with both. Other constants (numbers, tuples, strings, types, functions) cannot be replaced: nothing distinguishes them from other constants with the same value.

value is evaluated once each time the declaration is evaluated, and has to be something that the device code can use as a constant. It is neither copied nor frozen, and does not follow later changes to the source: a tuple made from a Vector keeps the elements the vector had then. Which reads it applies to, on the other hand, is decided when code is compiled, by what the source is in that world: if the constant Mod.name is later bound to another Vector, the overlay applies to reads of that one, and no longer to names that are still bound to the old one.

Which reads

Only reads that name the binding in the code are replaced: name, Mod.name and getglobal(Mod, :name), where Mod is a name for a constant module (or such a read itself, as in A.B.name) and name is a literal. These refer to the host binding:

  • reads through a module that is a value: an argument, a non-constant global, or a module that a binding overlay provides, even when the compiler knows which module it is;
  • getfield(Mod, :name), and reads with a memory order (getglobal(Mod, :name, :monotonic));
  • stores, and isdefined;
  • a value that reaches device code in another way, e.g., as an argument.

Mod.name is taken to mean what Base defines it as: a table with binding overlays shouldn't overlay getproperty for modules. GPUCompiler applies binding overlays when the method table view of a job is one it knows (an OverlayMethodTable, a StackedMethodTable or a MethodTableStack), and leaves code that switches to the latest world (:latestworld, Julia 1.12+) alone.

Tables and invalidation

Like method overlays, binding overlays are looked up in the tables that a compiler stacks, and the first table that has one for a binding provides it. A table shouldn't have two that apply to the same read: declaring one for a binding that another module already declared in the same table is an error, and so are two declarations for constants bound to the same object, which a compiler reports when it looks up the declarations of the table. That includes declarations by packages that were precompiled independently.

Declaring, replacing or deleting an overlay (e.g., with Base.delete_method, or by Revise) invalidates the device code that depends on it, which is compiled again when it is next needed. The dependency is broad: a new declaration invalidates all code in which a read could be overlaid by a declaration in that table. Some changes aren't noticed:

  • on Julia 1.10 and 1.11, code doesn't depend on bindings, so rebinding the source, or a name that refers to it, isn't noticed;
  • on 1.12 and 1.13, neither is replacing a name that a module uses implicitly by an explicit import of another global, as for code that Julia compiles;
  • device code that a package image holds isn't invalidated by a declaration that was loaded before the image, from a package the image doesn't depend on (as for method overlays, JuliaLang/julia#63959).

Declaring again

A declaration is identified by the module that declares it, the table, and the source binding, not by how these are written. Evaluating it again (with an alias of the table or of Mod, or by Revise when it revises a package) replaces it, like evaluating a method definition again. Replacing the value of a declaration that code may have used requires Julia 1.12, where code depends on the constants it reads. Like a method, a declaration can't be replaced while its package is being precompiled. Files tracked with Revise's includet only have their method definitions evaluated again, which leaves the value as it was.

source
GPUToolbox.Overlays.binding_overlay_signature — Function
Overlays.binding_overlay_signature(mt::Core.MethodTable) -> Type

The signature of the methods in mt that declare binding overlays (see @binding_overlay). A compiler finds the declarations in mt by looking up the methods for this signature in mt, and passing them to binding_overlay_refs. Declarations in tables with another module or name don't intersect the signature.

This, binding_overlay_refs and has_identity are the interface between GPUToolbox and compilers. Unlike the semantics of binding overlays, it is stable across GPUToolbox 3.x.

source
GPUToolbox.Overlays.binding_overlay_refs — Function
Overlays.binding_overlay_refs(method::Method) -> (source::GlobalRef, target::GlobalRef)

The binding overlay that method declares, a method found with binding_overlay_signature: a read of the binding source becomes a read of the constant target. Both refer to bindings that are to be resolved in the world that the code is compiled for. Throws an ArgumentError for a method that wasn't defined by @binding_overlay.

This is part of the interface between GPUToolbox and compilers, which is stable across GPUToolbox 3.x (see binding_overlay_signature).

source
GPUToolbox.Overlays.has_identity — Function
Overlays.has_identity(x) -> Bool

Whether x is an object that === compares by address: a mutable value other than a type, module, string or symbol (the latter two compare by content). Only constants that hold such an object can be the source of a binding overlay (see @binding_overlay), as compiled code depends on the value of a constant and not on the binding it was read from.

This is part of the interface between GPUToolbox and compilers, which is stable across GPUToolbox 3.x (see binding_overlay_signature).

source