fuel-tensor 0.19.1

Fuel's user-facing Tensor handle and Device abstraction — the central, near-universal consumer surface of the former fuel-core (board #109; CireSnave: "Move Tensor into fuel-tensor. We can worry about a semantic split later.")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Device abstraction for CPU, CUDA, and Metal backends.
//!
//! ```rust
//! use fuel_tensor::Device;
//! let dev = Device::cpu();
//! assert!(dev.is_cpu());
//! assert_eq!(dev.location(), fuel_tensor::DeviceLocation::Cpu);
//! ```
use crate::{DType, HostBuffer, Result, Shape, Storage, WithDType};
use fuel_backend_contract::dyn_backend::DynBackendDevice;
use fuel_cpu_backend::dyn_impl::CpuBackendDevice;
use std::sync::Arc;

pub use fuel_ir::DeviceLocation;

/// A device on which tensors can be created and computations performed.
///
/// Internally this is an `Arc<dyn DynBackendDevice>` — a trait-object handle
/// to the concrete backend device.  CPU, CUDA, Metal, and arbitrary third-party
/// backends are all accessed through this single type.
///
/// # Example
///
/// ```rust
/// use fuel_tensor::{Device, DType};
/// use fuel_tensor::lazy::Tensor;
/// let dev = Device::cpu();
/// let t = Tensor::zeros((2, 3), DType::F32, &dev)?;
/// assert_eq!(t.shape().dims(), &[2, 3]);
/// # Ok::<(), fuel_tensor::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct Device {
    pub(crate) inner: Arc<dyn DynBackendDevice>,
}

/// Trait for host array-like values that describe their shape and yield CPU storage.
///
/// Implemented for scalars, arrays, slices, and nested vecs up to 4 dimensions.
/// It lets array-like Rust values report the [`Shape`] their data describes and
/// materialize into a [`HostBuffer`] — the raw material a lazy tensor is built from.
///
/// # Example
///
/// ```rust
/// use fuel_tensor::NdArray;
/// // Scalars, arrays, and nested arrays all implement `NdArray` and report
/// // the shape their data describes.
/// assert_eq!(3.14f32.shape()?.dims(), &[] as &[usize]);
/// assert_eq!((&[1f32, 2., 3.]).shape()?.dims(), &[3]);
/// assert_eq!((&[[1f32, 2.], [3., 4.]]).shape()?.dims(), &[2, 2]);
/// # Ok::<(), fuel_tensor::Error>(())
/// ```
pub trait NdArray {
    /// Returns the shape determined by this array-like value.
    fn shape(&self) -> Result<Shape>;

    /// Converts this value into CPU storage.
    fn to_cpu_storage(&self) -> HostBuffer;
}

impl<S: WithDType> NdArray for S {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from(()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        S::to_cpu_storage(&[*self])
    }
}

impl<S: WithDType, const N: usize> NdArray for &[S; N] {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from(self.len()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        S::to_cpu_storage(self.as_slice())
    }
}

impl<S: WithDType> NdArray for &[S] {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from(self.len()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        S::to_cpu_storage(self)
    }
}

impl<S: WithDType, const N: usize, const M: usize> NdArray for &[[S; N]; M] {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from((M, N)))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        S::to_cpu_storage_owned(self.concat())
    }
}

impl<S: WithDType, const N1: usize, const N2: usize, const N3: usize> NdArray
    for &[[[S; N3]; N2]; N1]
{
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from((N1, N2, N3)))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        let mut vec = Vec::with_capacity(N1 * N2 * N3);
        for i1 in 0..N1 {
            for i2 in 0..N2 {
                vec.extend(self[i1][i2])
            }
        }
        S::to_cpu_storage_owned(vec)
    }
}

impl<S: WithDType, const N1: usize, const N2: usize, const N3: usize, const N4: usize> NdArray
    for &[[[[S; N4]; N3]; N2]; N1]
{
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from((N1, N2, N3, N4)))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        let mut vec = Vec::with_capacity(N1 * N2 * N3 * N4);
        for i1 in 0..N1 {
            for i2 in 0..N2 {
                for i3 in 0..N3 {
                    vec.extend(self[i1][i2][i3])
                }
            }
        }
        S::to_cpu_storage_owned(vec)
    }
}

impl<S: WithDType> NdArray for Vec<S> {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from(self.len()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        S::to_cpu_storage(self.as_slice())
    }
}

impl<S: WithDType> NdArray for Vec<&[S]> {
    fn shape(&self) -> Result<Shape> {
        if self.is_empty() {
            crate::bail!("empty array")
        }
        let n = self.len();
        let m = self[0].len();
        for v in self.iter() {
            if v.len() != m {
                crate::bail!("two elements have different len {m} {}", v.len())
            }
        }
        Ok(Shape::from((n, m)))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        let data = self.iter().copied().flatten().copied().collect::<Vec<_>>();
        S::to_cpu_storage_owned(data)
    }
}

impl<S: WithDType> NdArray for Vec<Vec<S>> {
    fn shape(&self) -> Result<Shape> {
        if self.is_empty() {
            crate::bail!("empty array")
        }
        let n = self.len();
        let m = self[0].len();
        for v in self.iter() {
            if v.len() != m {
                crate::bail!("two elements have different len {m} {}", v.len())
            }
        }
        Ok(Shape::from((n, m)))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        let len: usize = self.iter().map(|v| v.len()).sum();
        let mut dst = Vec::with_capacity(len);
        for v in self.iter() {
            dst.extend(v.iter().copied());
        }
        S::to_cpu_storage_owned(dst)
    }
}

impl<S: WithDType> NdArray for Vec<Vec<Vec<S>>> {
    fn shape(&self) -> Result<Shape> {
        if self.is_empty() {
            crate::bail!("empty array")
        }
        let shape0 = self[0].shape()?;
        let n = self.len();
        for v in self.iter() {
            let shape = v.shape()?;
            if shape != shape0 {
                crate::bail!("two elements have different shapes {shape:?} {shape0:?}")
            }
        }
        Ok(Shape::from([[n].as_slice(), shape0.dims()].concat()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        if self.is_empty() {
            return S::to_cpu_storage_owned(vec![]);
        }
        let len: usize = self
            .iter()
            .map(|v| v.iter().map(|v| v.len()).sum::<usize>())
            .sum();
        let mut dst = Vec::with_capacity(len);
        for v1 in self.iter() {
            for v2 in v1.iter() {
                dst.extend(v2.iter().copied());
            }
        }
        S::to_cpu_storage_owned(dst)
    }
}

impl<S: WithDType> NdArray for Vec<Vec<Vec<Vec<S>>>> {
    fn shape(&self) -> Result<Shape> {
        if self.is_empty() {
            crate::bail!("empty array")
        }
        let shape0 = self[0].shape()?;
        let n = self.len();
        for v in self.iter() {
            let shape = v.shape()?;
            if shape != shape0 {
                crate::bail!("two elements have different shapes {shape:?} {shape0:?}")
            }
        }
        Ok(Shape::from([[n].as_slice(), shape0.dims()].concat()))
    }

    fn to_cpu_storage(&self) -> HostBuffer {
        let len: usize = self
            .iter()
            .map(|v| {
                v.iter()
                    .map(|v| v.iter().map(|v| v.len()).sum::<usize>())
                    .sum::<usize>()
            })
            .sum();
        let mut dst = Vec::with_capacity(len);
        for v1 in self.iter() {
            for v2 in v1.iter() {
                for v3 in v2.iter() {
                    dst.extend(v3.iter().copied());
                }
            }
        }
        S::to_cpu_storage_owned(dst)
    }
}

impl Device {
    /// Returns a CPU device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// let dev = Device::cpu();
    /// assert!(dev.is_cpu());
    /// ```
    pub fn cpu() -> Self {
        Device {
            inner: Arc::new(CpuBackendDevice),
        }
    }

    /// Creates a device backed by a custom [`DynBackendDevice`].
    ///
    /// The device uses dynamic dispatch for all operations, enabling
    /// third-party backends without modifying `fuel-core`.
    pub fn custom(device: Arc<dyn DynBackendDevice>) -> Self {
        Device { inner: device }
    }

    /// Borrow the underlying `Arc<dyn DynBackendDevice>`.
    ///
    /// Phase 7.5 work item G2: fuel-graph's slot-populating
    /// constructors (`Tensor::from_f32`, `const_f32_like`, etc.) take
    /// a `&Arc<dyn DynBackendDevice>` so they can allocate Storage on
    /// the right device without depending on fuel-core. Callers that
    /// hold a `&fuel_tensor::Device` thread it through with
    /// `dev.as_dyn()`.
    pub fn as_dyn(&self) -> &Arc<dyn DynBackendDevice> {
        &self.inner
    }

    /// Returns `true` if this is a custom (third-party) device.
    pub fn is_custom(&self) -> bool {
        !self.is_cpu() && !self.is_cuda() && !self.is_metal()
    }

    /// Sets the random seed for this device's random number generator.
    pub fn set_seed(&self, seed: u64) -> Result<()> {
        self.inner.set_seed_dyn(seed)
    }

    /// Returns the current random seed for this device.
    pub fn get_current_seed(&self) -> Result<u64> {
        self.inner.get_current_seed_dyn()
    }

    /// Returns `true` if both devices refer to the same physical device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// assert!(Device::cpu().same_device(&Device::cpu()));
    /// ```
    pub fn same_device(&self, rhs: &Self) -> bool {
        self.inner.same_device_dyn(&*rhs.inner)
    }

    /// Returns the physical [`DeviceLocation`] for this device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::{Device, DeviceLocation};
    /// assert_eq!(Device::cpu().location(), DeviceLocation::Cpu);
    /// ```
    pub fn location(&self) -> DeviceLocation {
        self.inner.location_dyn()
    }

    /// Returns `true` if this is the CPU device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// assert!(Device::cpu().is_cpu());
    /// ```
    pub fn is_cpu(&self) -> bool {
        matches!(self.location(), DeviceLocation::Cpu)
    }

    /// Returns `true` if this is a CUDA device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// assert!(!Device::cpu().is_cuda());
    /// ```
    pub fn is_cuda(&self) -> bool {
        matches!(self.location(), DeviceLocation::Cuda { .. })
    }

    /// Returns `true` if this is a Metal device.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// assert!(!Device::cpu().is_metal());
    /// ```
    pub fn is_metal(&self) -> bool {
        matches!(self.location(), DeviceLocation::Metal { .. })
    }

    /// Returns `true` if this device has native BF16 support.
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// // CPU does not have native BF16 support
    /// assert!(!Device::cpu().supports_bf16());
    /// ```
    pub fn supports_bf16(&self) -> bool {
        self.inner.supports_bf16()
    }

    /// Returns [`DType::BF16`] if supported, otherwise [`DType::F32`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use fuel_tensor::{Device, DType};
    /// assert_eq!(Device::cpu().bf16_default_to_f32(), DType::F32);
    /// ```
    pub fn bf16_default_to_f32(&self) -> DType {
        if self.supports_bf16() {
            DType::BF16
        } else {
            DType::F32
        }
    }

    // Backend-delegating RNG + zeros path (`self.inner.{rand_*,zeros}_dyn`).
    // Currently unused: the lazy graph never takes this path — `Tensor::randn`
    // builds host-side via `rand_distr::Normal` and uploads through `from_f32`,
    // and these methods' only callers are the `_f64`-to-generic delegations
    // just below. They are SUPERSEDED, not vestigial: GAP-023 (the
    // `Op::RandomBits` generator seam, Tier A) is the replacement. DELETE all
    // five the moment `Op::RandomBits` lands in the op enum — that is the
    // owned, dated deletion trigger this #[allow] is recorded against.
    #[allow(dead_code)]
    pub(crate) fn rand_uniform_f64(
        &self,
        lo: f64,
        up: f64,
        shape: &Shape,
        dtype: DType,
    ) -> Result<Storage> {
        // CUDA doesn't support generating F16/BF16 directly; generate as F32 then convert.
        if self.is_cuda() && (dtype == DType::F16 || dtype == DType::BF16) {
            let storage =
                Storage::from_dyn(self.inner.rand_uniform_dyn(shape, DType::F32, lo, up)?);
            storage.to_dtype(&crate::Layout::contiguous(shape), dtype)
        } else {
            Ok(Storage::from_dyn(
                self.inner.rand_uniform_dyn(shape, dtype, lo, up)?,
            ))
        }
    }

    #[allow(dead_code)] // superseded RNG path — delete with GAP-023 (Op::RandomBits)
    pub(crate) fn rand_uniform<T: crate::FloatDType>(
        &self,
        lo: T,
        up: T,
        shape: &Shape,
    ) -> Result<Storage> {
        self.rand_uniform_f64(lo.to_f64(), up.to_f64(), shape, T::DTYPE)
    }

    #[allow(dead_code)] // superseded RNG path — delete with GAP-023 (Op::RandomBits)
    pub(crate) fn rand_normal_f64(
        &self,
        mean: f64,
        std: f64,
        shape: &Shape,
        dtype: DType,
    ) -> Result<Storage> {
        // CUDA doesn't support generating F16/BF16 directly; generate as F32 then convert.
        if self.is_cuda() && (dtype == DType::F16 || dtype == DType::BF16) {
            let storage =
                Storage::from_dyn(self.inner.rand_normal_dyn(shape, DType::F32, mean, std)?);
            storage.to_dtype(&crate::Layout::contiguous(shape), dtype)
        } else {
            Ok(Storage::from_dyn(
                self.inner.rand_normal_dyn(shape, dtype, mean, std)?,
            ))
        }
    }

    #[allow(dead_code)] // superseded RNG path — delete with GAP-023 (Op::RandomBits)
    pub(crate) fn rand_normal<T: crate::FloatDType>(
        &self,
        mean: T,
        std: T,
        shape: &Shape,
    ) -> Result<Storage> {
        self.rand_normal_f64(mean.to_f64(), std.to_f64(), shape, T::DTYPE)
    }

    #[allow(dead_code)] // superseded RNG path — delete with GAP-023 (Op::RandomBits)
    pub(crate) fn zeros(&self, shape: &Shape, dtype: DType) -> Result<Storage> {
        Ok(Storage::from_dyn(self.inner.zeros_impl_dyn(shape, dtype)?))
    }

    /// Synchronizes the device, waiting for all pending operations to complete.
    ///
    /// This is a no-op on CPU.
    ///
    /// ```rust
    /// use fuel_tensor::Device;
    /// Device::cpu().synchronize()?;
    /// # Ok::<(), fuel_tensor::Error>(())
    /// ```
    pub fn synchronize(&self) -> Result<()> {
        self.inner.synchronize_dyn()
    }
}