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!andgemmEx_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 (Float32forFloat16storage); 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.
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
trueNextLA.gemm! — Method
gemm!(transA, transB, alpha, A, B, beta, C) -> CThe 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
trueNextLA.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 defaultdefault_compute_typechooses it from the storage types ofA,BandC.alphaandbetatake no part and are converted to it. - Mixed storage and compute types are a
CUDAandAMDGPUfeature. TheCPUaccepts any combination, accumulating incompute_type.oneAPIandMetalhave nogemmEx!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)
trueNextLA.recgemm! — Method
recgemm!(alpha, A::AbstractMatrix, B::AbstractMatrix, beta, C::AbstractMatrix) -> CCompute 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,ComplexF32orComplexF64:gemm!. Float16AandBinto aFloat16orFloat32C:gemmEx!with aFloat32sum. On Metal and oneAPI, which have nogemmEx!, the same sum comes from oneFloat32gemm!on widened copies.- Other mixes: when
Cis at least as wide asAandB, the operands are widened toeltype(C)and passed togemm!. OtherwisegemmEx!sums in at leastFloat32and rounds once on store. On a GPU, whenCis narrower thanAandB, they are first rounded toeltype(C).
No transpose is applied. Sizes that do not fit throw DimensionMismatch. The method for a mixed-precision C is documented separately.
Compute types and alignment
NextLA.GEMM_COMPUTE_TYPES — Constant
GEMM_COMPUTE_TYPEScompute_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:
- Ordinary dense GEMM is
gemm!, which forwards tomul!(Float16 on the CPU and CUDA togemmEx!, for Float32 sums). gemm_batched!provides the batched GEMM surface, for many independent products.NextLA.gemmEx!andNextLA.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:
| Operation | CPU | CUDA | AMDGPU | oneAPI | Metal |
|---|---|---|---|---|---|
gemmEx! with default compute_type | BLAS, or a wide accumulation | cuBLAS GEMMEx | rocBLAS GEMMEx | throws | throws |
gemm_batched!, 3-D strided | BLAS loop, same-type BLAS types only; a batch count of 1 broadcasts | strided batched, or GEMMEx | strided batched, or GEMMEx | oneMKL strided | MPS; equal batch counts only |
gemm_batched!, vector of matrices | BLAS loop, same-type BLAS types only | pointer batched; non-native types via GEMMEx | rocBLAS batched | oneMKL batched | throws |
gemm_batched_ptrs! | throws | pointer batched | pointer batched | throws | throws |
gemmEx_batched! with default compute_type | same-type fallback only | cuBLAS batched GEMMEx | rocBLAS batched GEMMEx | same-type fallback only | same-type fallback only |
| grouped GEMM, unequal shapes | loop of precision_gemm! | grouped GEMMEx | throws | throws | throws |
| TF32 | throws | single, batched and pointer batched | throws | throws | throws |
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 storage | C storage | compute_type | CPU | CUDA | AMDGPU | oneAPI | Metal |
|---|---|---|---|---|---|---|---|
Float16 | Float16 | Float32 | unsupported | yes | yes | unsupported | unsupported |
Float16 | Float32 | Float32 | unsupported | yes | yes | unsupported | unsupported |
BFloat16 | BFloat16 | Float32 | unsupported | yes | yes | unsupported | unsupported |
BFloat16 | Float32 | Float32 | unsupported | yes | yes | unsupported | unsupported |
Int8 | Int32 | Int32 | unsupported | yes | yes | unsupported | unsupported |
Float32 | Float32 | Float32 | BLAS | yes | yes | yes | yes |
Float64 | Float64 | Float64 | BLAS | yes | yes | yes | yes |
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.
NextLA.NATIVE_GEMM_TYPES — Type
NATIVE_GEMM_TYPESElement 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.
NextLA.aligned_leading_dimension — Method
aligned_leading_dimension(T, m) -> IntSmallest 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) == 4104A 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.
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:
Float16defaults toFloat16Float32defaults toFloat32Float64defaults toFloat64- 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
trueNextLA.gemm_alignment_quantum — Method
gemm_alignment_quantum(T) -> IntNumber 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.
T | quantum |
|---|---|
Float16/BFloat16 | 8 |
Float32 | 4 |
Float64 | 2 |
See also aligned_leading_dimension, is_gemm_aligned.
Examples
julia> gemm_alignment_quantum(Float16)
8
julia> gemm_alignment_quantum(Float64) * sizeof(Float64) == 16
trueNextLA.is_gemm_aligned — Method
is_gemm_aligned(T, n) -> BoolWhether 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))
trueNextLA.GEMMCompute — Type
Request ordinary GEMM accumulation in T.
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)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
trueNextLA.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)
trueNextLA.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.
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.
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 defaultdefault_compute_typeinfers it from the element types ofA,BandConly.alphaandbetatake 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)
trueNextLA.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.
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 batchesAbstractVectorof 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-typeFloat32,Float64,ComplexF32orComplexF64; any other member throwsArgumentError. - 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)
trueNextLA.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.
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.
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].
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.
Grouped GEMM
NextLA.AbstractPreparedGroupedGemm — Type
Opaque backend-owned descriptor for a prepared grouped-GEMM submission.
NextLA.CPUPreparedGroupedGemm — Type
CPU prepared group: retain task views and replay them with ordinary GEMMs.
NextLA.GroupedGemmKey — Type
Typed, allocation-free-to-compare key used while constructing GEMM groups.
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.
NextLA.PreparedGroupedGemmBundle — Type
Prepared aligned groups plus ordinary-GEMM fallback members.
NextLA.destroy_prepared_grouped_gemm! — Method
Release device metadata owned by a prepared descriptor.
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)
trueNextLA.precision_gemm_grouped_prepared! — Method
Submit a prepared group, replacing every group's scalar pair in place.
NextLA.precision_gemm_grouped_prepared! — Method
Submit a prepared group using the scalars captured during preparation.
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.
NextLA.supports_bfloat16_grouped_gemm — Method
Whether this backend/device has native BF16 grouped GEMMEx support.
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
trueNextLA.with_grouped_host_pointer_mode — Method
Run f while grouped-GEMM scalar arrays are interpreted as host memory.
Tiled kernel
NextLA.GEMM_ADD! — Function
GEMM_ADD!(A, B, C, scale=1) -> CC .+= 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
trueNextLA.GEMM_SUB! — Function
GEMM_SUB!(A, B, C, scale=1) -> AA .-= 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
trueUsage 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
truegemmEx! 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
truegemm_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
trueGrouped 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
trueOn 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)