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:
- Which programming model owns an allocation. A CUDA pointer is not a HIP, SYCL, Metal, OpenCL or domain-flow buffer. A single
memory_space::devicewould let dispatch hand one model’s memory to another model’s library. - A handle that is not always a pointer. Metal, OpenCL and Vulkan buffers are objects with an offset, not addresses.
- Moving data between spaces. Explicit, because an implicit copy across PCIe inside an expression is a performance trap.
- 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.
Naming principles
Section titled “Naming principles”The names matter because they end up in every user’s type aliases. Four rules shaped them:
- 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.
- 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_BLASlinks 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 (seeruntime::preferred). - 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).
- 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. - Prefer a name the C++ standard or an established library already uses for the same idea, and say where MTL5’s meaning differs.
The vocabulary
Section titled “The vocabulary”| Name | What it is | Replaces or extends |
|---|---|---|
memory_space::host | Pageable host memory, MTL5’s default | unchanged |
memory_space::device<R> | Memory only runtime R’s devices can touch | today’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 overlapped | new |
DeviceRuntime | Concept: a runtime tag R (allocation, transfer, streams, capabilities) | new |
runtime::cuda, hip, sycl, metal, opencl, vulkan, domain_flow | The runtime tags, one per programming model, each defined by its backend header | new |
runtime::preferred | The build’s chosen runtime: an alias for one of the tags | new |
runtime::emulated | A host-backed test runtime whose memory the host may not touch | new (tests) |
stream<R> | An in-order sequence of work on one device of runtime R | new |
copy(src, dst) / copy(s, src, dst) | Element-exact transfer between any two spaces, blocking or ordered on a stream | new |
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 argument | Run an operation on the host, overriding placement | new use of standard names |
handle_type<T> | What a space stores to name its storage: T* by default | new |
runtime_of_t<M>, same_runtime_v<Ms...>, runtime_supports_v<R, T> | Dispatch predicates | extends 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 onlytemplate <DeviceRuntime R = runtime::preferred> struct shared; // host and device both address ittemplate <DeviceRuntime R = runtime::preferred> struct pinned; // host, page-locked by R
}| Kind | host_accessible | device_accessible | Allocated by | Examples |
|---|---|---|---|---|
host | yes | no | new (over-aligned) | today’s default |
pinned<R> | yes | DMA only | R | cudaMallocHost, hipHostMalloc |
device<R> | no | yes | R | cudaMalloc, hipMalloc, sycl::malloc_device, private Metal or OpenCL buffers, KPU memory under domain flow |
shared<R> | yes | yes | R | cudaMallocManaged (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.
Application code names no API
Section titled “Application code names no API”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 choseCode 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.
Runtimes
Section titled “Runtimes”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:
| Member | Purpose |
|---|---|
name | Diagnostics 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 tag | Programming model | Libraries or engine a backend calls | Kinds | Issue |
|---|---|---|---|---|
runtime::cuda | CUDA | cuBLAS, cuSOLVER, cuSPARSE | all four | #1018 |
runtime::hip | HIP | rocBLAS, hipSOLVER/rocSOLVER | all four | #1019 |
runtime::sycl | SYCL (Level Zero) | oneMKL SYCL interface | device, shared, pinned (USM) | #1020 |
runtime::metal | Metal | Metal Performance Shaders | device (private), shared (shared storage mode) | #1021 |
runtime::opencl | OpenCL | CLBlast; MTL5’s own kernels | device, shared (SVM, where present) | not chosen for #1022 |
runtime::vulkan | Vulkan compute | MTL5’s own kernels | device, shared | #1022 (chosen 2026-12-03) |
runtime::domain_flow | Domain flow | the 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.
Handles that are not pointers
Section titled “Handles that are not pointers”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 toT*. The block stores ahandle_type<T>instead of aValue*. - The space defines
offset(h, i), which views and sub-matrices use instead of pointer arithmetic. For a pointer it ish + i; for a Metal buffer it is{buffer, byte_offset + i * sizeof(T)}. data()returns the handle. For every space whose handle isT*that is the pointerdata()returns today, so host code is unchanged.- Element access still requires
host_access. A shared Metal buffer is host-accessible through itscontentspointer, 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).
Moving data
Section titled “Moving data”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 elementscopy(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 spaceauto h2 = to_host(d); // copy_to<memory_space::host>(d)copy(src, dst), source first. It matchesstd::linalg::copy(x, y), which copiesxintoy, and the order MTL5 users already read instd::copy. Kokkos’sdeep_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
Tmust be trivially copyable. That is what lets domain flow carry posits, LNS or fixed-point values to the KPU:copynever 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>orpinned<R>memory: those containers are host-accessible, so element access works on them directly. Adevice<R>container has no host access at all, andto_hostis the only way to bring its elements to the CPU.
Execution
Section titled “Execution”Placement: where an operation runs
Section titled “Placement: where an operation runs”MTL5 has no separate execution-space parameter. The operands’ spaces decide where an operation runs, by one rule applied at compile time:
- On the device, when every operand is device-accessible to one runtime
R(indevice<R>orshared<R>), andR’s backend implements the operation for the value type. - 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. - 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.
Overriding placement: a first argument
Section titled “Overriding placement: a first argument”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 decidesmult(s, A, x, y); // ordered on stream s, on its devicemult(std::execution::par, A, x, y); // on the host, threadedmult(std::execution::seq, A, x, y); // on the host, sequential- A standard execution policy means the host.
seqruns the host rungs single-threaded,parlets them use MTL5’s thread pool. Every operand must be host-accessible; adevice<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.
Ordering and synchronization
Section titled “Ordering and synchronization”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 devicefor (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 streamscopy(upload, h_A, d_A);compute.wait_for(record(upload)); // compute does not pass this point before the uploadlu_factor(compute, d_A, d_piv);
stream<runtime::cuda> adopted(my_cuda_stream); // adopt the application's native objectUntil 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.
Dispatch
Section titled “Dispatch”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 hosttemplate <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_CUDAif constexpr (CudaDenseMatrices<A, B, C>) { interface::cublas::gemm(A, B, C); return; }#endif// ... other runtimes ...// host rungs, unchanged: BLAS, SIMD, threaded, genericThe 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.
Precision and the host fallback
Section titled “Precision and the host fallback”Many devices have no FP64: Apple GPUs, most Adreno parts, Intel Arc A-series. The rule depends on the memory kind:
shared<R>: adoubleoperation 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 whenR::supports<double>is known false at compile time (Metal). Where support varies by device (Intel Xe),supportsanswers at run time and the operation throws.
Custom number types
Section titled “Custom number types”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,
copyand 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 samedevice<runtime::domain_flow>buffer can serve calls with different arithmetic and accumulation types.
Domain flow and the KPU
Section titled “Domain flow and the KPU”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.hppis 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::emulatedstands 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.
Interoperability: mdspan and std::linalg
Section titled “Interoperability: mdspan and std::linalg”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 anstd::mdspanover adense2Dordense_vector, withlayout_rightorlayout_leftfrom the orientation and the default accessor. It exists when__cpp_lib_mdspanis defined and the space is host-accessible.- A device space’s mdspan would use an accessor whose
data_handle_typeis 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 dispatchesstd::linalgon device data. - NVIDIA’s HPC SDK already runs
std::linalgon GPUs. Release 26.3 took<mdspan>and<linalg>out of experimental, and with-stdparthey run on cuBLAS (GPU) or OpenBLAS/NVPL (multicore CPU). Forshared<runtime::cuda>data,as_mdspanplusstd::linalgwith an execution policy is a second route to the GPU that MTL5 can benchmark against its own CUDA backend.
Testing without GPUs
Section titled “Testing without GPUs”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 declaresdevice<emulated>not host-accessible. Itscopy_bytesismemcpy, 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.
Comparison
Section titled “Comparison”| Kokkos | std::linalg / std::mdspan | MTL5 (this design) | |
|---|---|---|---|
| Where data lives | View<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 dereferenced | Container 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 runs | Execution spaces, separate from memory spaces; SpaceAccessibility<Exec, Mem> | An execution policy argument | Derived from the operands’ spaces; an optional first argument (a stream, or a standard execution policy for the host) overrides it |
| Non-pointer handles | Views hold pointers | data_handle_type, need not be a pointer | handle_type<T>, mdspan’s contract |
| Transfers | deep_copy(dst, src), optionally on an execution-space instance | copy(x, y) copies x into y; no notion of spaces | copy(src, dst), optionally on a stream<R>; shapes must match |
| Host mirror | create_mirror_view (aliases when host-accessible), create_mirror (always copies) | — | to_host (always copies); shared and pinned memory need no mirror |
| Asynchrony | Execution-space instances; ordered per instance | Execution policies | Synchronous in phase 1; then stream<R> overloads, in order per stream |
| Vendor libraries | Kokkos Kernels: native kernels, or cuBLAS/rocBLAS/oneMKL TPLs per routine | Implementation’s choice (NVIDIA: cuBLAS) | interface/ backends per runtime, in the compile-time ladder |
| Custom number types | Templates over T; no special support | Templates over the element type; no special support | Generic host path; domain flow on the KPU for device execution (#251) |
| Mismatched operands | Run-time error, or a compile error for an inaccessible execution space | Undefined behaviour | Compile error |
Where MTL5 follows them
Section titled “Where MTL5 follows them”- 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
SharedSpaceidea and name, asshared<>. - Explicit transfers, ordered per stream: Kokkos’s
deep_copysemantics. - Handles: mdspan’s
data_handle_typecontract. - 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.
Where MTL5 departs, and why
Section titled “Where MTL5 departs, and why”- 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 byto_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.
Lessons from Metal
Section titled “Lessons from Metal”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
MPSMatrixMultiplicationfixes 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
MPSMatrixis 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.dense2Dhas 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
DeviceRuntimesmall 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.
Migration from today
Section titled “Migration from today”memory_space::devicebecomes a template, andmemory_space::unifiedbecomesmemory_space::shared. Today both are plain structs without allocators, used only to describe memory and in tests (tests/unit/detail/test_memory_space.cppand four compile-fail tests). They becomedevice<R>andshared<R>. Code that names them changes todevice<>ordevice<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_blockstores ahandle_type. For every space whose handle isT*, which is every space a real runtime provides today, the layout and code are the same.interface::in_memory_space_vandhost_resident_vare unchanged. The new predicates sit beside them.
Phasing
Section titled “Phasing”- 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::noneandruntime::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 intests/unit/detail/emulated_runtime.hpp. - Done:
handle_typeincontiguous_memory_block. A runtime declaresdevice_handle<T>andshared_handle<T>(pinned memory keeps a pointer), withoffset(h, i),address(h)for shared memory, andcopy_bytesoverloads for each pair it copies between;overlaps(a, b, bytes)letscopyreject overlapping views in one device space.detail::handle_traits<Space, T>gives pointers and handles one interface, andbuffer_emulatedin 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.
- Done: the kinds as templates (
- The first backend: Metal (#1021). Hosted macOS runners run Metal and MPS (a probe on
macos-15andmacos-26ran 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, andmult(matrix and vector products) through MPS; see the Metal backend. - Done:
lu_factor,lu_solve,cholesky_factorandcholesky_solvethrough 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) throwsstd::runtime_error, in the factorizations and the solves alike.
- Done:
- 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 forfloatanddouble; see the CUDA backend. The operations now dispatch throughinterface/device_dispatch.hpp, which names no backend, and the factorizations shareinterface/device_fallback.hpp. - Next: a run on an NVIDIA GPU (a cloud instance, or the Jetson); CI compiles and loads the tests only.
- Done:
- 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::hipandruntime::cudastay separate runtimes behind one dispatch layer.- Done:
runtime::hip(device, shared and pinned memory), copies,mult, LU and Cholesky forfloatanddouble; 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
gfx1100override); CI compiles and loads the tests only.
- Done:
- Streams:
stream<R>and the stream overloads, once one backend shows where asynchrony pays. - 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, andmultforfloatin 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.
- Done:
- The remaining backends (#1020) and domain flow on the KPU (#251), independently.
- mdspan interoperability, host-accessible first.
Decided names
Section titled “Decided names”Settled with the maintainer on 2026-12-01:
| Question | Decided | Alternatives considered |
|---|---|---|
| Memory spaces | kinds over a runtime: host, pinned<R>, device<R>, shared<R> | one space per vendor (cuda_device, hip_device, …), as Kokkos does |
| Shared host–device memory | shared | unified (today’s name; confuses hardware with programming model), managed (implies page migration) |
| The ordering object | stream<R>, in order | queue<R> (SYCL and Vulkan queues are not in order), executor<R> |
| The KPU’s runtime tag | runtime::domain_flow: the programming model, not the engine | runtime::kpu |
| The runtime axis | runtime, with the concept DeviceRuntime | platform (OpenCL’s and SYCL’s word), device_api, backend (already used for BLAS/LAPACK) |
| Page-locked host memory | pinned<R> | host_pinned (Kokkos CudaHostPinnedSpace), staging |
| The build’s chosen runtime | runtime::preferred | runtime::default_device, runtime::accelerator |
| Where the runtime tags live | mtl::runtime, each defined by its backend header | mtl::interface::<api>::runtime |
| Running on the host on purpose | a standard execution policy as the first argument | host_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) |
References
Section titled “References”- Memory spaces: the storage layer this builds on (#223, #1012)
- The operation dispatch layer: the ladders device backends extend
- Kokkos: memory spaces, SpaceAccessibility, deep_copy, create_mirror, Kokkos Kernels BLAS support table
std::mdspan: accessor policy requirementsstd::linalg: P1673, BLAS 3 in the draft,copy; the reference implementations kokkos/mdspan and kokkos/stdBLAS- NVIDIA HPC SDK: 26.3 release notes (
<mdspan>and<linalg>out of experimental, cuBLAS back end)