fuel_memory/lib.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! # fuel-storage
3//!
4//! Unified storage abstraction for fuel. Phase 7.5 foundation work item
5//! (see [docs/storage-unification.md](../../docs/storage-unification.md)).
6//!
7//! `Storage` is the single entry point that holds bytes, a dtype tag,
8//! and a backend memory region (closed enum over CPU/CUDA/Vulkan/Metal).
9//! Backends provide *kernels* that operate on these types — backend
10//! storage types live in their own crates and implement the
11//! `fuel_ir::backend::BackendStorage` trait.
12//!
13//! This crate now owns ONLY the closed-enum dispatch wrapper + the
14//! public `Storage` API. Dispatch infrastructure (KernelBindingTable,
15//! registration wrappers, CompiledNode, ExecutionPlan, the picker,
16//! FusedKernelRegistry, cost functions, the PipelinedExecutor) was
17//! extracted to [`fuel-dispatch`](../../fuel-dispatch/) 2026-05-31;
18//! see [docs/session-prompts/dispatch-move-to-fuel-core.md](
19//! ../../docs/session-prompts/dispatch-move-to-fuel-core.md) for the
20//! move's rationale.
21//!
22//! ## Where things live
23//!
24//! - `fuel_ir::backend::BackendStorage` — the abstract trait
25//! (just `len_bytes()` today; alloc/copy_from land in A4).
26//! - [`fuel_cpu_backend::CpuStorageBytes`] — CPU storage (Phase A3.0).
27//! Bytes-based, 64-byte aligned, `Arc`-clonable, CoW on mutation.
28//! - `fuel_metal_backend::MetalStorageBytes` — Metal storage (A3.1).
29//! - `fuel_cuda_backend::CudaStorageBytes` — CUDA storage (A3.2).
30//! - `fuel_vulkan_backend::VulkanStorageBytes` — Vulkan storage (A3.3).
31//! - **`fuel_dispatch`** — every binding-table, registration wrapper,
32//! picker, executor, and cost-fn that used to live here.
33
34/// Vulkan storage variant — re-exported from fuel-vulkan-backend when
35/// the vulkan feature is enabled.
36#[cfg(feature = "vulkan")]
37pub use fuel_vulkan_backend::VulkanStorageBytes as VulkanStorage;
38
39/// CUDA storage variant — re-exported from fuel-cuda-backend when
40/// the cuda feature is enabled.
41#[cfg(feature = "cuda")]
42pub use fuel_cuda_backend::CudaStorageBytes as CudaStorage;
43
44/// Metal storage variant — re-exported from fuel-metal-backend on
45/// Apple platforms when the metal feature is enabled. The metal
46/// feature has no effect on non-Apple platforms (the dep is
47/// target-gated).
48#[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
49pub use fuel_metal_backend::MetalStorageBytes as MetalStorage;
50
51use fuel_cpu_backend::CpuStorageBytes;
52use fuel_ir::storage::OutputView;
53use fuel_ir::{BackendId, DType, DeviceLocation, Result, SType};
54use std::sync::Arc;
55
56#[cfg(feature = "dlpack")]
57pub mod dlpack_view;
58
59/// Closed enum over backend storage variants. The `Cpu` variant
60/// holds [`CpuStorageBytes`] from `fuel-cpu-backend`. GPU variants
61/// (feature-gated) hold the per-backend `*StorageBytes` types from
62/// each backend crate.
63#[derive(Debug)]
64pub enum BackendStorage {
65 Cpu(CpuStorageBytes),
66 #[cfg(feature = "cuda")]
67 Cuda(CudaStorage),
68 #[cfg(feature = "vulkan")]
69 Vulkan(VulkanStorage),
70 #[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
71 Metal(MetalStorage),
72}
73
74/// Top-level storage type: byte-erased payload + runtime dtype tag.
75/// Layout (shape + strides + start_offset) lives separately on the
76/// consuming `Tensor` — `Storage` owns only the bytes and which
77/// device/dtype they represent.
78///
79/// Optionally carries a `bundle` side-table describing how the inner
80/// byte buffer is partitioned into multiple logically independent
81/// outputs. Set by multi-output op authors via
82/// [`Storage::with_bundle`] / [`Storage::new_bundled`]; consumed by
83/// `Op::View` / `Op::ViewOwned` at realize time. See
84/// [`OutputView`](fuel_ir::storage::OutputView).
85#[derive(Debug)]
86pub struct Storage {
87 /// Backend variant + the bytes themselves.
88 pub inner: BackendStorage,
89 /// How to interpret the bytes. Storage's `len_bytes` is the byte
90 /// count; the element count is `len_bytes / dtype.size_in_bytes()`.
91 pub dtype: DType,
92 /// `None` for single-output storage (today's default). `Some(_)`
93 /// for multi-output bundles: a shared Arc'd slice of per-slot
94 /// [`OutputView`] entries, one per logical output. `Op::View`
95 /// nodes share this Arc so the bundle stays alive as long as any
96 /// view holds a reference.
97 pub bundle: Option<Arc<[OutputView]>>,
98 /// How the bytes are ENCODED (orthogonal to `dtype`, which is the
99 /// logical element type). Empty = plain dense `dtype`, byte-identical
100 /// to pre-SType behaviour. v1: PRIMARY storage only — bundle slots
101 /// keep `dtype` only (per-slot SType is a future addition). See
102 /// [`fuel_ir::SType`] and
103 /// `docs/specs/storage-encoding.md`.
104 pub stype: SType,
105}
106
107/// Feature-aware match over `BackendStorage` variants. Used wherever
108/// the dispatch shape `match s { Cpu(...) => ..., Cuda(...) => ... }`
109/// would otherwise need `#[cfg(feature = "...")]` arms inline.
110///
111/// ```
112/// # use fuel_memory::{BackendStorage, dispatch_storage};
113/// fn len_bytes(s: &BackendStorage) -> usize {
114/// dispatch_storage!(s, inner => inner.len_bytes())
115/// }
116/// ```
117#[macro_export]
118macro_rules! dispatch_storage {
119 ($s:expr, $name:ident => $body:expr) => {
120 match $s {
121 $crate::BackendStorage::Cpu($name) => $body,
122 #[cfg(feature = "cuda")]
123 $crate::BackendStorage::Cuda($name) => $body,
124 #[cfg(feature = "vulkan")]
125 $crate::BackendStorage::Vulkan($name) => $body,
126 #[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
127 $crate::BackendStorage::Metal($name) => $body,
128 }
129 };
130}
131
132impl BackendStorage {
133 /// Total addressable byte count, regardless of dtype.
134 pub fn len_bytes(&self) -> usize {
135 dispatch_storage!(self, inner => inner.len_bytes())
136 }
137
138 /// The kind of backend that owns these bytes. Exhaustive: a new variant fails to compile here
139 /// until it names its [`BackendId`]. Use this, not `std::mem::discriminant`, to say which backend a
140 /// storage came from (ROADMAP row 137, seam S3 step 2).
141 pub fn backend_id(&self) -> BackendId {
142 match self {
143 BackendStorage::Cpu(_) => BackendId::Cpu,
144 #[cfg(feature = "cuda")]
145 BackendStorage::Cuda(_) => BackendId::Cuda,
146 #[cfg(feature = "vulkan")]
147 BackendStorage::Vulkan(_) => BackendId::Vulkan,
148 #[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
149 BackendStorage::Metal(_) => BackendId::Metal,
150 }
151 }
152
153 /// The device these bytes live on, with the within-process GPU ordinal the owning device reports
154 /// (an enumeration index, not an identity: ROADMAP row 125). `None` only for a Vulkan storage built
155 /// without a backend handle (the legacy `alloc_bytes` path), which cannot say which GPU holds it;
156 /// [`Self::backend_id`] still answers for it.
157 pub fn location(&self) -> Option<DeviceLocation> {
158 match self {
159 BackendStorage::Cpu(_) => Some(DeviceLocation::Cpu),
160 #[cfg(feature = "cuda")]
161 BackendStorage::Cuda(c) => Some(c.device().location()),
162 #[cfg(feature = "vulkan")]
163 BackendStorage::Vulkan(v) => v
164 .backend()
165 .map(|b| DeviceLocation::Vulkan { gpu_id: b.gpu_id }),
166 #[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
167 BackendStorage::Metal(m) => Some(m.device().location()),
168 }
169 }
170
171 /// Receive the bytes of `src` into `self`, using the transfer the pair of backends supports:
172 ///
173 /// | `self` \ `src` | Cpu | Cuda | Vulkan |
174 /// |---|---|---|---|
175 /// | Cpu | byte copy | device-to-host read (`to_cpu_bytes_finer`, no whole-device sync) | device-to-host read (`download_bytes`) |
176 /// | Cuda | typed `Err` | write into the existing buffer (`copy_from_device`, no allocation) | typed `Err` |
177 /// | Vulkan | typed `Err` | typed `Err` | one `vkCmdCopyBuffer` into a fresh buffer that replaces `self` |
178 ///
179 /// A pair outside the table returns an `Err` naming both backends by [`BackendId`] (cross-vendor
180 /// transfer is two hops through the CPU, planned by the optimizer, not hidden here). A CPU
181 /// destination copies `min(src, dst)` bytes, as the executor's sized outputs always match.
182 /// This is the one place the per-pair knowledge lives (ROADMAP row 137, seam S3 step 2); the
183 /// executor's `Op::Copy` wrappers call it.
184 pub fn copy_from(&mut self, src: &BackendStorage) -> Result<()> {
185 match self {
186 BackendStorage::Cpu(dst) => copy_into_cpu(dst, src),
187 #[cfg(feature = "cuda")]
188 BackendStorage::Cuda(dst) => copy_into_cuda(dst, src),
189 #[cfg(feature = "vulkan")]
190 BackendStorage::Vulkan(dst) => copy_into_vulkan(dst, src),
191 #[cfg(all(feature = "metal", any(target_os = "macos", target_os = "ios")))]
192 BackendStorage::Metal(_) => Err(no_direct_transfer(src, BackendId::Metal)),
193 }
194 }
195}
196
197/// The error for a (source, destination) pair with no direct transfer.
198fn no_direct_transfer(src: &BackendStorage, dst: BackendId) -> fuel_ir::Error {
199 fuel_ir::Error::Msg(format!(
200 "BackendStorage::copy_from: no direct transfer from {:?} storage to {dst:?} storage (cross-vendor and host-to-device copies are separate hops)",
201 src.backend_id(),
202 ))
203 .bt()
204}
205
206/// Destination CPU: a byte copy from CPU, a device-to-host read from CUDA or Vulkan.
207fn copy_into_cpu(dst: &mut CpuStorageBytes, src: &BackendStorage) -> Result<()> {
208 match src {
209 BackendStorage::Cpu(s) => {
210 copy_prefix(dst, s.bytes());
211 Ok(())
212 }
213 #[cfg(feature = "cuda")]
214 BackendStorage::Cuda(s) => {
215 copy_prefix(dst, &s.to_cpu_bytes_finer()?);
216 Ok(())
217 }
218 #[cfg(feature = "vulkan")]
219 BackendStorage::Vulkan(s) => {
220 copy_prefix(dst, &vulkan_backend_of(s)?.download_bytes(s)?);
221 Ok(())
222 }
223 #[allow(unreachable_patterns)]
224 other => Err(no_direct_transfer(other, BackendId::Cpu)),
225 }
226}
227
228/// Destination CUDA: write into the existing buffer from CUDA; nothing else is direct.
229#[cfg(feature = "cuda")]
230fn copy_into_cuda(dst: &mut CudaStorage, src: &BackendStorage) -> Result<()> {
231 match src {
232 BackendStorage::Cuda(s) => dst.copy_from_device(s),
233 other => Err(no_direct_transfer(other, BackendId::Cuda)),
234 }
235}
236
237/// Destination Vulkan: one buffer copy from Vulkan that replaces the destination; nothing else is direct.
238#[cfg(feature = "vulkan")]
239fn copy_into_vulkan(dst: &mut VulkanStorage, src: &BackendStorage) -> Result<()> {
240 match src {
241 BackendStorage::Vulkan(s) => {
242 *dst = vulkan_backend_of(s)?.slot_copy_to_new_handle(s, 0, s.len_bytes())?;
243 Ok(())
244 }
245 other => Err(no_direct_transfer(other, BackendId::Vulkan)),
246 }
247}
248
249/// Copy as many bytes of `bytes` as fit into the CPU destination.
250fn copy_prefix(dst: &mut CpuStorageBytes, bytes: &[u8]) {
251 let n = bytes.len().min(dst.len_bytes());
252 dst.bytes_mut()[..n].copy_from_slice(&bytes[..n]);
253}
254
255/// The backend handle a Vulkan storage must carry for the pipelined executor's copies.
256#[cfg(feature = "vulkan")]
257fn vulkan_backend_of(s: &VulkanStorage) -> Result<&Arc<fuel_vulkan_backend::VulkanBackend>> {
258 s.backend().ok_or_else(|| {
259 fuel_ir::Error::Msg(
260 "BackendStorage::copy_from: Vulkan source has no backend handle. Storages flowing through the pipelined-executor Copy path come from VulkanBackend::alloc_bytes_handle / upload_bytes_handle."
261 .to_string(),
262 )
263 .bt()
264 })
265}
266
267impl Storage {
268 /// Build a Storage from an already-allocated backend variant
269 /// plus its dtype tag. Single-output (no bundle metadata); use
270 /// [`Self::with_bundle`] / [`Self::new_bundled`] for the
271 /// multi-output case.
272 pub fn new(inner: BackendStorage, dtype: DType) -> Self {
273 Self {
274 inner,
275 dtype,
276 bundle: None,
277 stype: SType::default(),
278 }
279 }
280
281 /// Build a Storage from a backend variant + dtype tag + bundle
282 /// side-table in one shot. Validates that the bundle is
283 /// non-empty and that slot 0's dtype matches the storage's
284 /// primary dtype (the bundled-storage invariant: slot 0 IS the
285 /// primary).
286 pub fn new_bundled(
287 inner: BackendStorage,
288 dtype: DType,
289 bundle: Arc<[OutputView]>,
290 ) -> Result<Self> {
291 Self::validate_bundle(dtype, &bundle)?;
292 Ok(Self {
293 inner,
294 dtype,
295 bundle: Some(bundle),
296 stype: SType::default(),
297 })
298 }
299
300 /// Attach a bundle side-table to an existing single-output
301 /// Storage. Same validation as [`Self::new_bundled`]; panics in
302 /// debug mode if a bundle is already attached (re-bundling is a
303 /// contract bug).
304 pub fn with_bundle(mut self, bundle: Arc<[OutputView]>) -> Result<Self> {
305 debug_assert!(
306 self.bundle.is_none(),
307 "Storage::with_bundle: bundle already attached",
308 );
309 Self::validate_bundle(self.dtype, &bundle)?;
310 self.bundle = Some(bundle);
311 Ok(self)
312 }
313
314 fn validate_bundle(primary_dtype: DType, bundle: &Arc<[OutputView]>) -> Result<()> {
315 if bundle.is_empty() {
316 return Err(fuel_ir::Error::Msg(
317 "Storage::with_bundle: bundle slice must be non-empty".into(),
318 )
319 .bt());
320 }
321 let slot0 = &bundle[0];
322 if slot0.dtype != primary_dtype {
323 return Err(fuel_ir::Error::Msg(format!(
324 "Storage::with_bundle: slot 0 dtype {:?} must match \
325 Storage's primary dtype {:?}",
326 slot0.dtype, primary_dtype,
327 ))
328 .bt());
329 }
330 Ok(())
331 }
332
333 /// Whether this storage carries multi-output bundle metadata.
334 pub fn is_bundled(&self) -> bool {
335 self.bundle.is_some()
336 }
337
338 /// Number of logical output slots. `1` for single-output;
339 /// `bundle.len()` for bundled.
340 pub fn slot_count(&self) -> usize {
341 self.bundle.as_ref().map_or(1, |b| b.len())
342 }
343
344 /// Borrow the bundle slice, or `None` for single-output storage.
345 pub fn bundle(&self) -> Option<&[OutputView]> {
346 self.bundle.as_deref()
347 }
348
349 /// Per-slot view; `None` for out-of-range or single-output.
350 pub fn slot_view(&self, idx: usize) -> Option<&OutputView> {
351 self.bundle.as_deref().and_then(|b| b.get(idx))
352 }
353
354 /// The `DType` tag attached to these bytes.
355 pub fn dtype(&self) -> DType {
356 self.dtype
357 }
358
359 /// Total addressable byte count.
360 pub fn len_bytes(&self) -> usize {
361 self.inner.len_bytes()
362 }
363
364 /// Element count = `len_bytes / dtype.size_in_bytes()`.
365 pub fn elem_count(&self) -> usize {
366 let bps = self.dtype.size_in_bytes();
367 self.len_bytes().checked_div(bps).unwrap_or(0)
368 }
369
370 /// Attach an encoding scheme to this storage (consuming builder).
371 /// Does not touch the bytes or the logical dtype — only describes
372 /// HOW the bytes are encoded. See [`fuel_ir::SType`].
373 pub fn with_stype(mut self, stype: SType) -> Self {
374 self.stype = stype;
375 self
376 }
377
378 /// The encoding scheme. Empty = plain dense `dtype`.
379 pub fn stype(&self) -> &SType {
380 &self.stype
381 }
382}
383
384/// Allocate freshly on the CPU backend with the given dtype + element
385/// count. Bytes are zero-initialized and 64-byte aligned (suitable
386/// for AVX-512 SIMD).
387pub fn alloc_cpu_zeroed(dtype: DType, elem_count: usize) -> Result<Storage> {
388 let len_bytes = elem_count.saturating_mul(dtype.size_in_bytes());
389 Ok(Storage::new(
390 BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(len_bytes)),
391 dtype,
392 ))
393}
394
395/// Build a CPU `Storage` from a typed slice, copying the bytes. The
396/// result has the dtype matching `T` and is 64-byte aligned.
397pub fn from_slice_cpu<T: bytemuck::Pod + fuel_ir::WithDType>(data: &[T]) -> Storage {
398 Storage::new(
399 BackendStorage::Cpu(CpuStorageBytes::from_slice(data)),
400 T::DTYPE,
401 )
402}
403
404#[cfg(test)]
405mod tests {
406 use super::*;
407
408 /// CPU to CPU copy moves the bytes; a pair with no direct transfer fails loudly, naming both backends.
409 #[test]
410 fn copy_from_cpu_to_cpu_copies_and_unsupported_pairs_error() {
411 let src = BackendStorage::Cpu(CpuStorageBytes::from_slice(&[1u8, 2, 3, 4]));
412 let mut dst = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(4));
413 dst.copy_from(&src).unwrap();
414 match &dst {
415 BackendStorage::Cpu(c) => assert_eq!(c.bytes(), &[1, 2, 3, 4]),
416 #[allow(unreachable_patterns)]
417 _ => panic!("destination changed backend"),
418 }
419 // A shorter destination takes the prefix that fits and does not overrun.
420 let mut short = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(2));
421 short.copy_from(&src).unwrap();
422 match &short {
423 BackendStorage::Cpu(c) => assert_eq!(c.bytes(), &[1, 2]),
424 #[allow(unreachable_patterns)]
425 _ => panic!("destination changed backend"),
426 }
427 }
428
429 /// A CPU storage names its backend and its place, and `len_bytes` agrees with the bytes built.
430 #[test]
431 fn cpu_storage_reports_backend_id_and_location() {
432 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(24));
433 assert_eq!(bs.backend_id(), BackendId::Cpu);
434 assert_eq!(bs.location(), Some(DeviceLocation::Cpu));
435 assert_eq!(bs.len_bytes(), 24);
436 // The reported place maps back to the reported backend (the fuel-ir mapping, one definition).
437 assert_eq!(bs.location().map(|l| l.backend()), Some(bs.backend_id()));
438 }
439
440 /// Smoke: building a Storage via the CPU backend and reading back
441 /// dtype + len_bytes + elem_count works.
442 #[test]
443 fn cpu_storage_basic_shape() {
444 let s = alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
445 assert_eq!(s.dtype(), DType::F32);
446 assert_eq!(s.len_bytes(), 16);
447 assert_eq!(s.elem_count(), 4);
448 }
449
450 /// Smoke: dispatch_storage! macro picks the right variant arm.
451 #[test]
452 fn dispatch_macro_routes_to_variant() {
453 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(8));
454 let n = dispatch_storage!(&bs, inner => inner.len_bytes());
455 assert_eq!(n, 8);
456 }
457
458 /// Smoke: BackendStorage::len_bytes goes through dispatch_storage!
459 /// and matches the underlying CpuStorageBytes len_bytes.
460 #[test]
461 fn backend_storage_len_bytes_dispatches() {
462 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(32));
463 assert_eq!(bs.len_bytes(), 32);
464 }
465
466 /// Smoke: zero-element allocations still produce a valid Storage
467 /// with elem_count 0 and dtype intact.
468 #[test]
469 fn zero_element_allocation() {
470 let s = alloc_cpu_zeroed(DType::F64, 0).expect("alloc");
471 assert_eq!(s.dtype(), DType::F64);
472 assert_eq!(s.len_bytes(), 0);
473 assert_eq!(s.elem_count(), 0);
474 }
475
476 /// Smoke: from_slice_cpu preserves dtype + values via Pod cast.
477 #[test]
478 fn from_slice_cpu_round_trip() {
479 let data = vec![1.0_f32, 2.0, 3.0, 4.0];
480 let s = from_slice_cpu(&data);
481 assert_eq!(s.dtype(), DType::F32);
482 assert_eq!(s.elem_count(), 4);
483 assert_eq!(s.len_bytes(), 16);
484 }
485
486 /// Born-red (step 2): a plain Storage has an empty (plain) SType by default.
487 #[test]
488 fn plain_storage_has_empty_stype() {
489 let s = alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
490 assert!(
491 s.stype().is_plain(),
492 "default Storage must carry a plain SType"
493 );
494 assert_eq!(s.stype().layers().len(), 0);
495 }
496
497 /// Born-red (step 2): attaching an SType is preserved and does not disturb
498 /// the logical dtype or the byte count.
499 #[test]
500 fn storage_with_stype_round_trips() {
501 use fuel_ir::{Encoding, GgmlDType, SType};
502 let s = alloc_cpu_zeroed(DType::F32, 8)
503 .expect("alloc")
504 .with_stype(SType::from_layer(Encoding::GgmlBlock {
505 ggml_dtype: GgmlDType::Q4_0,
506 }));
507 assert!(!s.stype().is_plain());
508 assert_eq!(s.dtype(), DType::F32); // dtype unchanged
509 assert_eq!(s.len_bytes(), 32); // bytes unchanged
510 }
511
512 /// A4: alloc symmetry — CpuStorageBytes::alloc and from_zero_bytes
513 /// produce the same shape.
514 #[test]
515 fn cpu_storage_alloc_alias() {
516 let a = fuel_cpu_backend::CpuStorageBytes::alloc(24);
517 let b = fuel_cpu_backend::CpuStorageBytes::from_zero_bytes(24);
518 assert_eq!(a.len_bytes(), b.len_bytes());
519 assert_eq!(a.bytes(), b.bytes());
520 }
521}