Skip to main content

fuel_backend_contract/
storage.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Type-erased tensor storage wrapper (Phase 7.5 work item G fix-up).
3//!
4//! `Storage` was originally `fuel-core::Storage` and lived alongside the
5//! eager-dispatch op methods that mutate it. Phase 7.5 work item G moved
6//! the struct and the methods that depend only on backend-contract traits
7//! here so that `fuel_graph::Graph` can own a NodeId-keyed map of
8//! `Arc<RwLock<Storage>>` slots without inverting the dependency graph.
9//!
10//! As of B0.3 (the `fuel-backend-contract` cut) it lives in this crate —
11//! it IS the type-erased `Box<dyn DynBackendStorage>` handle that carries a
12//! backend's storage. The bundle *data* it references (`OutputView`,
13//! `OutputViewSpec`, `compose_bundle`) stays in [`fuel_ir::storage`].
14//!
15//! `Storage::device()` returns `Arc<dyn DynBackendDevice>` rather than
16//! the `Device` wrapper (which still lives in fuel-core); callers wrap as
17//! needed.
18//!
19//! ## Multi-output bundles (Option C, Session 1)
20//!
21//! A `Storage` may optionally carry [`OutputView`] side-table entries
22//! describing how the inner byte buffer is partitioned into multiple
23//! logically independent outputs. A multi-output op allocates one
24//! bundled `Storage` whose `bundle` slice describes per-slot dtype/shape/
25//! layout at byte offsets within the same underlying buffer. The
26//! backend trait surface ([`DynBackendStorage`]) is intentionally
27//! unchanged — backends still produce single typed-byte buffers; bundle
28//! metadata lives only on the `Storage` newtype.
29
30use crate::dyn_backend::{DynBackendDevice, DynBackendStorage};
31use fuel_ir::op::{self, BinaryOp, CmpOp, ReduceOp};
32use fuel_ir::storage::{OutputView, OutputViewSpec, compose_bundle};
33use fuel_ir::stype::SType;
34use fuel_ir::{DType, Error, HostBuffer, Layout, Result, Scalar, Shape, conv};
35use std::sync::Arc;
36
37/// Allocate a bundled [`Storage`] on `device` covering all of `specs`.
38///
39/// Sizes the underlying allocation to `total_bytes / primary_size`
40/// elements of the primary (slot 0) dtype, rounding up so the buffer
41/// is guaranteed to hold every slot's bytes. Zero-initialised — the
42/// kernel can overwrite each slot on first write.
43///
44/// Returns a [`Storage`] whose [`Storage::bundle()`] is the resolved
45/// slot-view list and whose primary dtype equals slot 0's dtype.
46pub fn allocate_bundled_storage(
47    device: &dyn DynBackendDevice,
48    specs: &[OutputViewSpec],
49) -> Result<Storage> {
50    let (total_bytes, views) = compose_bundle(specs)?;
51    let primary_dtype = specs[0].dtype;
52    let primary_size = primary_dtype.size_in_bytes().max(1);
53    // Round up so the allocation holds every slot's bytes even when
54    // the bundle's total isn't a clean multiple of the primary dtype's
55    // size (e.g. F32 primary + F64 secondary at an odd boundary).
56    let flat_elems = total_bytes.div_ceil(primary_size).max(1);
57    let inner = device.zeros_impl_dyn(&Shape::from_dims(&[flat_elems]), primary_dtype)?;
58    Storage::from_dyn_bundled(inner, Arc::from(views.into_boxed_slice()))
59}
60
61/// Owns a typed contiguous buffer on one device. The boxed
62/// `DynBackendStorage` is the actual byte holder; `Storage` is a thin
63/// wrapper that gives the eager-dispatch op methods (matmul, conv,
64/// unary, binary, …) somewhere to live.
65///
66/// Optionally carries a `bundle` side-table describing how the inner
67/// buffer is partitioned into multiple logically independent outputs.
68/// See [`OutputView`] and the module-level "Multi-output bundles" doc
69/// for the contract.
70///
71/// We do not implement `Clone` because cloning storage may fail on
72/// out-of-memory; use [`Self::try_clone`] for the fallible version.
73#[derive(Debug)]
74pub struct Storage {
75    pub(crate) inner: Box<dyn DynBackendStorage>,
76    /// `None` for single-output storage (today's default). `Some(_)`
77    /// for multi-output bundles: a shared Arc'd slice of per-slot
78    /// [`OutputView`] entries, one per logical output. `Op::View`
79    /// nodes share this Arc so the bundle stays alive as long as any
80    /// view holds a reference.
81    pub(crate) bundle: Option<Arc<[OutputView]>>,
82    /// How the bytes are ENCODED (orthogonal to the logical element type
83    /// reported by `inner.dtype_dyn()`). Empty = plain dense dtype,
84    /// byte-identical to pre-SType behaviour. v1: PRIMARY storage only —
85    /// bundle slots keep `dtype` only (per-slot SType is a future
86    /// addition). See [`fuel_ir::SType`] and `docs/specs/storage-encoding.md`.
87    pub(crate) stype: SType,
88}
89
90impl Storage {
91    /// Construct storage from any concrete `DynBackendStorage` implementor.
92    ///
93    /// This is the backend-agnostic entry point — backends provide a type
94    /// implementing `DynBackendStorage`, and `Storage::new` boxes it.
95    /// Single-output (no bundle metadata); use
96    /// [`Storage::from_dyn_bundled`] for the multi-output case.
97    pub fn new<B: DynBackendStorage + 'static>(b: B) -> Self {
98        Storage {
99            inner: Box::new(b),
100            bundle: None,
101            stype: SType::default(),
102        }
103    }
104
105    /// Wrap an already-boxed `dyn DynBackendStorage`. Used by callers
106    /// (notably the quantized fast-paths) that produce a `Box<dyn ..>`
107    /// directly from trait dispatch. Single-output; use
108    /// [`Storage::from_dyn_bundled`] for the multi-output case.
109    pub fn from_dyn(b: Box<dyn DynBackendStorage>) -> Self {
110        Storage {
111            inner: b,
112            bundle: None,
113            stype: SType::default(),
114        }
115    }
116
117    /// Wrap an already-boxed `dyn DynBackendStorage` together with a
118    /// per-slot bundle side-table. Used by multi-output op authors:
119    /// the backend allocates one bundled byte buffer (whose
120    /// `dtype_dyn()` is the primary/slot-0 dtype), and the caller
121    /// attaches the slot metadata here.
122    ///
123    /// Validates at construction time that
124    /// `bundle[0].dtype == inner.dtype_dyn()` so callers can trust
125    /// `Storage::dtype()` ≡ `Storage::primary_dtype()` ≡
126    /// `Storage::slot_dtype(0)` on a bundled storage.
127    pub fn from_dyn_bundled(
128        b: Box<dyn DynBackendStorage>,
129        bundle: Arc<[OutputView]>,
130    ) -> Result<Self> {
131        if bundle.is_empty() {
132            return Err(Error::Msg(
133                "Storage::from_dyn_bundled: bundle slice must be non-empty".into(),
134            )
135            .bt());
136        }
137        let primary = bundle[0].dtype;
138        let inner_dtype = b.dtype_dyn();
139        if primary != inner_dtype {
140            return Err(Error::Msg(format!(
141                "Storage::from_dyn_bundled: slot 0 dtype {primary:?} must \
142                 match inner backend dtype {inner_dtype:?}",
143            ))
144            .bt());
145        }
146        Ok(Storage {
147            inner: b,
148            bundle: Some(bundle),
149            stype: SType::default(),
150        })
151    }
152
153    /// Attach a bundle side-table to an existing single-output
154    /// `Storage`. The dtype check from [`Storage::from_dyn_bundled`]
155    /// applies. Panics in `debug_assertions` mode if a bundle is
156    /// already attached — re-bundling silently is a contract bug.
157    pub fn with_bundle(mut self, bundle: Arc<[OutputView]>) -> Result<Self> {
158        debug_assert!(
159            self.bundle.is_none(),
160            "Storage::with_bundle: bundle already attached",
161        );
162        if bundle.is_empty() {
163            return Err(
164                Error::Msg("Storage::with_bundle: bundle slice must be non-empty".into()).bt(),
165            );
166        }
167        let primary = bundle[0].dtype;
168        let inner_dtype = self.inner.dtype_dyn();
169        if primary != inner_dtype {
170            return Err(Error::Msg(format!(
171                "Storage::with_bundle: slot 0 dtype {primary:?} must \
172                 match inner backend dtype {inner_dtype:?}",
173            ))
174            .bt());
175        }
176        self.bundle = Some(bundle);
177        Ok(self)
178    }
179
180    /// Whether this storage carries multi-output bundle metadata.
181    pub fn is_bundled(&self) -> bool {
182        self.bundle.is_some()
183    }
184
185    /// Number of logical output slots in this storage. `1` for
186    /// single-output storage; for a bundled storage, the number of
187    /// [`OutputView`] entries.
188    pub fn slot_count(&self) -> usize {
189        match &self.bundle {
190            Some(b) => b.len(),
191            None => 1,
192        }
193    }
194
195    /// Borrow the full bundle slice, or `None` if this is a
196    /// single-output storage.
197    pub fn bundle(&self) -> Option<&[OutputView]> {
198        self.bundle.as_deref()
199    }
200
201    /// Clone the `Arc<[OutputView]>` handle. Used by `Op::View`'s
202    /// realization path: a View's output storage shares this Arc so
203    /// the bundle stays alive as long as any view holds a reference.
204    pub fn bundle_arc(&self) -> Option<Arc<[OutputView]>> {
205        self.bundle.clone()
206    }
207
208    /// Per-slot view for `idx`. Returns `None` for out-of-range
209    /// indices or for single-output storage with `idx != 0`. For
210    /// single-output storage with `idx == 0` this returns `None` as
211    /// well — the slot's dtype/shape live in the (`Storage::dtype`,
212    /// caller-supplied Layout) pair, NOT in a synthetic `OutputView`.
213    pub fn slot_view(&self, idx: usize) -> Option<&OutputView> {
214        self.bundle.as_deref().and_then(|b| b.get(idx))
215    }
216
217    /// Primary slot's dtype — for a bundled storage this is slot 0's
218    /// dtype (enforced equal to the inner backend dtype at construction
219    /// time); for single-output storage this is just the inner dtype.
220    /// Use [`Self::slot_dtype`] when the consumer is talking about a
221    /// specific bundle slot, not the primary one.
222    pub fn primary_dtype(&self) -> DType {
223        self.inner.dtype_dyn()
224    }
225
226    /// Dtype of a specific bundle slot. Returns `None` for
227    /// out-of-range indices or for single-output storage. For
228    /// single-output storage, callers should use [`Self::dtype`]
229    /// directly.
230    pub fn slot_dtype(&self, idx: usize) -> Option<DType> {
231        self.slot_view(idx).map(|v| v.dtype)
232    }
233
234    /// Borrow the inner storage as a `DynBackendStorage` trait object.
235    ///
236    /// Backends that need to peel back to their concrete storage type can
237    /// downcast via `storage.as_dyn().as_any().downcast_ref::<MyStorage>()`.
238    pub fn as_dyn(&self) -> &dyn DynBackendStorage {
239        &*self.inner
240    }
241
242    /// Mutable variant of [`Self::as_dyn`].
243    pub fn as_dyn_mut(&mut self) -> &mut dyn DynBackendStorage {
244        &mut *self.inner
245    }
246
247    /// Downcast the inner storage to a concrete backend type.
248    pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
249        self.inner.as_any().downcast_ref::<T>()
250    }
251
252    /// Mutable variant of [`downcast_ref`](Self::downcast_ref).
253    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
254        self.inner.as_any_mut().downcast_mut::<T>()
255    }
256
257    pub fn try_clone(&self, layout: &Layout) -> Result<Self> {
258        // Preserve the encoding scheme across a clone (v1: cloning a plain
259        // storage stays plain since `from_dyn` defaults empty; cloning an
260        // *encoded* storage must carry its `stype` forward).
261        Ok(Storage::from_dyn(self.inner.try_clone_dyn(layout)?).with_stype(self.stype.clone()))
262    }
263
264    /// Return an `Arc` to the owning device as a trait object.
265    /// fuel-core wraps this in its `Device` newtype; other consumers
266    /// (fuel-graph, tests) can use the trait object directly.
267    pub fn device(&self) -> Arc<dyn DynBackendDevice> {
268        self.inner.device_arc_dyn()
269    }
270
271    pub fn dtype(&self) -> DType {
272        self.inner.dtype_dyn()
273    }
274
275    /// Attach an encoding scheme to this storage (consuming builder).
276    /// Does not touch the bytes or the logical dtype — only describes HOW
277    /// 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    /// Pre-G this method consulted `Device::same_device` for the Metal
289    /// pointer-identity check; post-G it goes through the
290    /// `DynBackendDevice::same_device_dyn` trait method which has the
291    /// same semantics.
292    pub fn same_device(&self, rhs: &Self, op: &'static str) -> Result<()> {
293        let lhs_dev = self.inner.device_dyn();
294        let rhs_dev = rhs.inner.device_dyn();
295        let lhs_loc = lhs_dev.location_dyn();
296        let rhs_loc = rhs_dev.location_dyn();
297        let same = if matches!(lhs_loc, fuel_ir::DeviceLocation::Metal { .. }) {
298            // On metal, require physical identity (matches pre-G behaviour).
299            lhs_dev.same_device_dyn(rhs_dev)
300        } else {
301            lhs_loc == rhs_loc
302        };
303        if !same {
304            Err(Error::DeviceMismatchBinaryOp {
305                lhs: lhs_loc,
306                rhs: rhs_loc,
307                op,
308            }
309            .bt())
310        } else {
311            Ok(())
312        }
313    }
314
315    pub fn same_dtype(&self, rhs: &Self, op: &'static str) -> Result<()> {
316        let lhs = self.dtype();
317        let rhs = rhs.dtype();
318        if lhs != rhs {
319            Err(Error::DTypeMismatchBinaryOp { lhs, rhs, op }.bt())
320        } else {
321            Ok(())
322        }
323    }
324
325    pub fn const_set(&mut self, v: Scalar, l: &Layout) -> Result<()> {
326        self.inner.const_set_dyn(v, l)
327    }
328
329    pub fn affine(&self, layout: &Layout, mul: f64, add: f64) -> Result<Self> {
330        Ok(Storage::from_dyn(self.inner.affine_dyn(layout, mul, add)?))
331    }
332
333    pub fn powf(&self, layout: &Layout, e: f64) -> Result<Self> {
334        Ok(Storage::from_dyn(self.inner.powf_dyn(layout, e)?))
335    }
336
337    pub fn elu(&self, layout: &Layout, alpha: f64) -> Result<Self> {
338        Ok(Storage::from_dyn(self.inner.elu_dyn(layout, alpha)?))
339    }
340
341    pub fn cmp(
342        &self,
343        op: CmpOp,
344        rhs: &Self,
345        lhs_layout: &Layout,
346        rhs_layout: &Layout,
347    ) -> Result<Self> {
348        Ok(Storage::from_dyn(self.inner.cmp_dyn(
349            op,
350            &*rhs.inner,
351            lhs_layout,
352            rhs_layout,
353        )?))
354    }
355
356    pub fn reduce_op(&self, op: ReduceOp, layout: &Layout, reduce_dims: &[usize]) -> Result<Self> {
357        Ok(Storage::from_dyn(self.inner.reduce_op_dyn(
358            op,
359            layout,
360            reduce_dims,
361        )?))
362    }
363
364    pub fn to_dtype(&self, layout: &Layout, dtype: DType) -> Result<Self> {
365        Ok(Storage::from_dyn(self.inner.to_dtype_dyn(layout, dtype)?))
366    }
367
368    pub fn to_cpu_storage(&self) -> Result<HostBuffer> {
369        self.inner.to_host_buffer_dyn()
370    }
371
372    // -----------------------------------------------------------------------
373    // Unary / Binary dispatch
374    // -----------------------------------------------------------------------
375
376    pub fn unary_impl<B: op::UnaryOpT>(&self, layout: &Layout) -> Result<Self> {
377        let op = op::UnaryOp::from_name(B::NAME)
378            .ok_or_else(|| Error::Msg(format!("unknown unary op '{}'", B::NAME)))?;
379        Ok(Storage::from_dyn(self.inner.unary_op_dyn(layout, op)?))
380    }
381
382    pub fn binary_impl<B: op::BinaryOpT>(
383        &self,
384        rhs: &Self,
385        lhs_layout: &Layout,
386        rhs_layout: &Layout,
387    ) -> Result<Self> {
388        self.same_device(rhs, B::NAME)?;
389        self.same_dtype(rhs, B::NAME)?;
390        let op = BinaryOp::from_name(B::NAME)
391            .ok_or_else(|| Error::Msg(format!("unknown binary op '{}'", B::NAME)))?;
392        Ok(Storage::from_dyn(self.inner.binary_op_dyn(
393            &*rhs.inner,
394            lhs_layout,
395            rhs_layout,
396            op,
397        )?))
398    }
399
400    // -----------------------------------------------------------------------
401    // Convolutions, pooling, upsampling
402    // -----------------------------------------------------------------------
403
404    pub fn conv1d(
405        &self,
406        l: &Layout,
407        kernel: &Self,
408        kernel_l: &Layout,
409        params: &conv::ParamsConv1D,
410    ) -> Result<Self> {
411        self.same_device(kernel, "conv1d")?;
412        self.same_dtype(kernel, "conv1d")?;
413        Ok(Storage::from_dyn(self.inner.conv1d_dyn(
414            l,
415            &*kernel.inner,
416            kernel_l,
417            params,
418        )?))
419    }
420
421    pub fn conv_transpose1d(
422        &self,
423        l: &Layout,
424        kernel: &Self,
425        kernel_l: &Layout,
426        params: &conv::ParamsConvTranspose1D,
427    ) -> Result<Self> {
428        self.same_device(kernel, "conv-transpose1d")?;
429        self.same_dtype(kernel, "conv-transpose1d")?;
430        Ok(Storage::from_dyn(self.inner.conv_transpose1d_dyn(
431            l,
432            &*kernel.inner,
433            kernel_l,
434            params,
435        )?))
436    }
437
438    pub fn conv2d(
439        &self,
440        l: &Layout,
441        kernel: &Self,
442        kernel_l: &Layout,
443        params: &conv::ParamsConv2D,
444    ) -> Result<Self> {
445        self.same_device(kernel, "conv2d")?;
446        self.same_dtype(kernel, "conv2d")?;
447        Ok(Storage::from_dyn(self.inner.conv2d_dyn(
448            l,
449            &*kernel.inner,
450            kernel_l,
451            params,
452        )?))
453    }
454
455    pub fn conv_transpose2d(
456        &self,
457        l: &Layout,
458        kernel: &Self,
459        kernel_l: &Layout,
460        params: &conv::ParamsConvTranspose2D,
461    ) -> Result<Self> {
462        self.same_device(kernel, "conv_transpose2d")?;
463        self.same_dtype(kernel, "conv_transpose2d")?;
464        Ok(Storage::from_dyn(self.inner.conv_transpose2d_dyn(
465            l,
466            &*kernel.inner,
467            kernel_l,
468            params,
469        )?))
470    }
471
472    pub fn avg_pool2d(
473        &self,
474        layout: &Layout,
475        kernel_size: (usize, usize),
476        stride: (usize, usize),
477    ) -> Result<Self> {
478        Ok(Storage::from_dyn(self.inner.avg_pool2d_dyn(
479            layout,
480            kernel_size,
481            stride,
482        )?))
483    }
484
485    pub fn max_pool2d(
486        &self,
487        layout: &Layout,
488        kernel_size: (usize, usize),
489        stride: (usize, usize),
490    ) -> Result<Self> {
491        Ok(Storage::from_dyn(self.inner.max_pool2d_dyn(
492            layout,
493            kernel_size,
494            stride,
495        )?))
496    }
497
498    pub fn upsample_nearest1d(&self, layout: &Layout, sz: usize) -> Result<Self> {
499        Ok(Storage::from_dyn(
500            self.inner.upsample_nearest1d_dyn(layout, sz)?,
501        ))
502    }
503
504    pub fn upsample_nearest2d(&self, layout: &Layout, h: usize, w: usize) -> Result<Self> {
505        Ok(Storage::from_dyn(
506            self.inner.upsample_nearest2d_dyn(layout, h, w)?,
507        ))
508    }
509
510    pub fn upsample_bilinear2d(
511        &self,
512        layout: &Layout,
513        h: usize,
514        w: usize,
515        align_corners: bool,
516        scale_h: Option<f64>,
517        scale_w: Option<f64>,
518    ) -> Result<Self> {
519        Ok(Storage::from_dyn(self.inner.upsample_bilinear2d_dyn(
520            layout,
521            h,
522            w,
523            align_corners,
524            scale_h,
525            scale_w,
526        )?))
527    }
528
529    // -----------------------------------------------------------------------
530    // Gather / Scatter / Index
531    // -----------------------------------------------------------------------
532
533    pub fn where_cond(
534        &self,
535        layout: &Layout,
536        t: &Self,
537        layout_t: &Layout,
538        f: &Self,
539        layout_f: &Layout,
540    ) -> Result<Self> {
541        self.same_device(t, "where")?;
542        self.same_device(f, "where")?;
543        t.same_dtype(f, "where")?;
544        Ok(Storage::from_dyn(self.inner.where_cond_dyn(
545            layout, &*t.inner, layout_t, &*f.inner, layout_f,
546        )?))
547    }
548
549    pub fn gather(&self, l: &Layout, indexes: &Self, indexes_l: &Layout, d: usize) -> Result<Self> {
550        self.same_device(indexes, "index-add")?;
551        Ok(Storage::from_dyn(self.inner.gather_dyn(
552            l,
553            &*indexes.inner,
554            indexes_l,
555            d,
556        )?))
557    }
558
559    pub fn scatter_set(
560        &mut self,
561        l: &Layout,
562        indexes: &Self,
563        indexes_l: &Layout,
564        source: &Self,
565        source_l: &Layout,
566        d: usize,
567    ) -> Result<()> {
568        self.same_device(indexes, "scatter-set")?;
569        self.same_device(source, "scatter-set")?;
570        self.inner
571            .scatter_set_dyn(l, &*source.inner, source_l, &*indexes.inner, indexes_l, d)
572    }
573
574    pub fn scatter_add(
575        &mut self,
576        l: &Layout,
577        indexes: &Self,
578        indexes_l: &Layout,
579        source: &Self,
580        source_l: &Layout,
581        d: usize,
582    ) -> Result<()> {
583        self.same_device(indexes, "scatter-add")?;
584        self.same_device(source, "scatter-add")?;
585        self.inner
586            .scatter_add_set_dyn(l, &*source.inner, source_l, &*indexes.inner, indexes_l, d)
587    }
588
589    pub fn index_add(
590        &self,
591        l: &Layout,
592        indexes: &Self,
593        indexes_l: &Layout,
594        source: &Self,
595        source_l: &Layout,
596        d: usize,
597    ) -> Result<Self> {
598        self.same_device(indexes, "index-add")?;
599        self.same_device(source, "index-add")?;
600        Ok(Storage::from_dyn(self.inner.index_add_dyn(
601            l,
602            &*indexes.inner,
603            indexes_l,
604            &*source.inner,
605            source_l,
606            d,
607        )?))
608    }
609
610    pub fn index_select(
611        &self,
612        rhs: &Self,
613        lhs_l: &Layout,
614        rhs_l: &Layout,
615        d: usize,
616    ) -> Result<Self> {
617        self.same_device(rhs, "index-select")?;
618        Ok(Storage::from_dyn(self.inner.index_select_dyn(
619            &*rhs.inner,
620            lhs_l,
621            rhs_l,
622            d,
623        )?))
624    }
625
626    // -----------------------------------------------------------------------
627    // Matmul and copy
628    // -----------------------------------------------------------------------
629
630    pub fn matmul(
631        &self,
632        rhs: &Self,
633        bmnk: (usize, usize, usize, usize),
634        lhs_layout: &Layout,
635        rhs_layout: &Layout,
636    ) -> Result<Self> {
637        self.same_device(rhs, "matmul")?;
638        self.same_dtype(rhs, "matmul")?;
639        Ok(Storage::from_dyn(self.inner.matmul_dyn(
640            &*rhs.inner,
641            bmnk,
642            lhs_layout,
643            rhs_layout,
644        )?))
645    }
646
647    /// `self`, the source, can be strided whereas `dst` is contiguous.
648    pub fn copy_strided_src(
649        &self,
650        dst: &mut Self,
651        dst_offset: usize,
652        src_l: &Layout,
653    ) -> Result<()> {
654        self.inner
655            .copy_strided_src_dyn(&mut *dst.inner, dst_offset, src_l)
656    }
657
658    pub fn copy2d(
659        &self,
660        dst: &mut Self,
661        d1: usize,
662        d2: usize,
663        src_s: usize,
664        dst_s: usize,
665        src_o: usize,
666        dst_o: usize,
667    ) -> Result<()> {
668        self.inner
669            .copy2d_dyn(&mut *dst.inner, d1, d2, src_s, dst_s, src_o, dst_o)
670    }
671}
672
673#[cfg(test)]
674mod multi_output_specs {
675    use super::*;
676
677    /// Helper: contiguous F32 spec of the given shape.
678    fn f32_spec(dims: &[usize]) -> OutputViewSpec {
679        OutputViewSpec::contiguous(DType::F32, Shape::from_dims(dims))
680    }
681
682    /// Helper: contiguous F64 spec of the given shape.
683    fn f64_spec(dims: &[usize]) -> OutputViewSpec {
684        OutputViewSpec::contiguous(DType::F64, Shape::from_dims(dims))
685    }
686
687    /// compose_bundle composes a single-slot spec into one OutputView
688    /// with byte_offset 0 and total_bytes equal to the slot's
689    /// footprint.
690    #[test]
691    fn compose_bundle_single_slot() {
692        let specs = vec![f32_spec(&[2, 3])];
693        let (total, views) = compose_bundle(&specs).expect("single slot composes");
694        assert_eq!(views.len(), 1);
695        assert_eq!(views[0].byte_offset, 0);
696        assert_eq!(views[0].len_elements, 6);
697        assert_eq!(views[0].dtype, DType::F32);
698        assert_eq!(total, 24); // 6 * 4 bytes
699    }
700
701    /// compose_bundle stacks slots with per-slot dtype alignment.
702    /// Slot 0 = F32[6] = 24 bytes (aligned to 4).
703    /// Slot 1 = F64[3] = 24 bytes (aligned to 8). cursor at 24 is
704    /// already aligned to 8, so byte_offset = 24.
705    #[test]
706    fn compose_bundle_two_slot_aligned() {
707        let specs = vec![f32_spec(&[2, 3]), f64_spec(&[3])];
708        let (total, views) = compose_bundle(&specs).expect("aligned compose");
709        assert_eq!(views.len(), 2);
710        assert_eq!(views[0].byte_offset, 0);
711        assert_eq!(views[0].len_elements, 6);
712        assert_eq!(views[1].byte_offset, 24);
713        assert_eq!(views[1].len_elements, 3);
714        assert_eq!(views[1].dtype, DType::F64);
715        assert_eq!(total, 48); // 24 (slot 0) + 24 (slot 1)
716    }
717
718    /// compose_bundle pads when slot 1's alignment requires it.
719    /// Slot 0 = F32[1] = 4 bytes, cursor at 4.
720    /// Slot 1 = F64[1], alignment 8; 4 % 8 = 4, pad to 8. byte_offset = 8.
721    #[test]
722    fn compose_bundle_pads_for_alignment() {
723        let specs = vec![f32_spec(&[1]), f64_spec(&[1])];
724        let (total, views) = compose_bundle(&specs).expect("padded compose");
725        assert_eq!(views[0].byte_offset, 0);
726        assert_eq!(views[1].byte_offset, 8); // padded from 4 to next-8-multiple
727        assert_eq!(total, 16); // 8 (start of slot 1) + 8 (slot 1)
728    }
729
730    /// compose_bundle rejects an empty spec list.
731    #[test]
732    fn compose_bundle_rejects_empty() {
733        let err = compose_bundle(&[]).expect_err("empty spec list must error");
734        assert!(format!("{err}").contains("non-empty"));
735    }
736
737    /// compose_bundle rejects a spec whose layout.shape() disagrees
738    /// with its declared shape (mirrors with_bundle's invariant).
739    #[test]
740    fn compose_bundle_rejects_shape_layout_mismatch() {
741        let s = Shape::from_dims(&[2, 3]);
742        let bogus_layout = Layout::contiguous(Shape::from_dims(&[3, 2]));
743        let bad = OutputViewSpec {
744            dtype: DType::F32,
745            shape: s,
746            layout: bogus_layout,
747            name: None,
748        };
749        let err = compose_bundle(&[bad]).expect_err("shape/layout mismatch must error");
750        assert!(format!("{err}").contains("disagrees"));
751    }
752
753    /// OutputViewSpec::contiguous wires the default layout correctly.
754    #[test]
755    fn output_view_spec_contiguous_helper() {
756        let s = f32_spec(&[4, 5]);
757        assert_eq!(s.dtype, DType::F32);
758        assert_eq!(s.shape, Shape::from_dims(&[4, 5]));
759        assert_eq!(s.layout.shape(), &Shape::from_dims(&[4, 5]));
760        assert_eq!(s.elem_count(), 20);
761        assert_eq!(s.len_bytes(), 80);
762        assert!(s.name.is_none());
763    }
764}
765
766#[cfg(test)]
767mod stype_attach {
768    //! Step 2 born-red coverage for the trait-object `Storage`'s `stype`
769    //! field. There is no concrete `DynBackendStorage` impl in this crate
770    //! (backends live downstream and would cycle as a dev-dep), so the test
771    //! uses a minimal mock whose only real method is `try_clone_dyn`.
772    use super::*;
773    use fuel_ir::op::UnaryOp;
774    use std::any::Any;
775
776    /// Minimal `DynBackendStorage`: an empty unit struct. Only
777    /// `try_clone_dyn` / `dtype_dyn` / `as_any*` are exercised; every other
778    /// method panics (never called by these tests).
779    #[derive(Debug)]
780    struct MockStorage;
781
782    #[allow(unused_variables)]
783    impl DynBackendStorage for MockStorage {
784        fn try_clone_dyn(&self, _layout: &Layout) -> Result<Box<dyn DynBackendStorage>> {
785            Ok(Box::new(MockStorage))
786        }
787        fn dtype_dyn(&self) -> DType {
788            DType::F32
789        }
790        fn as_any(&self) -> &dyn Any {
791            self
792        }
793        fn as_any_mut(&mut self) -> &mut dyn Any {
794            self
795        }
796
797        fn device_dyn(&self) -> &dyn DynBackendDevice {
798            unimplemented!()
799        }
800        fn device_arc_dyn(&self) -> Arc<dyn DynBackendDevice> {
801            unimplemented!()
802        }
803        fn to_host_buffer_dyn(&self) -> Result<HostBuffer> {
804            unimplemented!()
805        }
806        fn affine_dyn(&self, l: &Layout, mul: f64, add: f64) -> Result<Box<dyn DynBackendStorage>> {
807            unimplemented!()
808        }
809        fn powf_dyn(&self, l: &Layout, e: f64) -> Result<Box<dyn DynBackendStorage>> {
810            unimplemented!()
811        }
812        fn elu_dyn(&self, l: &Layout, alpha: f64) -> Result<Box<dyn DynBackendStorage>> {
813            unimplemented!()
814        }
815        fn reduce_op_dyn(
816            &self,
817            op: ReduceOp,
818            l: &Layout,
819            axes: &[usize],
820        ) -> Result<Box<dyn DynBackendStorage>> {
821            unimplemented!()
822        }
823        fn cmp_dyn(
824            &self,
825            op: CmpOp,
826            rhs: &dyn DynBackendStorage,
827            ll: &Layout,
828            rl: &Layout,
829        ) -> Result<Box<dyn DynBackendStorage>> {
830            unimplemented!()
831        }
832        fn to_dtype_dyn(&self, l: &Layout, dtype: DType) -> Result<Box<dyn DynBackendStorage>> {
833            unimplemented!()
834        }
835        fn unary_op_dyn(&self, l: &Layout, op: UnaryOp) -> Result<Box<dyn DynBackendStorage>> {
836            unimplemented!()
837        }
838        fn binary_op_dyn(
839            &self,
840            rhs: &dyn DynBackendStorage,
841            ll: &Layout,
842            rl: &Layout,
843            op: BinaryOp,
844        ) -> Result<Box<dyn DynBackendStorage>> {
845            unimplemented!()
846        }
847        fn where_cond_dyn(
848            &self,
849            cl: &Layout,
850            t: &dyn DynBackendStorage,
851            tl: &Layout,
852            f: &dyn DynBackendStorage,
853            fl: &Layout,
854        ) -> Result<Box<dyn DynBackendStorage>> {
855            unimplemented!()
856        }
857        fn conv1d_dyn(
858            &self,
859            l: &Layout,
860            k: &dyn DynBackendStorage,
861            kl: &Layout,
862            p: &conv::ParamsConv1D,
863        ) -> Result<Box<dyn DynBackendStorage>> {
864            unimplemented!()
865        }
866        fn conv_transpose1d_dyn(
867            &self,
868            l: &Layout,
869            k: &dyn DynBackendStorage,
870            kl: &Layout,
871            p: &conv::ParamsConvTranspose1D,
872        ) -> Result<Box<dyn DynBackendStorage>> {
873            unimplemented!()
874        }
875        fn conv2d_dyn(
876            &self,
877            l: &Layout,
878            k: &dyn DynBackendStorage,
879            kl: &Layout,
880            p: &conv::ParamsConv2D,
881        ) -> Result<Box<dyn DynBackendStorage>> {
882            unimplemented!()
883        }
884        fn conv_transpose2d_dyn(
885            &self,
886            l: &Layout,
887            k: &dyn DynBackendStorage,
888            kl: &Layout,
889            p: &conv::ParamsConvTranspose2D,
890        ) -> Result<Box<dyn DynBackendStorage>> {
891            unimplemented!()
892        }
893        fn avg_pool2d_dyn(
894            &self,
895            l: &Layout,
896            k: (usize, usize),
897            s: (usize, usize),
898        ) -> Result<Box<dyn DynBackendStorage>> {
899            unimplemented!()
900        }
901        fn max_pool2d_dyn(
902            &self,
903            l: &Layout,
904            k: (usize, usize),
905            s: (usize, usize),
906        ) -> Result<Box<dyn DynBackendStorage>> {
907            unimplemented!()
908        }
909        fn upsample_nearest1d_dyn(
910            &self,
911            l: &Layout,
912            t: usize,
913        ) -> Result<Box<dyn DynBackendStorage>> {
914            unimplemented!()
915        }
916        fn upsample_nearest2d_dyn(
917            &self,
918            l: &Layout,
919            h: usize,
920            w: usize,
921        ) -> Result<Box<dyn DynBackendStorage>> {
922            unimplemented!()
923        }
924        fn upsample_bilinear2d_dyn(
925            &self,
926            l: &Layout,
927            h: usize,
928            w: usize,
929            ac: bool,
930            sh: Option<f64>,
931            sw: Option<f64>,
932        ) -> Result<Box<dyn DynBackendStorage>> {
933            unimplemented!()
934        }
935        fn gather_dyn(
936            &self,
937            sl: &Layout,
938            ids: &dyn DynBackendStorage,
939            il: &Layout,
940            dim: usize,
941        ) -> Result<Box<dyn DynBackendStorage>> {
942            unimplemented!()
943        }
944        fn scatter_set_dyn(
945            &mut self,
946            sl: &Layout,
947            src: &dyn DynBackendStorage,
948            srl: &Layout,
949            ids: &dyn DynBackendStorage,
950            il: &Layout,
951            dim: usize,
952        ) -> Result<()> {
953            unimplemented!()
954        }
955        fn scatter_add_set_dyn(
956            &mut self,
957            sl: &Layout,
958            src: &dyn DynBackendStorage,
959            srl: &Layout,
960            ids: &dyn DynBackendStorage,
961            il: &Layout,
962            dim: usize,
963        ) -> Result<()> {
964            unimplemented!()
965        }
966        fn index_select_dyn(
967            &self,
968            ids: &dyn DynBackendStorage,
969            sl: &Layout,
970            il: &Layout,
971            dim: usize,
972        ) -> Result<Box<dyn DynBackendStorage>> {
973            unimplemented!()
974        }
975        fn index_add_dyn(
976            &self,
977            sl: &Layout,
978            ids: &dyn DynBackendStorage,
979            il: &Layout,
980            src: &dyn DynBackendStorage,
981            srl: &Layout,
982            dim: usize,
983        ) -> Result<Box<dyn DynBackendStorage>> {
984            unimplemented!()
985        }
986        fn matmul_dyn(
987            &self,
988            rhs: &dyn DynBackendStorage,
989            bmnk: (usize, usize, usize, usize),
990            ll: &Layout,
991            rl: &Layout,
992        ) -> Result<Box<dyn DynBackendStorage>> {
993            unimplemented!()
994        }
995        fn copy_strided_src_dyn(
996            &self,
997            dst: &mut dyn DynBackendStorage,
998            off: usize,
999            sl: &Layout,
1000        ) -> Result<()> {
1001            unimplemented!()
1002        }
1003        fn copy2d_dyn(
1004            &self,
1005            dst: &mut dyn DynBackendStorage,
1006            d1: usize,
1007            d2: usize,
1008            ss1: usize,
1009            ds1: usize,
1010            so: usize,
1011            dofs: usize,
1012        ) -> Result<()> {
1013            unimplemented!()
1014        }
1015        fn const_set_dyn(&mut self, value: Scalar, l: &Layout) -> Result<()> {
1016            unimplemented!()
1017        }
1018    }
1019
1020    /// Born-red: a freshly constructed trait-object Storage carries a plain
1021    /// (empty) SType by default.
1022    #[test]
1023    fn trait_object_storage_defaults_plain() {
1024        let s = Storage::new(MockStorage);
1025        assert!(
1026            s.stype().is_plain(),
1027            "default Storage must carry a plain SType"
1028        );
1029        assert_eq!(s.stype().layers().len(), 0);
1030    }
1031
1032    /// Born-red: `try_clone` carries an attached `stype` forward (the cheap,
1033    /// correct v1 choice — cloning an encoded storage preserves its scheme).
1034    #[test]
1035    fn try_clone_preserves_stype() {
1036        use fuel_ir::GgmlDType;
1037        use fuel_ir::stype::Encoding;
1038        let s = Storage::new(MockStorage).with_stype(SType::from_layer(Encoding::GgmlBlock {
1039            ggml_dtype: GgmlDType::Q4_0,
1040        }));
1041        let layout = Layout::contiguous(Shape::from_dims(&[4]));
1042        let cloned = s.try_clone(&layout).expect("clone");
1043        assert_eq!(cloned.stype(), s.stype(), "try_clone must preserve stype");
1044        assert!(!cloned.stype().is_plain());
1045    }
1046}