The Metal backend: Apple GPUs
MTL5 runs dense float products, LU and Cholesky factorizations, and their solves on Apple GPUs through Metal and Metal Performance Shaders (MPS). It is the first backend built on the accelerator core, and the design it follows is in the accelerator backend architecture; this page covers what the Metal backend provides and how to use it. Tracked in issue 1021, under the umbrella #225.
Enabling it
Section titled “Enabling it”cmake -B build -DMTL5_WITH_METAL=ON # Apple platforms onlyMetal and MPS are Objective-C APIs, and MTL5 is header-only C++. The option builds one Objective-C++ file, src/mtl5_metal.mm, into the MTL5::metal library. A target that links MTL5::metal gets MTL5_HAS_METAL, and with it runtime::metal and the MPS dispatch in include/mtl/interface/metal.hpp. Everything else is unchanged, including code built without the option.
target_link_libraries(my_app PRIVATE MTL5::metal)Memory
Section titled “Memory”runtime::metal names its memory by a buffer and a byte offset, not a pointer: the non-pointer handles of the core (see memory spaces).
| Space | Metal storage | Host access |
|---|---|---|
memory_space::device<runtime::metal> | MTLStorageModePrivate | none: only the GPU touches it |
memory_space::shared<runtime::metal> | MTLStorageModeShared | yes, through the buffer’s contents pointer |
Apple silicon has one physical memory, so shared storage is ordinary memory that both the CPU and the GPU address. Private storage is still device-only to the program: the host has no address for it, and element access does not compile. There is no pinned<runtime::metal>, since shared storage already lets the GPU read host memory in place. Both kinds allocate zero-filled buffers. Since device memory cannot run a constructor, it holds only element types whose value is all-zero bytes: arithmetic types, enumerations, pointers and floating-point std::complex. A program opts another such type in by specializing mtl::zero_fill_is_value_init (include/mtl/memory/zero_fill.hpp).
#include <mtl/mtl.hpp>#include <mtl/interface/metal.hpp>
using dev = mtl::memory_space::device<mtl::runtime::metal>;mtl::mat::dense2D<float> A = ..., B = ...;auto dA = mtl::copy_to<dev>(A); // to the GPUauto dB = mtl::copy_to<dev>(B);auto dC = mtl::copy_to<dev>(mtl::mat::dense2D<float>(A.num_rows(), B.num_cols()));mtl::mult(dA, dB, dC); // MPSMatrixMultiplicationauto C = mtl::to_host(dC); // backcopy, copy_to and to_host move data through blits; a copy to or from shared storage is a memcpy.
Operations
Section titled “Operations”| Call | Operands | Runs as |
|---|---|---|
mult(A, B, C) | dense2D<float>, all in Metal memory, any mix of orientations | MPSMatrixMultiplication |
mult(A, x, y) | dense2D<float> and dense_vector<float>, all in Metal memory | MPSMatrixVectorMultiplication |
lu_factor(A, pivot) | dense2D<float> in Metal memory | MPSMatrixDecompositionLU |
lu_solve(LU, pivot, x, b) | the factor, and dense_vector<float>s, all in Metal memory | MPSMatrixSolveLU |
cholesky_factor(A) | dense2D<float> in Metal memory | a blocked factorization: MPSMatrixDecompositionCholesky on the diagonal blocks, MPSMatrixSolveTriangular and MPSMatrixMultiplication for the rest. With LAPACK linked, the host’s spotrf below cholesky_gpu_min_order (see below) |
cholesky_solve(L, x, b) | the factor, and dense_vector<float>s, all in Metal memory | MPSMatrixSolveCholesky |
- Placement follows the operands. A call whose operands are all in Metal memory (device or shared, mixed) runs on the GPU, with two exceptions, both under Factorizations: with LAPACK linked,
cholesky_factorof a matrix of order belowcholesky_gpu_min_orderruns on the CPU; and a factorization that MPS reports as failed, or whose factor has a pivot the host would reject, is redone by the host routine. The dispatch trace counts these calls asgemm_metal,gemv_metal,getrf_metal,getrs_metal,potrf_metalandpotrs_metal, whichever processor finishes them. Only the LAPACK hand-off ofcholesky_factoralso counts aspotrf_metal_host; a host routine redoing a failed factorization counts nothing extra. - Orientation is free. MPS reads row-major matrices; a column-major operand is its stored transpose, and the backend passes MPS the transpose flags that give the right product.
- Aliasing. A result that shares a buffer with an operand is computed through a temporary, as the host kernels do.
- Synchronous. Each call waits for its command buffer, as phase 1 of the design promises. Streams come later.
- The default accumulator only. MPS does not form each entry as one reduction, so a call with a non-void
Accumulator(mixed-precision reductions, #585) does not reach it. On operands in shared memory it takes the host routine. Operands in device memory have no such overload, so the call does not compile: copy them to host-accessible memory first.
Factorizations
Section titled “Factorizations”lu_factor and cholesky_factor return what the host routines return, and leave the same factor in A:
- The pivots are the host’s convention, which is also LAPACK’s and MPS’s: row
iwas interchanged with rowpivot[i]. A factor and pivots from the GPU solve on the host, and the reverse. - Failures are the host’s. MPS reports that a factorization failed but not at which pivot. The backend factors out of place, from a device copy of
A, and tests the factor’s diagonal as the host does (zero or NaN for LU, not positive for Cholesky). On a failure, or a rejected pivot, the host routine factors that copy instead, so the return code (k + 1for the first bad pivot) and the contents ofAare exactly the host’s. The copy costs one extran x nbuffer during the call. - Orientation. MPS reads row-major storage. A column-major LU is transposed into row-major scratch for MPS and its factor back (
MPSMatrixCopy), and each solve transposes the factor the same way. A column-major Cholesky needs no transpose:Ais symmetric, and the upper factor of its stored transpose isL^T, which lies exactly whereLlies inA. - The other triangle. The host Cholesky leaves the strictly upper triangle as it was. MPS does not document what it does there; the tests compare only the lower triangle, and
cholesky_solvereads only it. - Cholesky factors blocks (#1036). On an Apple M2,
MPSMatrixDecompositionCholeskyon the whole matrix ran at 5.9 GFLOP/s atn = 2048, against 147 for MPS’s LU and 2700 for its matrix multiply. So the backend uses MPS’s Cholesky only for the 64-wide diagonal blocks (128-wide fromn = 4096).MPSMatrixSolveTriangularforms each panel, andMPSMatrixMultiplicationupdates the trailing matrix, which holds nearly all the flops. All of it is encoded in one command buffer. Without LAPACK this ran at 112 GFLOP/s atn = 2048and 282 at 4096, in device memory. The update computes whole trailing blocks, so the strictly upper triangle of the factor is not the input’s, as before. - With LAPACK linked, small and medium orders run on the host. Accelerate’s
spotrfbeat the blocked GPU factorization on the M2 up ton = 5120(487 against 401 GFLOP/s), and lost from 6144 on (377 against 484). So belowinterface::metal::cholesky_gpu_min_order, 6144 by default, the backend copiesAto the host, factors it there, and copies the factor back. The copies are amemcpyfor shared memory and a blit for device memory. A program may setcholesky_gpu_min_orderto suit its machine; the tests set it to 0 to reach the GPU path at small orders. The dispatch trace counts the hand-off aspotrf_metal_host.cholesky_solvestays on MPS either way. - Aliasing. A solve whose
xshares a buffer withbor the factor goes through a temporary. - Size. MPS numbers pivots with 32 bits, so a larger LU throws
std::length_error. A non-square matrix in device memory throwsstd::invalid_argument. One in shared memory first meets the host routine’s assertion, as a host matrix does, so an assertion-enabled build aborts.
Precision: no FP64
Section titled “Precision: no FP64”Apple GPUs have no double precision, so runtime::metal::supports<double> is false and double operands never reach MPS.
- In shared memory, a
doublecontainer is host-accessible, and operations take MTL5’s host kernels. - In device memory, the host cannot touch it, so an operation on it does not compile. Copy it to the host (
to_host), or convert it tofloat.
Testing
Section titled “Testing”tests/unit/metal/ checks the buffers, the copies, every orientation of mult, and LU and Cholesky (factors, pivots, solves and failures) against MTL5’s host routines. A test skips itself on a machine without a Metal device, and fails instead when MTL5_REQUIRE_METAL is set.
GitHub’s hosted macOS runners expose a paravirtual Metal device that MPS supports, so CI’s macOS ARM64 Metal lane runs these tests on macos-15 and macos-26. That device reports neither the Apple7 nor the Metal3 GPU family, so features gated on those families cannot be tested there.
Not done yet
Section titled “Not done yet”- Several right-hand sides. The MPS solves take a matrix of them; the MTL5 calls solve one vector at a time.
- Streams (
stream<runtime::metal>), and the other operations: QR, eigenvalues and the SVD have no MPS kernel and would need MTL5’s own.