Memory spaces: where a container's elements live
Before issue #223, all of MTL5’s storage was host memory. contiguous_memory_block allocated with over-aligned new, and its non-owning modes, external and view, could only describe another host pointer. That left the distributed backend (#224) and the GPU backend (#225) nowhere to put their buffers. The dispatch traits could not ask where data lives, only its scalar type and whether it had data().
A memory space is the missing axis. It is a small policy type that says where storage lives, who may touch it, and how it is allocated. The default changes nothing.
The policy
Section titled “The policy”include/mtl/memory/memory_space.hpp:
| space | host_accessible | device_accessible | allocator |
|---|---|---|---|
memory_space::host | yes | no | over-aligned new and delete (detail::allocate_aligned), as before |
memory_space::device<R> | no | yes | runtime R’s device memory, where R provides it |
memory_space::shared<R> | yes | yes | runtime R’s shared (managed) memory, where R provides it |
memory_space::pinned<R> | yes | DMA only | runtime R’s page-locked host memory, where R provides it |
A type satisfies MemorySpace if it has host_accessible, device_accessible and name. An AllocatingMemorySpace also has allocate<T>(n), which returns n value-initialized, SIMD-aligned elements (or nullptr for n == 0), and deallocate<T>(p, n). A user-defined space needs nothing else. The tests use a host space that counts its allocations.
Device memory kinds and runtimes (#1017)
Section titled “Device memory kinds and runtimes (#1017)”The device kinds name how memory behaves, never a vendor. Each takes a runtime R, the programming model that allocated the memory (runtime::cuda, hip, sycl, metal, opencl, vulkan, domain_flow, each defined by its backend), so dispatch can never hand one model’s memory to another’s library. include/mtl/memory/runtime.hpp defines the DeviceRuntime concept: a name, a blocking copy_bytes(dst, src, bytes), and supports<T> (false for double on a device without FP64). A runtime may also provide allocate_device/deallocate_device, allocate_shared/deallocate_shared and allocate_pinned/deallocate_pinned; each kind allocates exactly where its runtime provides that pair, and is otherwise a describe-only space for memory the caller owns.
Rdefaults toruntime::preferred, the build’s runtime, so application code can writememory_space::device<>. A build with an accelerator definesMTL5_PREFERRED_RUNTIME; without one,preferredisruntime::none, which is not aDeviceRuntime, sodevice<>there does not compile.sharedis addressable from both sides, not concurrently. The host touches shared memory only while no device work writing it is in flight.- No backend exists yet. The tests run every rule against host-backed test runtimes (
tests/unit/detail/emulated_runtime.hpp).
The full design, with its comparison to Kokkos and std::linalg, is Accelerator backends.
Where the space is chosen
Section titled “Where the space is chosen”The space is the last template argument of the parameter bundles, and it defaults to host:
mat::parameters<Orientation, Index, Dimensions, Storage, SizeType, Space = memory_space::host>vec::parameters<Orientation, Dimensions, Storage, SizeType, Space = memory_space::host>parameters<> is the same type as before, and so are dense2D<double> and dense_vector<float>. A parameter bundle of your own that names no memory_space, as every bundle written before #223 does, is host memory: dense2D and dense_vector read the space through detail::memory_space_of_t, which defaults to host. The containers pass the space to their contiguous_memory_block<Value, Storage, StaticSize, Space>.
How the block uses the space:
- An owning block allocates and frees through it. A space without an allocator is a compile error, not host memory relabelled.
- A non-owning block (
external,view) only records where the caller’s memory lives. - Copying elements, in copy construction and assignment, is a host operation. It needs a host-accessible space, and the next section explains why.
- Stack storage is host memory.
Element access needs host access
Section titled “Element access needs host access”A(i, j), v[i], v(i) and the iterators of dense2D and dense_vector carry requires host_access. For a device space they do not exist, so host code that would read device memory fails to compile instead of crashing at run time:
using device_params = vec::parameters<tag::col_major, vec::non_fixed::dimension, tag::on_heap, std::size_t, memory_space::device<R>>;vec::dense_vector<double, device_params> v(n, device_ptr); // a view of the caller's device bufferv.size(); // finev.data(); // fine: hand it to a device kernelv[0]; // compile error: the constraint host_access is not satisfiedEvery member that writes elements on the host needs host access too:
- the filling constructors (
(n, value), initializer lists,std::vector); - the owning copy of a read-only view, which also needs the view’s space to be host-accessible;
- expression construction and assignment;
- the compound operators
+=,-=,*=,/=.
A space with an allocator but no host access, such as device<R> for a runtime that allocates device memory, can therefore own storage but not fill it from the host: its elements arrive through mtl::copy.
data() stays available, since it is how a device kernel gets the buffer. Shared and pinned memory are host-accessible, so element access works there. const_view keeps the space of the container it views.
Move assignment compiles in every space:
- An owning-to-owning move exchanges pointers.
- A same-size move into a view copies in place, which needs only host access, so it works between
sharedviews. - A move that would copy elements without host access, or allocate in a space without an allocator, aborts. Move assignment is
noexcept.
The dispatch key
Section titled “The dispatch key”include/mtl/interface/dispatch_traits.hpp:
interface::memory_space_t<M>:M::memory_space, ormemory_space::hostfor a type that does not name one, such as expressions, strided views and user types, all of which address host memory.interface::host_resident_v<M>andinterface::in_memory_space_v<M, Space>.
Every fast path in that header hands data() to host code: BLAS and LAPACK, SuiteSparse, the mtl::simd kernels, and the thread pool. So the concepts that gate them now require host-resident data:
BlasDenseMatrixandBlasHermitianMatrix;ContiguousVector, and soBlasDenseVector, theSimd*Vectorconcepts andThreadableDenseVector;ContiguousMatrixData, and soThreadableDenseMatrix;SimdDenseMatrix;suitesparse_solve_dispatches_v, for both vectors.
For host storage, which is every container today, they say exactly what they said before. A device backend adds its own concepts keyed on its runtime: interface::runtime_of_t<M> is the runtime of M’s space (runtime::none for host memory), interface::same_runtime_v<Ms...> holds when every operand belongs to one runtime, and interface::runtime_supports_v<R, T> asks whether R’s devices compute in T.
Sparse storage: compressed2D
Section titled “Sparse storage: compressed2D”compressed2D’s three CSR arrays grow while the matrix is built: the inserter and symmetric_permute resize them and push entries onto them. So they are growable vectors, not fixed blocks, and the memory space reaches them through the vector’s allocator. include/mtl/memory/space_allocator.hpp defines:
detail::space_vector<T, memory_space::host> // is std::vector<T>detail::space_vector<T, Space> // is std::vector<T, detail::space_allocator<T, Space>>The host case is std::vector<T> itself, not an equivalent allocator. A host compressed2D, which every compressed2D written before #223 is, has the same arrays, the same code and the same accessor types: ref_major() still returns std::vector<size_type>&. compressed2D::array_type<T> names the array type for any space.
compressed2D::memory_space is Parameters::memory_space, or host for a bundle that names none, so interface::memory_space_t, host_resident_v and in_memory_space_v answer for sparse matrices as they do for dense ones.
The space must be host-accessible and must allocate. Every member of compressed2D builds or reads the arrays on the host, and so does every sparse kernel that walks ref_major(). A compressed2D in memory_space::device<R> is a compile error, and so is one in memory_space::shared<R> unless runtime R allocates shared memory. A device-resident CSR, as a view of device arrays, belongs to the GPU backend.
space_allocator asks the space for bytes. A space’s allocate<T>(n) returns live, value-initialized elements, and its deallocate destroys them. A standard allocator hands out raw storage, which the vector constructs into and destroys element by element. So space_allocator<T>::allocate(n) takes allocate<std::byte>(n * sizeof(T)) from the space, where there are no lifetimes to manage, and construct and destroy are the standard ones. They have to be: a container may construct through its allocator into storage the allocator never gave it, as MSVC’s vector::insert does for its temporary. allocate checks the block against alignof(T) and throws std::bad_alloc if a space aligns less.
The sparse algorithms take the arrays through auto&, so they work on a compressed2D in any such space. The one helper that named std::vector, UMFPACK’s csr_to_csc, now takes any array type. The test tests/unit/mat/test_compressed2D_memory_space.cpp runs the inserter, both products, symmetric_permute, sparse LU and CG on a matrix in a counting host space.
coordinate2D, ell_matrix and sparse_vector keep their std::vectors for now. They are host build formats, and none is a dispatch target yet.
Mixing spaces
Section titled “Mixing spaces”Every operation in MTL5 runs on the host, so matrices and vectors combine across spaces when all operands are host-accessible:
| Operation | Result |
|---|---|
A * x, A host, x in shared<R> (a view) | works; the result is a host dense_vector |
mult(A, x, y), y in another host-accessible space | works: y receives the product in place |
y = expr, an expression into a container in another space | works |
y = h, a container from another host-accessible space | works (#1012) |
A * x, x in device<R> | compile error: no host element access, and no fast path takes non-host data |
Containers convert between host-accessible spaces (#1012). A dense_vector or dense2D can be built from, and assigned, one in another space whose parameter bundle agrees in every other axis:
vec::dense_vector<double> h = A * x; // hostvec::dense_vector<double, shared_params> y(n, ptr); // a view of shared memoryy = h; // copies into ptry = A * x; // the same: A * x is a host vectorvec::dense_vector<double, pinned_params> p(h); // an owning copy in a user-defined host space- Every other axis must match: orientation, dimensions, storage and size type, and for
dense2Dalso the index base. A row vector into a column vector is a change of shape, and a row-major into a column-major matrix a change of layout, so neither converts. - Assignment follows the rules of expression assignment. A target over an external buffer keeps it and receives the elements; a source of another size (another element count, for
dense2D) throws. Two views of one buffer copy nothing. - The constructor is explicit, as the copy of a read-only view is (#855). A container passed to a by-value parameter in another space does not deep-copy without a word at the call site. It also needs a space that allocates, so it does not exist for an owning
shared<R>container unlessRallocates shared memory. - Both spaces must be host-accessible. A device source or target is a compile error: data moves to and from device memory only through an explicit transfer (next section).
Moving data between spaces (#1017)
Section titled “Moving data between spaces (#1017)”include/mtl/memory/copy.hpp is the only way data moves to or from device memory:
mtl::copy(h, d); // d receives h's elements; blockingauto d2 = mtl::copy_to<memory_space::device<R>>(h); // a new owning container in the device spaceauto h2 = mtl::to_host(d2); // a new host container: always a copy- Source first, as
std::linalg::copy(x, y). - A transfer is not a conversion. Value type and orientation (and, for
dense2D, the index base) must match at compile time; dimensions must match at run time, orcopythrowsstd::length_error. A target that is a view of the caller’s buffer is written through. - A transfer moves bytes, so the value type must be trivially copyable. A posit or LNS value reaches a device unchanged; quantization is an operation, not a transfer.
- Overlapping views of one buffer copy correctly when both are host-accessible. Two overlapping views in one device space throw
std::invalid_argument, since a runtime’s copy needs disjoint ranges. Addresses are compared only within one address space: host and device memory, or two kinds of one runtime, need not share one. - The device side’s runtime moves the bytes. Between two host spaces it is a host copy. Two different runtimes share no transport, so a copy between them does not compile: stage through host memory.
copy_torebinds only the space. The result keeps orientation, dimensions, index base and size type; stack storage, which is host memory, becomes heap storage in another space, and a read-only view’s copy is a writable owner.to_hostalways copies, even from shared memory. There is no aliasing “mirror”: shared and pinned containers are already host-accessible, and device memory reaches the host only as a copy.
Handles that are not pointers (#1017)
Section titled “Handles that are not pointers (#1017)”A space names its storage by handle_type<T>, which is T* for host and pinned memory and for every runtime that declares nothing else. A runtime whose memory is an object addressed by an offset (a Metal buffer, an OpenCL cl_mem, a Vulkan VkBuffer) declares device_handle<T> and shared_handle<T>, following std::mdspan’s data_handle_type contract: copyable and nothrow movable, not necessarily dereferenceable.
data()returns the handle. For a pointer space it is theValue*it always was, and the block’s layout is unchanged.begin()and element access use the host address, which a host-accessible space gives throughaddress(h); a shared Metal buffer’s is its contents pointer.- Views are built from handles:
dense_vector(n, h)anddense2D(r, c, h)take a handle in such a space, anddetail::handle_traits<Space, T>::offset(h, i)steps through a buffer. mtl::copypasses handles to the runtime’scopy_bytes, which has an overload for each pair it copies between. Within one device space it asks the runtime’soverlaps(a, b, bytes), since only the runtime can tell whether two of its handles overlap.
What is not done yet
Section titled “What is not done yet”- Device backends: each runtime’s allocators,
copy_bytesand dispatch concepts belong to its backend issue under #225. - Streams (
stream<R>, ordered asynchronous work) and the host execution-policy argument (mult(std::execution::par, A, x, y)) are the next parts of #1017; see the design. - Per-rank host buffers belong to #224. They are host memory, so they may need nothing beyond
memory_space::host.