Interface

To extend the above functionality to a new array type, you should use the types and implement the interfaces listed on this page. GPUArrays is designed around having two different array types to represent a GPU array: one that exists only on the host, and one that actually can be instantiated on the device (i.e. in kernels). Device functionality is then handled by KernelAbstractions.jl.

Host abstractions

You should provide an array type that builds on the AbstractGPUArray supertype, such as:

mutable struct CustomArray{T, N} <: AbstractGPUArray{T, N}    data::DataRef{Vector{UInt8}}    offset::Int    dims::Dims{N}    ...end

This will allow your defined type (in this case JLArray) to use the GPUArrays interface where available. To be able to actually use the functionality that is defined for AbstractGPUArrays, you need to define a KernelInterface back-end, which compiles and launches kernels, like so:

import KernelInterface as KIstruct CustomBackend <: KI.Backend endKI.get_backend(a::CA) where CA <: CustomArray = CustomBackend()

There are numerous examples of potential interfaces for GPUArrays, such as with JLArrays, CuArrays, and ROCArrays.

Alias detection

Without the hook below, all views of one buffer are treated as aliasing each other, so Base and GPUArrays copy one of them before operations that write to the other (e.g. copyto!, broadcasting, accumulate!). Report where an array's elements are stored to make that check precise:

GPUArrays.memory_location — Function
GPUArrays.memory_location(A::AbstractGPUArray) -> Union{Nothing, Tuple{UInt, Int}}

Where the elements of A are stored: a coordinate base that identifies the allocation holding them (normally its address), and the byte offset of the first element from it. GPUArrays defines Base.dataids, Base.mightalias and the check Base uses to compare two SubArrays of the same parent for every AbstractGPUArray; with this hook, they compare the byte ranges arrays cover instead of the allocations they share.

Two arrays are taken to share memory when their byte ranges, sizeof(A) bytes from base + offset, overlap. For that to be sound:

  • Every array derived from an allocation (a view, reshape or reinterpretation, which are built with derive) must report the same base, and a nonnegative offset into it. Memory wrapped from a pointer into the middle of an allocation (unsafe_wrap) reports a base of its own: it is still compared by byte range against arrays that implement this hook, but against wrapped arrays (e.g. a SubArray) and arrays of other types (e.g. an Array), only when both start at the same address.
  • Arrays that share memory must report it in the same coordinates. That holds for addresses in a single address space, but not for memory that is reachable at two addresses (such as a host buffer and its device mapping) or that is wrapped twice with separate identities (such as two handles for one buffer): the hook cannot express such aliases, so a back-end that creates them has to detect them itself.
  • Memory without an address may be identified by any other value that is unique to its allocation, such as a handle. Overlap with the coordinates of other memory only causes false positives.
  • For valid, live arrays it must not have side effects (taking stream ownership, synchronizing) and must not throw, as Base checks for aliasing in many operations, including copyto! and broadcasting.

The default, nothing, keeps alias detection at the level of allocations: arrays alias when they share the DataRef returned by GPUArrays.storage.

source

Vendor BLAS

GPUArrays implements LinearAlgebra's matrix products, triangular products and solves, Diagonal products, matrix additions with transposed operands, and BLAS 1 functions such as dot, norm, axpy! and rotate! for all GPU arrays. It checks dimensions, turns transposed, symmetric and triangular wrappers into BLAS characters, handles false as a strong zero, and then calls one of the hooks below. Their default methods use GPUArrays' kernels; a back-end with a vendor BLAS library adds methods for the operand types and eltypes that library supports, and everything else keeps using the defaults:

GPUArrays.blas_gemm!(tA, tB, α::Union{Bool,T}, A::StridedCuVecOrMat{T}, B::StridedCuVecOrMat{T},                     β::Union{Bool,T}, C::StridedCuVecOrMat{T}) where {T<:CublasFloat} =    CUBLAS.gemm!(tA, tB, α, A, B, β, C)

The hooks are only called with operands that a BLAS library can address:

  • Operands are GPU arrays or strided views of them. Matrix operands have a unit row stride and a column stride of at least their number of rows; vectors have a positive stride.
  • The operands of BLAS 1 hooks (blas_scal! to blas_rot!) are vectors with a positive stride or contiguous arrays, i.e. length(x) elements stride(x, 1) apart.
  • Dimensions match, and no operand is empty.
  • Operands have the same eltype, except for blas_gemm! and blas_gemv!.
  • Scalars are Bools or of the eltype of the output, to which they are promoted like LinearAlgebra does unless they are of a wider type. The exceptions: blas_gemm! can also receive other scalars, blas_herk! receives real ones, and BLAS 1 hooks and blas_geam! can receive real scalars for complex operands.
  • Outputs don't share memory with inputs, except where a hook documents otherwise.

The BLAS 1, 2 and 3 hooks mirror the functions in LinearAlgebra.BLAS, and the extensions the ones in cuBLAS:

GPUArrays.blas_gemm! — Function
GPUArrays.blas_gemm!(tA, tB, α, A, B, β, C)

C = α op(A) op(B) + β C, like LinearAlgebra.BLAS.gemm!. The operands can be vectors, as $n×1$ matrices, and are the only ones that can have different eltypes, while α and β can be of yet another type if converting them to the eltype of C would lose precision.

source
GPUArrays.blas_symm! — Function
GPUArrays.blas_symm!(side, uplo, α, A, B, β, C)
GPUArrays.blas_hemm!(side, uplo, α, A, B, β, C)

C = α A B + β C (side == 'L') or C = α B A + β C (side == 'R') with A symmetric or Hermitian, stored in its uplo triangle, like LinearAlgebra.BLAS.symm!/hemm!. B and C can be vectors.

source
GPUArrays.blas_syrk! — Function
GPUArrays.blas_syrk!(uplo, trans, α, A, β, C)
GPUArrays.blas_herk!(uplo, trans, α, A, β, C)

Update the uplo triangle of C with α A Aᵀ + β C (trans == 'N') or α Aᵀ A + β C (trans == 'T'), or the Hermitian α A Aᴴ + β C and α Aᴴ A + β C (trans == 'C'), like LinearAlgebra.BLAS.syrk!/herk!. For herk!, α and β are real. The other triangle of C is left unspecified.

source
GPUArrays.blas_trmm! — Function
GPUArrays.blas_trmm!(side, uplo, trans, diag, α, A, B, C)

C = α op(A) B (side == 'L') or C = α B op(A) (side == 'R') with A triangular, stored in its uplo triangle and with a unit diagonal if diag == 'U'. Unlike LinearAlgebra.BLAS.trmm!, the result goes to C, which can be B. B and C can be vectors.

source
GPUArrays.blas_trsm! — Function
GPUArrays.blas_trsm!(side, uplo, trans, diag, α, A, B)

Overwrite B with α op(A) \ B (side == 'L') or α B / op(A) (side == 'R') with A triangular, like LinearAlgebra.BLAS.trsm!. B can be a vector. A singular A yields Infs and NaNs, as with vendor libraries, rather than an exception.

source
GPUArrays.blas_dot — Function
GPUArrays.blas_dot(x, y)
GPUArrays.blas_dotu(x, y)

The dot product of x and y, conjugating x (dot, which vendor libraries call dotc for complex numbers) or not (dotu).

source
GPUArrays.blas_asum — Function
GPUArrays.blas_asum(x)

The sum of the absolute values of the real and imaginary parts of x, like LinearAlgebra.BLAS.asum.

source
GPUArrays.blas_axpy! — Function
GPUArrays.blas_axpy!(α, x, y)
GPUArrays.blas_axpby!(α, x, β, y)

Overwrite y with α x + y or α x + β y, like LinearAlgebra.BLAS.axpy!/axpby!.

source
GPUArrays.blas_rot! — Function
GPUArrays.blas_rot!(x, y, c, s)

Apply the Givens rotation with real cosine c and sine s to the pairs of elements of x and y, like LinearAlgebra.rotate!.

source
GPUArrays.blas_geam! — Function
GPUArrays.blas_geam!(tA, tB, α, A, β, B, C)

C = α op(A) + β op(B), like cuBLAS's geam. With β === false, B is not read, which is how transposing a matrix into C is expressed.

source
GPUArrays.blas_dgmm! — Function
GPUArrays.blas_dgmm!(side, A, x, C)

C = Diagonal(x) A (side == 'L') or C = A Diagonal(x) (side == 'R'), like cuBLAS's dgmm. C can be A.

source

Caching Allocator

GPUArrays.@cached — Macro
@cached cache expr

Evaluate expr using allocations cache cache.

When GPU memory is allocated during the execution of expr, cache will first be checked. If no memory is available in the cache, a new allocation will be requested.

After the execution of expr, all allocations made under the scope of @cached will be cached within cache for future use. This is useful to avoid relying on GC to free GPU memory in time.

Once cache goes out scope, or when the user calls unsafe_free! on it, all cached allocations will be freed.

Example

In the following example, each iteration of the for-loop requires 8 GiB of GPU memory. Without caching those allocations, significant pressure would be put on the GC, resulting in high memory usage and latency. By using the allocator cache, the memory usage is stable:

cache = GPUArrays.AllocCache()for i in 1:1000    GPUArrays.@cached cache begin        sin.(CUDA.rand(Float32, 1024^3))    endend# optionally: free the memory now, instead of waiting for the GC to collect `cache`GPUArrays.unsafe_free!(cache)

See @uncached.

source
GPUArrays.@uncached — Macro
@uncached expr

Evaluate expression expr without using the allocation. This is useful to call from within @cached to avoid caching some allocations, e.g., because they can be returned out of the @cached scope.

source
GPUArrays.is_cached_storage — Function
GPUArrays.is_cached_storage(ref::DataRef) -> Bool

Whether the data behind ref is owned by an allocation cache (see @cached), which will hand it out again once the cache's scope ends. This holds for the cache's own reference as well as for every reference derived from it (e.g. by views and reshapes), from the first allocation until the cache is invalidated, regardless of the current task or cache scope.

Back-ends can use this to refuse operations that would keep using the memory after the scope ends, such as recording it into a CUDA graph.

source