Matrix multiply (GEMM)

C := α op(A) op(B) + β C in several forms:

  • gemm! — the dense entry point, in output-first (gemm!(C, A, B; alpha, beta)) or BLAS (gemm!(transA, transB, alpha, A, B, beta, C)) argument order.
  • gemmEx! — storage and accumulation types chosen separately.
  • gemm_batched! and gemmEx_batched! — many independent products in one call, from a vector of matrices or a 3-D strided array.
  • Grouped GEMM — batches of products with different shapes.
  • recgemm! — one GEMM that picks the accumulation type by itself (Float32 for Float16 storage); its recursive mixed-precision method is documented under Mixed-precision BLAS.
  • GEMM_ADD! / GEMM_SUB! — the tiled KernelAbstractions kernel.

Dense and extended GEMM

NextLA.gemm — Function
gemm(A, B; kwargs...)

Generic function for an allocating matrix product, for structured matrix types whose result layout depends on ranks found at runtime. It has no dense method: gemm(A, B) on plain matrices throws a MethodError. Use gemm! for dense matrices.

source
NextLA.gemm! — Function
gemm!(C, A, B; alpha=true, beta=false, kwargs...)

Compute C := alpha * A * B + beta * C in place.

gemm! is the common NextLA dispatch point for dense and structured matrix products. Dense matrix products forward to LinearAlgebra.mul!, except Float16 on the CPU and CUDA, which goes to gemmEx! so that it sums in Float32; structured matrix types provide specialized methods.

Examples

julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024);

julia> C0 = copy(C);

julia> gemm!(C, A, B; alpha=2.0, beta=0.5);   # C = 2AB + C/2

julia> C ≈ 2.0 * A * B + 0.5 * C0
true
source
NextLA.gemm! — Method
gemm!(transA, transB, alpha, A, B, beta, C) -> C

The BLAS argument order: C := alpha * op(A) * op(B) + beta * C, where op is the identity, transpose or adjoint for 'N', 'T' or 'C'. The flags are accepted in either case.

It forwards to the output-first method, so it runs on every backend and reaches cuBLAS/rocBLAS (through mul!, or gemmEx! for Float16) on GPU arrays.

Examples

julia> A = rand(1024, 1024); B = rand(1024, 1024); C = zeros(1024, 1024);

julia> gemm!('T', 'N', 1.0, A, B, 0.0, C);   # C = Aᵀ B

julia> C ≈ transpose(A) * B
true
source
NextLA.gemmEx! — Method
gemmEx!(transA, transB, alpha, A, B, beta, C; compute_type=...)

Compute the matrix product

C := alpha * op(A) * op(B) + beta * C

and store the result in C.

gemmEx! is an advanced NextLA API for backends that support mixed-type GEMM where the result storage may differ from the operand storage. It is available unqualified (it is exported) and as NextLA.gemmEx!.

op(A) and op(B) are determined by transA and transB, which may be:

  • 'N': no transpose
  • 'T': transpose
  • 'C': adjoint

The flags are accepted in either case.

Notes

  • The accumulation type can be selected explicitly with compute_type; by default default_compute_type chooses it from the storage types of A, B and C. alpha and beta take no part and are converted to it.
  • Mixed storage and compute types are a CUDA and AMDGPU feature. The CPU accepts any combination, accumulating in compute_type. oneAPI and Metal have no gemmEx! and throw for every signature, same-type ones included.
  • If a backend does not support a requested storage and compute type combination, backend-specific errors may be raised.
  • Algorithm selection and backend-specific math modes are out of scope for this API.

Examples

julia> A = rand(Float16, 1024, 1024); B = rand(Float16, 1024, 1024);

julia> C = zeros(Float32, 1024, 1024);   # Float16 operands, Float32 result

julia> gemmEx!('N', 'N', 1.0, A, B, 0.0, C; compute_type=Float32);

julia> C ≈ Float32.(A) * Float32.(B)
true
source
NextLA.recgemm! — Method
recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::AbstractMatrix) -> C

Compute C := alpha * A * B + beta * C in place, for dense matrices. This method does not recurse: it makes one GEMM call, chosen by element type.

  • Same-type Float32, Float64, ComplexF32 or ComplexF64: gemm!.
  • Float16 A and B into a Float16 or Float32 C: gemmEx! with a Float32 sum. On Metal and oneAPI, which have no gemmEx!, the same sum comes from one Float32 gemm! on widened copies.
  • Other mixes: when C is at least as wide as A and B, the operands are widened to eltype(C) and passed to gemm!. Otherwise gemmEx! sums in at least Float32 and rounds once on store. On a GPU, when C is narrower than A and B, they are first rounded to eltype(C).

No transpose is applied. Sizes that do not fit throw DimensionMismatch. The method for a mixed-precision C is documented separately.

source

Compute types and alignment

NextLA.GEMM_COMPUTE_TYPES — Constant
GEMM_COMPUTE_TYPES

compute_type values inferred or used internally by the advanced NextLA.gemmEx! and NextLA.gemmEx_batched! APIs.

compute_type is the Julia type used to request the GEMM accumulation type. These are plain Julia types, not backend-specific math modes such as TF32 or other fast-math settings.

NextLA separates its primary BLAS surface from the advanced Ex interfaces:

  1. Ordinary dense GEMM is gemm!, which forwards to mul! (Float16 on the CPU and CUDA to gemmEx!, for Float32 sums).
  2. gemm_batched! provides the batched GEMM surface, for many independent products.
  3. NextLA.gemmEx! and NextLA.gemmEx_batched! are advanced APIs for mixed-type GEMM where the result storage may differ from the operand storage.

compute_type is chosen from the storage types of A, B and C by default_compute_type; alpha and beta take no part and are converted to it. Support for the chosen combination depends on the backend.

The table below summarizes the current behavior.

Standard GEMM behavior:

OperationCPUCUDAAMDGPUoneAPIMetal
gemmEx! with default compute_typeBLAS, or a wide accumulationcuBLAS GEMMExrocBLAS GEMMExthrowsthrows
gemm_batched!, 3-D stridedBLAS loop, same-type BLAS types only; a batch count of 1 broadcastsstrided batched, or GEMMExstrided batched, or GEMMExoneMKL stridedMPS; equal batch counts only
gemm_batched!, vector of matricesBLAS loop, same-type BLAS types onlypointer batched; non-native types via GEMMExrocBLAS batchedoneMKL batchedthrows
gemm_batched_ptrs!throwspointer batchedpointer batchedthrowsthrows
gemmEx_batched! with default compute_typesame-type fallback onlycuBLAS batched GEMMExrocBLAS batched GEMMExsame-type fallback onlysame-type fallback only
grouped GEMM, unequal shapesloop of precision_gemm!grouped GEMMExthrowsthrowsthrows
TF32throwssingle, batched and pointer batchedthrowsthrowsthrows

The CPU column is served by BLAS. Single-matrix gemmEx! is the exception: there is no CPU GEMMEx primitive, so a triple BLAS accepts goes to BLAS.gemm! and everything else is accumulated in compute_type and rounded once on store. The batched and precision entry points do not extend that to the CPU – they take what BLAS takes and raise ArgumentError for the rest. The CPU has no half-precision arithmetic, so a wide accumulation there is a convenience, not a speed-up.

A throws above is a vendor limitation or an unverified path rather than an oversight. Neither oneMKL nor MPS exposes a pointer-array batched GEMM or a heterogeneous grouped GEMM, and TF32 is CUDA hardware. gemmEx! on oneAPI and Metal, and Metal's vector-of-matrices batch, throw because no device was available to verify a same-type path; a 3-D batch is the supported Metal form. supports_pointer_batched and supports_grouped_gemm answer for the backend, so a caller can ask before committing to a path.

The oneAPI and Metal entries are written from the vendor APIs and have never been executed – neither device was available during the integration.

Representative supported compute_type combinations, as gemm_signature_supported answers them:

A/B storageC storagecompute_typeCPUCUDAAMDGPUoneAPIMetal
Float16Float16Float32unsupportedyesyesunsupportedunsupported
Float16Float32Float32unsupportedyesyesunsupportedunsupported
BFloat16BFloat16Float32unsupportedyesyesunsupportedunsupported
BFloat16Float32Float32unsupportedyesyesunsupportedunsupported
Int8Int32Int32unsupportedyesyesunsupportedunsupported
Float32Float32Float32BLASyesyesyesyes
Float64Float64Float64BLASyesyesyesyes

AMDGPU serves BFloat16 as CUDA does: _rocblas_datatype maps it to rocBLAS's rocblas_datatype_bf16_r, and rocblas_gemm_ex takes it with a Float32 compute type. Like the rest of the AMDGPU column it compiles but has not run on a device.

TF32 is reached through precision_gemm! and its batched siblings with the TF32() mode rather than a compute_type, and only CUDA implements it.

source
NextLA.NATIVE_GEMM_TYPES — Type
NATIVE_GEMM_TYPES

Element types for which the GPU backends expose a native same-type GEMM. Used by the backend extensions to choose between the native BLAS call and the generic Ex path.

source
NextLA.aligned_leading_dimension — Method
aligned_leading_dimension(T, m) -> Int

Smallest leading dimension >= m that keeps every column of a column-major dense T matrix 16-byte aligned.

Allocate the padded array and take a logical view over the first m rows:

using NextLA, CUDA
n = 1024
ld = aligned_leading_dimension(Float16, 4097)   # 4104
store = CuArray{Float16}(undef, ld, n)
C = view(store, 1:4097, :)                      # stride(C, 2) == 4104

A column offset costs c * ld * sizeof(T) bytes, so an aligned ld makes every column start aligned regardless of which column a panel begins at. Row offsets are ld-independent — those are governed by the tile extent instead, which is what is_gemm_aligned checks.

source
NextLA.default_compute_type — Method
default_compute_type(alpha, A, B, beta, C)

Return the default compute_type inferred by NextLA for mixed-type GEMM.

The rule is intentionally simple and backend-agnostic:

  • Float16 defaults to Float16
  • Float32 defaults to Float32
  • Float64 defaults to Float64
  • integer inputs default to Int32
  • complex inputs follow the corresponding real compute type

Only the storage types of A, B and C decide. alpha and beta are accepted for the signature but take no part, so an untyped literal such as 0.5 on Float32 data cannot raise the compute type to Float64.

Backends may still reject unsupported storage and compute type combinations.

Examples

julia> A = rand(Float16, 1024, 1024); C = zeros(Float32, 1024, 1024);

julia> default_compute_type(1.0, A, A, 0.0, A)   # the Float64 scalars take no part
Float16

julia> default_compute_type(1.0, A, A, 0.0, C) === Float32
true
source
NextLA.gemm_alignment_quantum — Method
gemm_alignment_quantum(T) -> Int

Number of T elements spanning 16 bytes — the granularity at which offsets into a dense operand remain 16-byte aligned.

cuBLAS documents 16-byte alignment of pointers, leading dimensions and the m extent as a performance condition for Tensor Core kernels, not a legality one. Unaligned operands compute correct results but select a slower kernel; measured cost is ~2.2-2.5x for grouped GEMM on H100 and ~1.9-2.2x on Turing. Size tiles and leading dimensions against this quantum to keep the fast kernels selected.

Tquantum
Float16/BFloat168
Float324
Float642

See also aligned_leading_dimension, is_gemm_aligned.

Examples

julia> gemm_alignment_quantum(Float16)
8

julia> gemm_alignment_quantum(Float64) * sizeof(Float64) == 16
true
source
NextLA.is_gemm_aligned — Method
is_gemm_aligned(T, n) -> Bool

Whether n elements of T span a whole number of 16-byte units.

Applied to a nominal tile size this reports whether tile boundaries land on aligned addresses (tile row i of a dense output starts at element offset (i-1) * bm, which is independent of the leading dimension). Applied to a leading dimension it reports whether columns do.

Examples

julia> is_gemm_aligned(Float16, 4097)
false

julia> is_gemm_aligned(Float16, aligned_leading_dimension(Float16, 4097))
true
source
NextLA.TF32 — Type

Request TensorFloat-32 computation for FP32 GEMM operands and output.

Examples

CUDA only; every other backend throws ArgumentError.

using NextLA, CUDA

A = CUDA.rand(Float32, 4096, 4096); B = CUDA.rand(Float32, 4096, 4096)
C = CUDA.zeros(Float32, 4096, 4096)
NextLA.precision_gemm!('N', 'N', 1f0, A, B, 0f0, C, TF32())   # TF32 tensor cores
isapprox(C, A * B; rtol = 1e-2)
source
NextLA.precision_gemm! — Method

Precision-policy dispatch for one GEMM, including mixed output storage.

Examples

julia> A = rand(Float32, 1024, 1024); B = rand(Float32, 1024, 1024); C = zeros(Float32, 1024, 1024);

julia> NextLA.precision_gemm!('N', 'N', 1f0, A, B, 0f0, C, NextLA.GEMMCompute{Float32}());

julia> C ≈ A * B
true
source
NextLA.precision_gemm_batched! — Method
precision_gemm_batched!(transA, transB, alpha, A, B, beta, C, mode)

Dispatch a batched GEMM from its actual operand and destination storage types plus an explicit accumulation mode. The destination determines whether this is an intermediate (Tin) or final (Tout) contraction stage.

Examples

julia> A = rand(1024, 1024, 4); B = rand(1024, 1024, 4); C = zeros(1024, 1024, 4);

julia> NextLA.precision_gemm_batched!('N', 'N', 1.0, A, B, 0.0, C, NextLA.GEMMCompute{Float64}());

julia> all(C[:, :, i] ≈ A[:, :, i] * B[:, :, i] for i in 1:4)
true
source
NextLA.precision_gemm_batched_ptrs! — Method
precision_gemm_batched_ptrs!(transA, transB, alpha,
                              Ad::BatchPtrDescriptor, Aref,
                              Bd::BatchPtrDescriptor, Bref, beta,
                              Cd::BatchPtrDescriptor, Cref,
                              batch_count, mode)

Precision-policy sibling of precision_gemm_batched! for a batched GEMM over caller-owned, persistent pointer-batch descriptors (see BatchPtrDescriptor). Performs the same validate_gemm_signature check from Aref/Bref/Cref's element types, then dispatches to gemmEx_batched_ptrs!. Ad/Bd/Cd are untouched by this call; the caller builds them once and updates them only via swap_batch_ptrs!, never by rebuilding. Aref/Bref/Cref are cheap representative views (not device allocations) used only to size this call's m,n,k and leading dimensions — they may change every call (e.g. as a sketch width varies pass to pass) without requiring Ad/Bd/Cd to.

source

Batched GEMM

NextLA.BatchPtrDescriptor — Type
BatchPtrDescriptor(ptrs, host)
BatchPtrDescriptor(batch::AbstractVector{<:AbstractMatrix})

A device array of matrix base pointers built once and reused across many batched GEMM calls (via gemm_batched_ptrs!/gemmEx_batched_ptrs!), in contrast to the transient pointer arrays the Vector-of-matrix gemm_batched!/gemmEx_batched! methods build and free on every call.

A descriptor carries only addresses, no shape/element-type/leading-dimension information — callers supply a fresh, cheap representative Aref/Bref/Cref view at each call to size that call's GEMM. Slot k is stable across calls: if which logical batch member occupies slot k changes (e.g. active-prefix packing retiring a converged member), that must be expressed with swap_batch_ptrs!, which moves addresses between slots, never by physically reordering the pointed-to data or by rebuilding the descriptor.

The caller owns the descriptor's lifetime and must keep the pointed-to storage alive for as long as the descriptor is used; unlike the transient pointer arrays built by the Vector-of-matrix methods, nothing frees a BatchPtrDescriptor's pointer array automatically.

source
NextLA.gemmEx_batched! — Method
gemmEx_batched!(transA, transB, alpha, A, B, beta, C; compute_type=...)

Compute a mixed-type batched matrix product.

Each batch entry applies

C[i] := alpha * op(A[i]) * op(B[i]) + beta * C[i]

where op(A) and op(B) are determined by transA and transB.

gemmEx_batched! is an advanced NextLA API for batched mixed-type GEMM. It is available as NextLA.gemmEx_batched! and is not part of the primary exported surface.

Notes

  • The accumulation type can be selected explicitly with compute_type; by default default_compute_type infers it from the element types of A, B and C only. alpha and beta take no part.
  • Same-type batched calls may fall back to gemm_batched! on backends that do not expose a mixed-type batched GEMM primitive.
  • Mixed-type batched GEMM is currently implemented for CUDA and AMDGPU.
  • If a backend does not support a requested storage and compute type combination, backend-specific errors may be raised.
  • Algorithm selection and backend-specific math modes are out of scope for this API.

Examples

julia> A = [rand(1024, 1024) for _ in 1:4]; B = [rand(1024, 1024) for _ in 1:4];

julia> C = [zeros(1024, 1024) for _ in 1:4];

julia> NextLA.gemmEx_batched!('N', 'T', 1.0, A, B, 0.0, C);   # same type: allowed on the CPU

julia> all(C[i] ≈ A[i] * transpose(B[i]) for i in 1:4)
true
source
NextLA.gemmEx_batched_ptrs! — Method
gemmEx_batched_ptrs!(transA, transB, alpha, Aptrs, Aref, Bptrs, Bref, beta, Cptrs, Cref, batch_count; compute_type=...)

Internal batched GEMMEx helper that accepts device arrays of matrix base pointers. Aref, Bref, and Cref are representative matrices used only to infer the shared GEMM dimensions, element types, and leading dimensions for the pointed-to batches.

source
NextLA.gemm_batched! — Method
gemm_batched!(transA, transB, alpha, A, B, beta, C)

Compute a batched matrix product and store the result in C.

Three storage forms are supported:

  • AbstractArray{T,3} for strided batches
  • AbstractVector of matrices for pointer batches
  • backend pointer arrays plus representative matrices for explicit pointer-batch calls

Each batch entry applies

C[i] := alpha * op(A[i]) * op(B[i]) + beta * C[i]

where op(A) and op(B) are determined by transA and transB.

Notes

  • On the CPU, gemm_batched! falls back to a loop of standard GEMMs. Each member must be same-type Float32, Float64, ComplexF32 or ComplexF64; any other member throws ArgumentError.
  • GPU backends may dispatch to native pointer-batched or strided-batched GEMM kernels when available.

Examples

julia> A = rand(1024, 1024, 4); B = rand(1024, 1024, 4); C = zeros(1024, 1024, 4);

julia> gemm_batched!('N', 'N', 1.0, A, B, 0.0, C);

julia> all(C[:, :, i] ≈ A[:, :, i] * B[:, :, i] for i in 1:4)
true
source
NextLA.gemm_batched_ptrs! — Method
gemm_batched_ptrs!(transA, transB, alpha, Aptrs, Aref, Bptrs, Bref, beta, Cptrs, Cref, batch_count)

Internal batched GEMM helper that accepts device arrays of matrix base pointers. Aref, Bref, and Cref are representative matrices used only to infer the shared GEMM dimensions and leading dimensions for the pointed-to batches.

source
NextLA.set_batch_ptrs! — Method
set_batch_ptrs!(d, first, matrices)

Replace a contiguous descriptor range with the base addresses of matrices. The descriptor storage is retained; only its small address table is updated. This is used when a rolling scheduler admits a new logical member into an existing physical slot.

source
NextLA.swap_batch_ptrs! — Method
swap_batch_ptrs!(d::BatchPtrDescriptor, p::Int, q::Int, blocklen::Int)

Block form of swap_batch_ptrs! for descriptors where each logical batch member owns blocklen consecutive descriptor slots (e.g. one pointer per contraction tile of a member's factor panel, laid out member-major): swaps the two length-blocklen contiguous slot ranges [(p-1)*blocklen+1:p*blocklen] and [(q-1)*blocklen+1:q*blocklen].

source
NextLA.swap_batch_ptrs! — Method
swap_batch_ptrs!(d::BatchPtrDescriptor, p::Int, q::Int)

Swap which base address occupies descriptor slots p and q. Only the small address table moves; the numeric data the addresses point to is untouched and does not move. Use this instead of physically swapping or copying the underlying batch members when active-prefix packing retires one.

source

Grouped GEMM

NextLA.GroupedGemmTask — Type
GroupedGemmTask(transA, transB, alpha, A, B, beta, C)

One heterogeneous GEMM member. CUDA submits members through grouped GEMM; CPU executes identical semantics with a loop. Unlike gemm_batched!, members are allowed to have different m, n, and k. The task owns no storage; its matrices must remain live through the call.

source
NextLA.precision_gemm_grouped! — Method
precision_gemm_grouped!(tasks, mode)

Execute heterogeneous GEMMs. CUDA uses its native grouped primitive; CPU implements the same semantics with an ordinary GEMM loop.

Examples

julia> tasks = [NextLA.GroupedGemmTask('N', 'N', 1.0, rand(1024, 512), rand(512, 2048), 0.0, zeros(1024, 2048)),
                NextLA.GroupedGemmTask('N', 'T', 1.0, rand(2048, 1024), rand(512, 1024), 0.0, zeros(2048, 512))];

julia> NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float64}());

julia> tasks[1].C ≈ tasks[1].A * tasks[1].B && tasks[2].C ≈ tasks[2].A * transpose(tasks[2].B)
true
source
NextLA.prepare_precision_gemm_grouped — Method
prepare_precision_gemm_grouped(tasks, mode)

Build and upload the immutable pointer/group metadata for tasks. The returned descriptor retains no numerical workspace; callers must keep every referenced matrix alive until all submissions using the descriptor have completed.

source
NextLA.supports_grouped_gemm — Method

Whether a backend has the heterogeneous grouped-GEMM interface (one call over a batch of differently sized products).

Examples

julia> A = rand(1024, 1024);

julia> NextLA.supports_grouped_gemm(NextLA.get_backend(A))   # the CPU runs grouped GEMM as a loop
true
source

Tiled kernel

NextLA.GEMM_ADD! — Function
GEMM_ADD!(A, B, C, scale=1) -> C

C .+= scale * A * B. A or B may be a Transpose or an Adjoint. When A, B and C are all Float16, the sum is kept in Float32; a result beyond floatmax(Float16) is stored as Inf. Otherwise it is kept in eltype(C). Shapes that do not fit throw DimensionMismatch.

Examples

julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024);

julia> C0 = copy(C);

julia> GEMM_ADD!(A, B, C, 2.0);   # C += 2AB

julia> C ≈ C0 + 2.0 * A * B
true
source
NextLA.GEMM_SUB! — Function
GEMM_SUB!(A, B, C, scale=1) -> A

A .-= scale * B * C. Note the output is the first argument here, unlike GEMM_ADD! — both orders match the callers in src/dense/blas/trsm/rectrxm.jl. Operands, Float16 accumulation and shape checks are as for GEMM_ADD!.

Examples

julia> A = rand(1024, 1024); B = rand(1024, 1024); C = rand(1024, 1024);

julia> A0 = copy(A);

julia> GEMM_SUB!(A, B, C);   # A -= BC; the output is the first argument

julia> A ≈ A0 - B * C
true
source

Usage examples

Both argument orders of gemm! make the same update; the BLAS order takes the transposes as flags, the output-first order as transpose/adjoint wrappers.

using NextLA, LinearAlgebra

A = rand(2048, 1024)
B = rand(2048, 1024)
C1 = rand(1024, 1024)
C0 = copy(C1)
C2 = copy(C1)

gemm!('T', 'N', 2.0, A, B, 1.0, C1)                    # BLAS order: C1 = 2 Aᵀ B + C1
gemm!(C2, transpose(A), B; alpha = 2.0, beta = 1.0)    # output first, same update
C1 ≈ C2 ≈ 2.0 * transpose(A) * B + C0

# output

true

gemmEx! multiplies Float16 matrices with a Float32 accumulation and rounds once on store; recgemm! picks that accumulation by itself.

using NextLA, LinearAlgebra

A = rand(Float16, 2048, 2048)
B = rand(Float16, 2048, 2048)
C1 = zeros(Float16, 2048, 2048)
C2 = zeros(Float16, 2048, 2048)

gemmEx!('N', 'N', 1.0, A, B, 0.0, C1; compute_type = Float32)   # accumulate in Float32
recgemm!(1.0, A, B, 0.0, C2)                                    # chooses Float32 by itself
C1 ≈ C2 && isapprox(C1, Float64.(A) * Float64.(B); rtol = 1e-3)

# output

true

gemm_batched! takes a 3-D strided batch, where an operand with batch count 1 is shared by every member, or a vector of matrices.

using NextLA, LinearAlgebra

A = rand(1024, 1024, 8)
B = rand(1024, 1024, 1)        # batch count 1: one B shared by every member
C = zeros(1024, 1024, 8)
gemm_batched!('N', 'N', 1.0, A, B, 0.0, C)

As = [rand(1024, 1024) for _ in 1:4]
Bs = [rand(1024, 1024) for _ in 1:4]
Cs = [zeros(1024, 1024) for _ in 1:4]
gemm_batched!('N', 'T', 1.0, As, Bs, 0.0, Cs)

all(C[:, :, i] ≈ A[:, :, i] * B[:, :, 1] for i in 1:8) &&
    all(Cs[i] ≈ As[i] * transpose(Bs[i]) for i in 1:4)

# output

true

Grouped GEMM runs products of different shapes in one call, described by GroupedGemmTasks (a loop on the CPU, one grouped call on CUDA).

using NextLA, LinearAlgebra

shapes = [(1024, 2048, 512), (2048, 1024, 1024), (4096, 512, 1024)]   # (m, n, k) per member
tasks = [NextLA.GroupedGemmTask('N', 'N', 1.0, rand(m, k), rand(k, n), 0.0, zeros(m, n))
         for (m, n, k) in shapes]

NextLA.precision_gemm_grouped!(tasks, NextLA.GEMMCompute{Float64}())
all(t.C ≈ t.A * t.B for t in tasks)

# output

true

On the GPU the same calls reach cuBLAS: GEMMEx for mixed precision, one strided-batched call for a 3-D batch, and the TF32 tensor cores through TF32 (CUDA only). This block is not run when the documentation is built.

using NextLA, CUDA

# Float16 storage, Float32 accumulation: one cuBLAS GEMMEx call
A = CUDA.rand(Float16, 4096, 4096)
B = CUDA.rand(Float16, 4096, 4096)
C = CUDA.zeros(Float16, 4096, 4096)
gemmEx!('N', 'N', 1f0, A, B, 0f0, C; compute_type = Float32)

# a 3-D strided batch: one cuBLAS strided-batched call
Ab = CUDA.rand(Float32, 1024, 1024, 16)
Bb = CUDA.rand(Float32, 1024, 1024, 16)
Cb = CUDA.zeros(Float32, 1024, 1024, 16)
gemm_batched!('N', 'N', 1f0, Ab, Bb, 0f0, Cb)

# Float32 operands on the TF32 tensor cores (CUDA only)
X = CUDA.rand(Float32, 4096, 4096)
Y = CUDA.rand(Float32, 4096, 4096)
Z = CUDA.zeros(Float32, 4096, 4096)
NextLA.precision_gemm!('N', 'N', 1f0, X, Y, 0f0, Z, TF32())

isapprox(C, Float32.(A) * Float32.(B); rtol = 1e-3) &&
    Cb[:, :, 16] ≈ Ab[:, :, 16] * Bb[:, :, 16] &&
    isapprox(Z, X * Y; rtol = 1e-2)