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
172impl Storage {
173 /// Build a Storage from an already-allocated backend variant
174 /// plus its dtype tag. Single-output (no bundle metadata); use
175 /// [`Self::with_bundle`] / [`Self::new_bundled`] for the
176 /// multi-output case.
177 pub fn new(inner: BackendStorage, dtype: DType) -> Self {
178 Self {
179 inner,
180 dtype,
181 bundle: None,
182 stype: SType::default(),
183 }
184 }
185
186 /// Build a Storage from a backend variant + dtype tag + bundle
187 /// side-table in one shot. Validates that the bundle is
188 /// non-empty and that slot 0's dtype matches the storage's
189 /// primary dtype (the bundled-storage invariant: slot 0 IS the
190 /// primary).
191 pub fn new_bundled(
192 inner: BackendStorage,
193 dtype: DType,
194 bundle: Arc<[OutputView]>,
195 ) -> Result<Self> {
196 Self::validate_bundle(dtype, &bundle)?;
197 Ok(Self {
198 inner,
199 dtype,
200 bundle: Some(bundle),
201 stype: SType::default(),
202 })
203 }
204
205 /// Attach a bundle side-table to an existing single-output
206 /// Storage. Same validation as [`Self::new_bundled`]; panics in
207 /// debug mode if a bundle is already attached (re-bundling is a
208 /// contract bug).
209 pub fn with_bundle(mut self, bundle: Arc<[OutputView]>) -> Result<Self> {
210 debug_assert!(
211 self.bundle.is_none(),
212 "Storage::with_bundle: bundle already attached",
213 );
214 Self::validate_bundle(self.dtype, &bundle)?;
215 self.bundle = Some(bundle);
216 Ok(self)
217 }
218
219 fn validate_bundle(primary_dtype: DType, bundle: &Arc<[OutputView]>) -> Result<()> {
220 if bundle.is_empty() {
221 return Err(fuel_ir::Error::Msg(
222 "Storage::with_bundle: bundle slice must be non-empty".into(),
223 )
224 .bt());
225 }
226 let slot0 = &bundle[0];
227 if slot0.dtype != primary_dtype {
228 return Err(fuel_ir::Error::Msg(format!(
229 "Storage::with_bundle: slot 0 dtype {:?} must match \
230 Storage's primary dtype {:?}",
231 slot0.dtype, primary_dtype,
232 ))
233 .bt());
234 }
235 Ok(())
236 }
237
238 /// Whether this storage carries multi-output bundle metadata.
239 pub fn is_bundled(&self) -> bool {
240 self.bundle.is_some()
241 }
242
243 /// Number of logical output slots. `1` for single-output;
244 /// `bundle.len()` for bundled.
245 pub fn slot_count(&self) -> usize {
246 self.bundle.as_ref().map_or(1, |b| b.len())
247 }
248
249 /// Borrow the bundle slice, or `None` for single-output storage.
250 pub fn bundle(&self) -> Option<&[OutputView]> {
251 self.bundle.as_deref()
252 }
253
254 /// Per-slot view; `None` for out-of-range or single-output.
255 pub fn slot_view(&self, idx: usize) -> Option<&OutputView> {
256 self.bundle.as_deref().and_then(|b| b.get(idx))
257 }
258
259 /// The `DType` tag attached to these bytes.
260 pub fn dtype(&self) -> DType {
261 self.dtype
262 }
263
264 /// Total addressable byte count.
265 pub fn len_bytes(&self) -> usize {
266 self.inner.len_bytes()
267 }
268
269 /// Element count = `len_bytes / dtype.size_in_bytes()`.
270 pub fn elem_count(&self) -> usize {
271 let bps = self.dtype.size_in_bytes();
272 self.len_bytes().checked_div(bps).unwrap_or(0)
273 }
274
275 /// Attach an encoding scheme to this storage (consuming builder).
276 /// Does not touch the bytes or the logical dtype — only describes
277 /// HOW the bytes are encoded. See [`fuel_ir::SType`].
278 pub fn with_stype(mut self, stype: SType) -> Self {
279 self.stype = stype;
280 self
281 }
282
283 /// The encoding scheme. Empty = plain dense `dtype`.
284 pub fn stype(&self) -> &SType {
285 &self.stype
286 }
287}
288
289/// Allocate freshly on the CPU backend with the given dtype + element
290/// count. Bytes are zero-initialized and 64-byte aligned (suitable
291/// for AVX-512 SIMD).
292pub fn alloc_cpu_zeroed(dtype: DType, elem_count: usize) -> Result<Storage> {
293 let len_bytes = elem_count.saturating_mul(dtype.size_in_bytes());
294 Ok(Storage::new(
295 BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(len_bytes)),
296 dtype,
297 ))
298}
299
300/// Build a CPU `Storage` from a typed slice, copying the bytes. The
301/// result has the dtype matching `T` and is 64-byte aligned.
302pub fn from_slice_cpu<T: bytemuck::Pod + fuel_ir::WithDType>(data: &[T]) -> Storage {
303 Storage::new(
304 BackendStorage::Cpu(CpuStorageBytes::from_slice(data)),
305 T::DTYPE,
306 )
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 /// A CPU storage names its backend and its place, and `len_bytes` agrees with the bytes built.
314 #[test]
315 fn cpu_storage_reports_backend_id_and_location() {
316 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(24));
317 assert_eq!(bs.backend_id(), BackendId::Cpu);
318 assert_eq!(bs.location(), Some(DeviceLocation::Cpu));
319 assert_eq!(bs.len_bytes(), 24);
320 // The reported place maps back to the reported backend (the fuel-ir mapping, one definition).
321 assert_eq!(bs.location().map(|l| l.backend()), Some(bs.backend_id()));
322 }
323
324 /// Smoke: building a Storage via the CPU backend and reading back
325 /// dtype + len_bytes + elem_count works.
326 #[test]
327 fn cpu_storage_basic_shape() {
328 let s = alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
329 assert_eq!(s.dtype(), DType::F32);
330 assert_eq!(s.len_bytes(), 16);
331 assert_eq!(s.elem_count(), 4);
332 }
333
334 /// Smoke: dispatch_storage! macro picks the right variant arm.
335 #[test]
336 fn dispatch_macro_routes_to_variant() {
337 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(8));
338 let n = dispatch_storage!(&bs, inner => inner.len_bytes());
339 assert_eq!(n, 8);
340 }
341
342 /// Smoke: BackendStorage::len_bytes goes through dispatch_storage!
343 /// and matches the underlying CpuStorageBytes len_bytes.
344 #[test]
345 fn backend_storage_len_bytes_dispatches() {
346 let bs = BackendStorage::Cpu(CpuStorageBytes::from_zero_bytes(32));
347 assert_eq!(bs.len_bytes(), 32);
348 }
349
350 /// Smoke: zero-element allocations still produce a valid Storage
351 /// with elem_count 0 and dtype intact.
352 #[test]
353 fn zero_element_allocation() {
354 let s = alloc_cpu_zeroed(DType::F64, 0).expect("alloc");
355 assert_eq!(s.dtype(), DType::F64);
356 assert_eq!(s.len_bytes(), 0);
357 assert_eq!(s.elem_count(), 0);
358 }
359
360 /// Smoke: from_slice_cpu preserves dtype + values via Pod cast.
361 #[test]
362 fn from_slice_cpu_round_trip() {
363 let data = vec![1.0_f32, 2.0, 3.0, 4.0];
364 let s = from_slice_cpu(&data);
365 assert_eq!(s.dtype(), DType::F32);
366 assert_eq!(s.elem_count(), 4);
367 assert_eq!(s.len_bytes(), 16);
368 }
369
370 /// Born-red (step 2): a plain Storage has an empty (plain) SType by default.
371 #[test]
372 fn plain_storage_has_empty_stype() {
373 let s = alloc_cpu_zeroed(DType::F32, 4).expect("alloc");
374 assert!(
375 s.stype().is_plain(),
376 "default Storage must carry a plain SType"
377 );
378 assert_eq!(s.stype().layers().len(), 0);
379 }
380
381 /// Born-red (step 2): attaching an SType is preserved and does not disturb
382 /// the logical dtype or the byte count.
383 #[test]
384 fn storage_with_stype_round_trips() {
385 use fuel_ir::{Encoding, GgmlDType, SType};
386 let s = alloc_cpu_zeroed(DType::F32, 8)
387 .expect("alloc")
388 .with_stype(SType::from_layer(Encoding::GgmlBlock {
389 ggml_dtype: GgmlDType::Q4_0,
390 }));
391 assert!(!s.stype().is_plain());
392 assert_eq!(s.dtype(), DType::F32); // dtype unchanged
393 assert_eq!(s.len_bytes(), 32); // bytes unchanged
394 }
395
396 /// A4: alloc symmetry — CpuStorageBytes::alloc and from_zero_bytes
397 /// produce the same shape.
398 #[test]
399 fn cpu_storage_alloc_alias() {
400 let a = fuel_cpu_backend::CpuStorageBytes::alloc(24);
401 let b = fuel_cpu_backend::CpuStorageBytes::from_zero_bytes(24);
402 assert_eq!(a.len_bytes(), b.len_bytes());
403 assert_eq!(a.bytes(), b.bytes());
404 }
405}