Skip to content

Accelerator backends: memory, transfers, execution and dispatch

Status: accepted (names decided 2026-12-01). This is the design note that #1017 asks for before any accelerator backend’s code lands. It is the shared core of the backends tracked in #225: CUDA (#1018), AMD (#1019), Intel (#1020), Apple (#1021), Qualcomm (#1022) and domain flow on the KPU (#251). The names were settled with the maintainer; Decided names records each choice and the alternatives it beat.

MTL5 already knows where a container’s elements live. Memory spaces (#223) made the space a template argument of every dense container and of compressed2D. They are the storage layer. Every accelerator backend needs four more things on top of it, and if each backend invents its own, they will not agree:

  1. Which programming model owns an allocation. A CUDA pointer is not a HIP, SYCL, Metal, OpenCL or domain-flow buffer. A single memory_space::device would let dispatch hand one model’s memory to another model’s library.
  2. A handle that is not always a pointer. Metal, OpenCL and Vulkan buffers are objects with an offset, not addresses.
  3. Moving data between spaces. Explicit, because an implicit copy across PCIe inside an expression is a performance trap.
  4. Choosing where an operation runs, and refusing at compile time an operation whose operands cannot meet anywhere.

This page decides each of them, names the pieces, and compares the result with the two designs MTL5 should track: Kokkos and C++26 std::linalg.


The names matter because they end up in every user’s type aliases. Four rules shaped them:

  1. No vendor name in the vocabulary. A memory space describes how memory behaves: who can touch it and how it is allocated. Memory kinds, concepts, transfer functions, streams and dispatch predicates carry no company or product name.
  2. The programming model is named exactly once, where it is unavoidable: the runtime tag. A backend links a specific programming model and its API (CUDA, HIP, SYCL, Metal, OpenCL, Vulkan, domain flow), just as MTL5_WITH_BLAS links a specific library. That tag is the one place the model is named, it is a type argument rather than part of a space’s name, and application code need not spell it at all (see runtime::preferred).
  3. Name the programming model, not the hardware. A runtime tag names how a device is programmed, not the chip that executes it: CUDA rather than “NVIDIA GPU”, and domain flow rather than “KPU” (see Domain flow and the KPU).
  4. Name the property, not the product. “Device memory the host cannot touch” is the same idea on every GPU, so it is one name, device, parameterized by the runtime that allocated it.
  5. Prefer a name the C++ standard or an established library already uses for the same idea, and say where MTL5’s meaning differs.
NameWhat it isReplaces or extends
memory_space::hostPageable host memory, MTL5’s defaultunchanged
memory_space::device<R>Memory only runtime R’s devices can touchtoday’s memory_space::device
memory_space::shared<R>Memory the host and R’s devices can both address, under R’s ordering rules (managed, shared or integrated memory)today’s memory_space::unified, renamed
memory_space::pinned<R>Host memory page-locked by R, so transfers can be DMA’d and overlappednew
DeviceRuntimeConcept: a runtime tag R (allocation, transfer, streams, capabilities)new
runtime::cuda, hip, sycl, metal, opencl, vulkan, domain_flowThe runtime tags, one per programming model, each defined by its backend headernew
runtime::preferredThe build’s chosen runtime: an alias for one of the tagsnew
runtime::emulatedA host-backed test runtime whose memory the host may not touchnew (tests)
stream<R>An in-order sequence of work on one device of runtime Rnew
copy(src, dst) / copy(s, src, dst)Element-exact transfer between any two spaces, blocking or ordered on a streamnew
copy_to<Space>(x), to_host(x)A new owning container holding x’s elements in Space (or host memory)new
std::execution::seq, par as a first argumentRun an operation on the host, overriding placementnew use of standard names
handle_type<T>What a space stores to name its storage: T* by defaultnew
runtime_of_t<M>, same_runtime_v<Ms...>, runtime_supports_v<R, T>Dispatch predicatesextends memory_space_t, in_memory_space_v

Memory spaces: kind and runtime are separate axes

Section titled “Memory spaces: kind and runtime are separate axes”

A memory space answers two independent questions, and the design keeps them apart:

  • The kind: can the host touch it, can a device touch it, is it page-locked. This decides what code may do with the memory, and MTL5 already checks it at compile time: element access, iterators and filling constructors require host_access (#223).
  • The runtime: which device API allocated it, and therefore which libraries and kernels may receive it. This decides dispatch.

So a space is a kind applied to a runtime:

namespace mtl::memory_space {
struct host; // as today: host_accessible, allocates
template <DeviceRuntime R = runtime::preferred> struct device; // device only
template <DeviceRuntime R = runtime::preferred> struct shared; // host and device both address it
template <DeviceRuntime R = runtime::preferred> struct pinned; // host, page-locked by R
}
Kindhost_accessibledevice_accessibleAllocated byExamples
hostyesnonew (over-aligned)today’s default
pinned<R>yesDMA onlyRcudaMallocHost, hipHostMalloc
device<R>noyesRcudaMalloc, hipMalloc, sycl::malloc_device, private Metal or OpenCL buffers, KPU memory under domain flow
shared<R>yesyesRcudaMallocManaged (Jetson), hipMallocManaged (APUs), sycl::malloc_shared, MTLStorageModeShared (Apple)

Each space keeps the members #223 defined (host_accessible, device_accessible, name, and for an allocating space allocate<T> and deallocate<T>), and adds using runtime = R;. host has no device runtime. The existing compile-time checks therefore keep working unchanged: device<R> fails host_access exactly as device does today.

Why a template rather than one space per API. The alternative, cuda_device, hip_device, sycl_device and so on, as #1017 first sketched, puts a vendor name into every space and multiplies the kinds by the runtimes. With a template, adding a runtime adds one tag, and every kind, concept, rule and test applies to it at once.

Integrated GPUs need no special case. On the Jetson, an AMD APU or an Apple M-series chip, shared<R> is the natural space: the host and the device share physical memory, and the same rules apply as for managed memory on a discrete card. Only performance differs.

shared does not promise concurrent access. On the Jetson, for example, the host must not touch managed memory while a GPU kernel runs. So shared<R> means that both sides can address the memory, under R’s ordering rules: the host touches it only when no device work writing it is in flight (see Ordering). It does not mean coherent at every instant.

Why shared and not unified. shared is the name SYCL (malloc_shared), Kokkos (SharedSpace), Metal (MTLStorageModeShared) and OpenCL (shared virtual memory) use. unified mixes up a hardware fact (one physical memory, as on Apple’s “unified memory architecture”) with a programming model (one address both sides may use). They don’t line up: a private Metal buffer on an M-series Mac sits in physically unified memory, yet the CPU cannot touch it, so it is device<runtime::metal>. managed, the CUDA and HIP API word, implies a driver that migrates pages, which integrated parts don’t do. The cost of shared is that CUDA and HIP programmers also use “shared memory” for the on-chip scratchpad of a thread block. MTL5 never exposes that scratchpad, and the name is always qualified as memory_space::shared<R>.

One device per runtime, for now. A space names a runtime, not a particular device of it. Phase 1 uses the runtime’s current device, and a handle may later carry a device index. A system with two GPUs of one runtime is out of scope until a backend needs it.

runtime::preferred is an alias for the runtime the build selected (MTL5_ACCELERATOR=cuda, hip, …, or the only one enabled). It is also the default argument of every kind. So application code written against the kinds compiles unchanged on any backend:

using gpu_matrix = mat::dense2D<float, mat::parameters<tag::row_major, index::c_index,
non_fixed::dimensions, tag::on_heap, std::size_t,
memory_space::device<>>>; // whichever runtime the build chose

Code that targets one runtime on purpose, such as a test of the CUDA backend, writes memory_space::device<runtime::cuda>. In a build that enables no accelerator, runtime::preferred is runtime::none, which does not satisfy DeviceRuntime. So naming device<> there is a compile error, not host memory relabelled, while code that never names it compiles as before.

A runtime tag is an empty type, defined by its backend’s header in include/mtl/interface/ and guarded by that backend’s MTL5_WITH_*. The DeviceRuntime concept collects what the core needs from it:

MemberPurpose
nameDiagnostics and benchmark provenance
allocate<Kind, T>(n), deallocate<Kind, T>(h, n)Allocation for each kind the runtime supports; a kind it lacks is a compile error
device_handle<T>, shared_handle<T>, offset(h, i), address(h), overlaps(a, b, bytes)How the runtime names storage, when not by a pointer (next section)
copy_bytes(q, src, dst, bytes)The transfer primitive copy is built on
stream_type, default_stream(), wait(s)Ordering and completion
supports<T>Whether the runtime’s devices can compute in T (see Precision)
Runtime tagProgramming modelLibraries or engine a backend callsKindsIssue
runtime::cudaCUDAcuBLAS, cuSOLVER, cuSPARSEall four#1018
runtime::hipHIProcBLAS, hipSOLVER/rocSOLVERall four#1019
runtime::syclSYCL (Level Zero)oneMKL SYCL interfacedevice, shared, pinned (USM)#1020
runtime::metalMetalMetal Performance Shadersdevice (private), shared (shared storage mode)#1021
runtime::openclOpenCLCLBlast; MTL5’s own kernelsdevice, shared (SVM, where present)not chosen for #1022
runtime::vulkanVulkan computeMTL5’s own kernelsdevice, shared#1022 (chosen 2026-12-03)
runtime::domain_flowDomain flowthe KPU (four-precision API)device at least#251

HIP can also target NVIDIA hardware. Whether the CUDA backend is written through HIP is #1019’s decision. It does not change these names: memory allocated through HIP is runtime::hip memory whatever the hardware underneath.

contiguous_memory_block stores a Value*. That is right for host, CUDA, HIP, SYCL USM and Apple shared memory. It is wrong for a private Metal buffer, an OpenCL cl_mem or a Vulkan VkBuffer, which are objects addressed by an offset.

The design follows std::mdspan. An mdspan accessor policy defines a data_handle_type, which the standard requires only to be copyable, nothrow movable and nothrow swappable; it need not be a pointer or dereferenceable. An offset(p, i) produces the handle for element i. MTL5 adopts the same contract:

  • A space defines handle_type<T>, defaulting to T*. The block stores a handle_type<T> instead of a Value*.
  • The space defines offset(h, i), which views and sub-matrices use instead of pointer arithmetic. For a pointer it is h + i; for a Metal buffer it is {buffer, byte_offset + i * sizeof(T)}.
  • data() returns the handle. For every space whose handle is T* that is the pointer data() returns today, so host code is unchanged.
  • Element access still requires host_access. A shared Metal buffer is host-accessible through its contents pointer, so its handle carries both.

Following mdspan’s contract rather than inventing one means a container’s handle can become the data handle of an std::mdspan directly (see Interoperability).

Every transfer is explicit. Containers convert implicitly only between host-accessible spaces (#1012). Everything else goes through one of three functions:

copy(src, dst); // blocking: when it returns, dst holds src's elements
copy(s, src, dst); // ordered on stream s; complete after the next wait(s)
auto d = copy_to<memory_space::device<>>(h); // a new owning container in the device space
auto h2 = to_host(d); // copy_to<memory_space::host>(d)
  • copy(src, dst), source first. It matches std::linalg::copy(x, y), which copies x into y, and the order MTL5 users already read in std::copy. Kokkos’s deep_copy(dst, src) puts the destination first; MTL5 follows the standard rather than Kokkos.
  • Shapes and value types must match, as for std::linalg::copy: same value type, same dimensions, same orientation and index base. A transfer is not a conversion. Changing layout or element type is a separate step on one side or the other.
  • A transfer is element-exact. It moves bytes, so T must be trivially copyable. That is what lets domain flow carry posits, LNS or fixed-point values to the KPU: copy never interprets them. Quantization, the input and output types of #251’s four-precision API, is an operation, not a transfer.
  • A non-owning target is written through, and a size mismatch throws, as in #1012’s assignment and the zero-copy overlay policy (#829).

No silent alias. Kokkos’s create_mirror_view returns a new host allocation, or the original view when the host can already reach the data. Code that needs an independent copy then mutates the original on shared memory. MTL5 has no such function:

  • to_host(x) always copies.
  • No copy is needed for host access to shared<R> or pinned<R> memory: those containers are host-accessible, so element access works on them directly. A device<R> container has no host access at all, and to_host is the only way to bring its elements to the CPU.

MTL5 has no separate execution-space parameter. The operands’ spaces decide where an operation runs, by one rule applied at compile time:

  1. On the device, when every operand is device-accessible to one runtime R (in device<R> or shared<R>), and R’s backend implements the operation for the value type.
  2. On the host, when every operand is host-accessible (host, pinned<R>, shared<R>). This is today’s behaviour, and the generic kernels are its floor.
  3. Otherwise, a compile error that names the spaces: a device<R> operand with a host one, or operands on two runtimes. No transfer is inserted.

Rule 1 is tried before rule 2. So shared<R> operands go to R’s library when it has the routine, and to the host kernels when it does not, which gives integrated GPUs every operation from day one.

Why no execution space. Kokkos separates memory spaces from execution spaces and asks SpaceAccessibility<Exec, Mem> whether they can meet, because its users write kernels and choose where each runs. MTL5’s users call operations, and the library chooses. The operands already say where the data is, and a second parameter would only add combinations to reject. A user who wants a different placement says so with a first argument, below.

An operation takes an optional first argument that states where it runs, as std::linalg takes an execution policy:

mult(A, x, y); // the placement rule decides
mult(s, A, x, y); // ordered on stream s, on its device
mult(std::execution::par, A, x, y); // on the host, threaded
mult(std::execution::seq, A, x, y); // on the host, sequential
  • A standard execution policy means the host. seq runs the host rungs single-threaded, par lets them use MTL5’s thread pool. Every operand must be host-accessible; a device<R> operand is a compile error. Reusing the standard’s policy objects adds no MTL5 name, and gives MTL5’s existing host threading a standard spelling.
  • A stream means its device. Every operand must be device-accessible to the stream’s runtime.
  • No argument means the placement rule. This is the common case, and today’s code is unchanged by it.

Phase 1 is synchronous. Every device operation and every copy without a stream returns only when its work is complete. That keeps two rules simple: shared memory is safe for the host to read after any MTL5 call, and exceptions are thrown where the error happened.

Streams come next. stream<R> is an in-order sequence of device work: work submitted to one stream runs in submission order, and work on different streams may overlap. It wraps the programming model’s ordering object: a CUDA or HIP stream, an in-order SYCL queue, a Metal or OpenCL command queue, a Vulkan queue with the barriers that make it in-order, or a domain-flow work sequence. Operations and copies that take a stream as their first argument are ordered on it and return immediately, as with an execution policy in the standard algorithms. wait(s) completes them.

stream<> s0, s1; // two in-order sequences on the device
for (std::size_t k = 0; k < tiles; ++k) { // upload tile k+1 while tile k multiplies
auto& s = (k % 2 == 0) ? s0 : s1;
copy(s, h_tile[k], d_tile[k]); // upload tile k
mult(s, d_tile[k], d_B, d_out[k]); // after the upload: same stream
copy(s, d_out[k], h_out[k]); // after the multiply
}
wait(s0); wait(s1);
stream<> upload, compute; // a dependency between two streams
copy(upload, h_A, d_A);
compute.wait_for(record(upload)); // compute does not pass this point before the upload
lu_factor(compute, d_A, d_piv);
stream<runtime::cuda> adopted(my_cuda_stream); // adopt the application's native object

Until a wait, the host must not touch shared memory that in-flight work writes; this is the same contract as Kokkos’s asynchronous deep_copy, which is ordered only with respect to its execution-space instance.

Why stream and not queue. Every example above depends on the in-order guarantee, and stream is the word that promises it: CUDA and HIP streams are always in order. A queue promises only a submission point. A sycl::queue is out of order unless created in_order, and Vulkan queue submissions may overlap without semaphores or barriers, so a SYCL or Vulkan programmer reading queue<R> would reasonably assume the wrong semantics. stream<runtime::sycl> therefore requires, or creates, an in-order sycl::queue. The cost is that “stream” also means iostreams, which mtl::io uses throughout; documentation writes it as mtl::stream<R>.

Toward std::execution. C++26’s senders and receivers order asynchronous work through schedulers, and NVIDIA’s implementation (stdexec) builds them on CUDA streams. A later get_scheduler() on stream<R> would let MTL5’s ordering compose with standard asynchronous code.

The dispatch ladders of the operation dispatch layer keep their structure: a compile-time if constexpr ladder, with an ordered preference and a generic floor. Device backends add rungs above the host ones, keyed on new predicates in dispatch_traits.hpp:

template <class M> using runtime_of_t = typename memory_space_t<M>::runtime; // none for host
template <class... Ms> inline constexpr bool same_runtime_v = /* all operands on one runtime */;
template <class R, class T> inline constexpr bool runtime_supports_v = R::template supports<T>;
// in mult(A, B, C):
#ifdef MTL5_HAS_CUDA
if constexpr (CudaDenseMatrices<A, B, C>) { interface::cublas::gemm(A, B, C); return; }
#endif
// ... other runtimes ...
// host rungs, unchanged: BLAS, SIMD, threaded, generic

The device concepts (CudaDenseMatrices and its siblings) live in each backend’s header, as BlasDenseMatrix does for BLAS. Each requires same_runtime_v, device accessibility, a value type the library takes (float, double, their complex forms), and runtime_supports_v. No operand of one runtime can satisfy another runtime’s concept, which is #225’s rule that a mismatched space fails to compile.

Many devices have no FP64: Apple GPUs, most Adreno parts, Intel Arc A-series. The rule depends on the memory kind:

  • shared<R>: a double operation falls through to the host rungs. The data is host-accessible, so this is correct, and only slower.
  • device<R>: there is no host path, since the host cannot read the data. It is a compile error when R::supports<double> is known false at compile time (Metal). Where support varies by device (Intel Xe), supports answers at run time and the operation throws.

Vendor libraries take float and double only. A posit, LNS or other custom type never satisfies a vendor library’s concept, so it takes the host generic path on host-accessible data. On device<R> data that is a compile error, not a hidden transfer.

MTL5’s own device kernels (needed for OpenCL or Vulkan on Adreno, #1022) are the one place custom types could run on a GPU. Whether they should, and how that overlaps with domain flow on the KPU, is #1022’s question.

Domain flow is the backend built for them. Its dispatch gate is not “a BLAS scalar”; it is “the operands are runtime::domain_flow memory and the precision tuple (input, arithmetic, accumulation, output) is realizable on the fabric” (#251). Two requirements on this core follow from that:

  • Nothing in the core assumes an IEEE value type. Spaces, handles, copy and streams are all value-type agnostic.
  • The four-precision policy, precision_policy<Input, Arithmetic, Accumulate, Output>, belongs to the operation, not to the memory space or the transfer, so the same device<runtime::domain_flow> buffer can serve calls with different arithmetic and accumulation types.

The KPU is an execution engine, as a GPU is. CUDA, HIP, SYCL, Metal, OpenCL and Vulkan are programming models with an API, and the runtime tags name those. The KPU’s programming model is domain flow, so its tag is runtime::domain_flow, and the KPU is the hardware a domain-flow backend executes on.

Domain flow names the methodology at more than one level, and both levels matter to MTL5:

  • Inside the fabric: domain flow keeps the structure of aggregates as they move through a data-flow machine, so they move with less energy. The KPU is the engine that makes this possible.
  • Across tiles: a problem larger than the KPU’s compute fabric runs as a sequence of tiles, and domain flow describes that sequence too. That level sits close to MTL5: the block-recursive recursion/matrix_recursator.hpp is the natural place to generate it (#251).

Naming the programming model rather than the chip has three consequences:

  • The tag outlives one chip. Another engine that executes domain flow, such as a simulator, an FPGA build or a later KPU, is another device of the same runtime, not a new runtime.
  • A host emulation of domain flow is a natural test runtime, in the way runtime::emulated stands in for GPUs.
  • A stream<runtime::domain_flow> orders operations, each of which the backend may run as its own tile sequence. The stream’s in-order guarantee applies between operations; the schedule of tiles within an operation belongs to the domain-flow backend.

std::mdspan (C++23) is the standard’s view of a multidimensional array, and std::linalg (C++26) is its BLAS. MTL5 targets C++20, so neither can be a dependency. MTL5 can still make its containers usable with them where the standard library provides them:

  • as_mdspan(A) returns an std::mdspan over a dense2D or dense_vector, with layout_right or layout_left from the orientation and the default accessor. It exists when __cpp_lib_mdspan is defined and the space is host-accessible.
  • A device space’s mdspan would use an accessor whose data_handle_type is the space’s handle. With handles following mdspan’s contract, that accessor is small. Whether to provide it waits for a standard library or toolchain that dispatches std::linalg on device data.
  • NVIDIA’s HPC SDK already runs std::linalg on GPUs. Release 26.3 took <mdspan> and <linalg> out of experimental, and with -stdpar they run on cuBLAS (GPU) or OpenBLAS/NVPL (multicore CPU). For shared<runtime::cuda> data, as_mdspan plus std::linalg with an execution policy is a second route to the GPU that MTL5 can benchmark against its own CUDA backend.

GitHub’s hosted runners have no GPUs (the macOS ARM64 runners might expose Metal; #1021 will find out). So the core is tested on the host:

  • runtime::emulated, in the tests, allocates host memory but declares device<emulated> not host-accessible. Its copy_bytes is memcpy, and its stream records the order of submitted work. Every rule on this page — placement, the compile errors for mixed runtimes and for host access, copy’s shape checks, the placement argument’s constraints, handles with offsets — runs against it on every CI lane.
  • Compile-fail tests, as in tests/unit/compile_fail/, pin each rejected combination.
  • A second emulated runtime with a non-pointer handle exercises the handle path before Metal or OpenCL exist.
  • Each backend issue owns its self-hosted runner, or a documented manual run, plus a compile-only lane in hosted CI.
Kokkosstd::linalg / std::mdspanMTL5 (this design)
Where data livesView<T, Layout, MemorySpace>; one space per vendor kind (CudaSpace, CudaUVMSpace, HIPSpace, HIPManagedSpace, SYCLDeviceUSMSpace, SYCLSharedUSMSpace, …)Not modelled. An mdspan’s accessor decides how a handle is dereferencedContainer parameter: a kind applied to a runtime, device<R>, shared<R>, pinned<R>, host
Vendor-neutral “shared memory”Kokkos::SharedSpace, an alias to the backend’s shared space—shared<> with runtime::preferred
Where code runsExecution spaces, separate from memory spaces; SpaceAccessibility<Exec, Mem>An execution policy argumentDerived from the operands’ spaces; an optional first argument (a stream, or a standard execution policy for the host) overrides it
Non-pointer handlesViews hold pointersdata_handle_type, need not be a pointerhandle_type<T>, mdspan’s contract
Transfersdeep_copy(dst, src), optionally on an execution-space instancecopy(x, y) copies x into y; no notion of spacescopy(src, dst), optionally on a stream<R>; shapes must match
Host mirrorcreate_mirror_view (aliases when host-accessible), create_mirror (always copies)—to_host (always copies); shared and pinned memory need no mirror
AsynchronyExecution-space instances; ordered per instanceExecution policiesSynchronous in phase 1; then stream<R> overloads, in order per stream
Vendor librariesKokkos Kernels: native kernels, or cuBLAS/rocBLAS/oneMKL TPLs per routineImplementation’s choice (NVIDIA: cuBLAS)interface/ backends per runtime, in the compile-time ladder
Custom number typesTemplates over T; no special supportTemplates over the element type; no special supportGeneric host path; domain flow on the KPU for device execution (#251)
Mismatched operandsRun-time error, or a compile error for an inaccessible execution spaceUndefined behaviourCompile error
  • Memory spaces as a type parameter of the container, with per-API managed or shared variants: Kokkos’s design, already adopted in #223.
  • A portable name for shared memory: Kokkos’s SharedSpace idea and name, as shared<>.
  • Explicit transfers, ordered per stream: Kokkos’s deep_copy semantics.
  • Handles: mdspan’s data_handle_type contract.
  • Argument order and shape rules of copy: std::linalg::copy.
  • Per-routine coverage tables for each backend: Kokkos Kernels documents which vendor library implements which routine, and MTL5’s backend docs should do the same.
  • No vendor names in spaces. Kokkos names each space after its backend (CudaSpace). MTL5 names the kind and passes the runtime as an argument, so the kinds and rules are written once.
  • No execution spaces. Kokkos users write kernels; MTL5 users call operations. The operands’ spaces carry enough information to place them.
  • No aliasing mirror. create_mirror_view’s alias-or-copy is replaced by to_host, which always copies; host-accessible memory needs no mirror.
  • Mismatches fail at compile time. MTL5’s dispatch is compile-time throughout (see the dispatch layer), so a CUDA operand reaching rocBLAS is a type error, not a run-time check.
  • Custom number types are a design goal, which neither reference has. That is why the core is value-type agnostic and the four-precision policy lives on the operation.

Metal (#1021) was the first backend built on this core. Its layer is short: two MPS products, buffers and copies in a few hundred lines. Most of that brevity comes from the core, which had already settled memory kinds, handles, copy and dispatch, so a CUDA backend written against it should be as short. Metal’s own design still offers lessons for the parts of the core that are not built yet.

What to emulate:

  • Storage mode is a property of the allocation. Metal fixes private or shared storage when a buffer is created, not per access. That is the memory-kind design (device<R>, shared<R>), and it is why the Metal mapping needed no adaptation.
  • Operation objects configured once, run many times. An MPSMatrixMultiplication fixes its shape and transpose flags at creation and is then encoded as often as needed; MTL5 creates one on every call. A plan object for repeated operations of one shape (as FFTW plans or cuBLASLt descriptors) would remove that per-call cost on every backend.
  • The command buffer is the unit of submission. Metal batches many operations into one command buffer and reports completion and errors on it, not per call. Phase 1 waits after every operation, the slow pattern. stream<R> should follow Metal here: batched submission, a completion callback, and errors attached to the batch.
  • A layout descriptor separate from the buffer. An MPSMatrix is a buffer, an offset and a descriptor (rows, columns, row stride). Keeping the stride apart from the shape is what makes sub-matrix views and padded layouts free. dense2D has no padding and passes its stride implicitly; a separate descriptor would let device views of sub-matrices work without copies.
  • Few concepts: device, queue, buffer, encoder. A small contract is easy to implement and to review, which argues for keeping DeviceRuntime small as backends are added.

What not to emulate:

  • The Objective-C boundary. Metal forces a compiled shim (MTL5::metal); CUDA, HIP and SYCL backends can stay header-only C++.
  • Single-vendor assumptions. Unified memory makes Metal’s shared storage cheap. A discrete GPU’s managed memory is not, so shared<R> must not promise Metal’s performance everywhere.

What Metal taught the implementation: a blit’s offsets and size must be multiples of four bytes on macOS, work sent to a nil command buffer or encoder is silently dropped, and a C++ caller has no autorelease pool. Each was found in review before the first GPU run, and each is handled in src/mtl5_metal.mm.

  • memory_space::device becomes a template, and memory_space::unified becomes memory_space::shared. Today both are plain structs without allocators, used only to describe memory and in tests (tests/unit/detail/test_memory_space.cpp and four compile-fail tests). They become device<R> and shared<R>. Code that names them changes to device<> or device<runtime::emulated>. Since nothing could allocate in them, no stored data is affected. It is a breaking change, so it ships in a MINOR release.
  • contiguous_memory_block stores a handle_type. For every space whose handle is T*, which is every space a real runtime provides today, the layout and code are the same.
  • interface::in_memory_space_v and host_resident_v are unchanged. The new predicates sit beside them.
  1. The core (#1017), synchronous only and tested on the host, in three parts:
    • Done: the kinds as templates (device<R>, shared<R>, pinned<R>), DeviceRuntime, runtime::none and runtime::preferred, copy, copy_to, to_host, the dispatch predicates (runtime_of_t, same_runtime_v, runtime_supports_v), and their compile errors. The emulated runtimes live in tests/unit/detail/emulated_runtime.hpp.
    • Done: handle_type in contiguous_memory_block. A runtime declares device_handle<T> and shared_handle<T> (pinned memory keeps a pointer), with offset(h, i), address(h) for shared memory, and copy_bytes overloads for each pair it copies between; overlaps(a, b, bytes) lets copy reject overlapping views in one device space. detail::handle_traits<Space, T> gives pointers and handles one interface, and buffer_emulated in the tests names its memory by a buffer object and a byte offset.
    • Next: the host execution-policy argument on the operations, and the placement rule once a backend gives it a device rung.
  2. The first backend: Metal (#1021). Hosted macOS runners run Metal and MPS (a probe on macos-15 and macos-26 ran an MPS sgemm exactly), so it is tested in CI, and it exercises the non-pointer handles first.
    • Done: runtime::metal (private and shared buffers), copies, and mult (matrix and vector products) through MPS; see the Metal backend.
    • Done: lu_factor, lu_solve, cholesky_factor and cholesky_solve through MPS. Two kinds of failure are kept apart. A numerical one (MPS’s status reports a failed factorization, or the factor has a pivot the host would reject) falls back to the host routine, so codes and factors match the host’s. A runtime error (no command buffer, a failed allocation, an MPS object that could not be made) throws std::runtime_error, in the factorizations and the solves alike.
  3. CUDA (#1018). Header-only over the CUDA runtime, cuBLAS and cuSOLVER, built by the host compiler.
    • Done: runtime::cuda (device, shared and pinned memory), copies, mult, LU and Cholesky for float and double; see the CUDA backend. The operations now dispatch through interface/device_dispatch.hpp, which names no backend, and the factorizations share interface/device_fallback.hpp.
    • Next: a run on an NVIDIA GPU (a cloud instance, or the Jetson); CI compiles and loads the tests only.
  4. HIP (#1019). AMD GPUs through rocBLAS and rocSOLVER, header-only like CUDA. Written directly against ROCm rather than sharing a HIP code path with NVIDIA: runtime::hip and runtime::cuda stay separate runtimes behind one dispatch layer.
    • Done: runtime::hip (device, shared and pinned memory), copies, mult, LU and Cholesky for float and double; see the HIP backend.
    • Next: a run on an AMD GPU (a cloud instance on ROCm’s support list, or a Ryzen NUC’s 780M with the gfx1100 override); CI compiles and loads the tests only.
  5. Streams: stream<R> and the stream overloads, once one backend shows where asynchrony pays.
  6. Vulkan for Qualcomm Adreno (#1022). Vulkan compute was chosen over OpenCL for the first target, an Adreno 623 on Mesa’s Turnip driver; the reasons are in the Vulkan backend. There is no vendor library, so the kernels are MTL5’s own GLSL shaders.
    • Done: runtime::vulkan (device and shared memory, named by a buffer and an offset), copies, and mult for float in every orientation; tested on the Adreno 623 and, in CI, on Mesa’s lavapipe.
    • Next: faster shaders, benchmarks, and LU and Cholesky as MTL5’s own shaders.
  7. The remaining backends (#1020) and domain flow on the KPU (#251), independently.
  8. mdspan interoperability, host-accessible first.

Settled with the maintainer on 2026-12-01:

QuestionDecidedAlternatives considered
Memory spaceskinds over a runtime: host, pinned<R>, device<R>, shared<R>one space per vendor (cuda_device, hip_device, …), as Kokkos does
Shared host–device memorysharedunified (today’s name; confuses hardware with programming model), managed (implies page migration)
The ordering objectstream<R>, in orderqueue<R> (SYCL and Vulkan queues are not in order), executor<R>
The KPU’s runtime tagruntime::domain_flow: the programming model, not the engineruntime::kpu
The runtime axisruntime, with the concept DeviceRuntimeplatform (OpenCL’s and SYCL’s word), device_api, backend (already used for BLAS/LAPACK)
Page-locked host memorypinned<R>host_pinned (Kokkos CudaHostPinnedSpace), staging
The build’s chosen runtimeruntime::preferredruntime::default_device, runtime::accelerator
Where the runtime tags livemtl::runtime, each defined by its backend headermtl::interface::<api>::runtime
Running on the host on purposea standard execution policy as the first argumenthost_view(x), a re-typed view of each operand (dropped)
The four-precision policy (#251)precision_policy<Input, Arithmetic, Accumulate, Output>kpu_precision (names the hardware)