Skip to content
class

SharedStorage

SharedStorage

Metal shared-memory storage accessible from both CPU and GPU.

The underlying allocation is a Metal buffer created with MTLResourceStorageModeShared, which the Metal driver maps into the process address space. This gives Lucid a zero-copy host↔device bridge on Apple Silicon unified-memory hardware: the same bytes are addressable from CPU code through cpu_ptr and submitted to the GPU through mtl_handle.

See Also

cpu_view — produces a CpuStorage aliasing this buffer.

Attributes

cpu_ptrvoid*
Host-side mapped pointer. Safe to dereference from any CPU thread.
mtl_handlevoid*
Opaque id<MTLBuffer> handle, stored as void* to avoid pulling the Metal headers into this translation unit.
nbytesstd::size_t
Allocation capacity in bytes.
dtypeDtype
Element type. Default Dtype::F32.
versionstd::shared_ptr<VersionCounter>
Shared mutation counter — same semantics as the other variants.
ownerstd::shared_ptr<void>
Lifetime token for the underlying Metal allocation. The cpu_view deleter captures a copy so the Metal buffer cannot be freed while a CPU view is alive.
gpu_aliasstd::shared_ptr<mlx::core::array>
The one MLX external array over the buffer, shared by every copy of this descriptor. GPU aliases are copies of it, so MLX never sees an alias as the sole owner of the buffer and cannot donate the buffer to an op's output — which would write the result into memory the CPU side is still reading. Set by gpu::pin_shared_storage when a tensor first adopts the buffer.

Notes

A TensorImpl never holds this variant at rest. Its constructor keeps the descriptor aside and stores the cpu_view or the GPU alias its device label calls for, so every op sees ordinary storage.

Methods

3
fnconst

bump_version

void bump_version()

Atomically increments the shared version counter.

fnconst

cpu_view

→CpuStorage
CpuStorage cpu_view()

Returns a CpuStorage that aliases cpu_ptr without copying bytes.

The returned storage installs a custom deleter that holds a copy of owner, guaranteeing the Metal buffer outlives every CpuStorage view spawned this way. The VersionCounter is also shared with this SharedStorage, so mutations through the CPU view are visible to the GPU side.

Returns

CpuStorage

CPU view aliasing the shared buffer. Lifetime-tied to owner.

fnconst

get_version

→std::uint64_t
int get_version()

Reads the current version counter value.

Returns

std::uint64_t

Monotonically non-decreasing snapshot of mutation count.