Skip to main content

tract_data/
tensor.rs

1//! `Tensor`, tract main data object of interest.
2use crate::TVec;
3use crate::blob::Blob;
4use crate::datum::{ClampCast, Datum, DatumType, QParams, round_ties_to_even, scale_by};
5use crate::dim::TDim;
6use crate::internal::*;
7use half::f16;
8use half::slice::HalfFloatSliceExt;
9use itertools::{Itertools, izip};
10use ndarray::prelude::*;
11#[cfg(feature = "complex")]
12use num_complex::Complex;
13use num_traits::Float;
14use std::borrow::Cow;
15use std::fmt;
16use std::hash::Hash;
17use std::ops::Range;
18use std::sync::Arc;
19
20pub mod litteral;
21pub mod named;
22pub mod plain_view;
23pub mod storage;
24pub mod view;
25
26pub use plain_view::{PlainView, PlainViewMut};
27use storage::{PlainStorage, StorageKind, TensorStorage};
28
29#[derive(Copy, Clone, Default, Debug)]
30pub enum Approximation {
31    Exact,
32    #[default]
33    Close,
34    Approximate,
35    VeryApproximate,
36    SuperApproximate,
37    UltraApproximate,
38    Custom(f32, f32, f32),
39    /// Compare by integer ULP distance in the reference tensor's own float type,
40    /// accepting a distance up to the given bound.
41    ///
42    /// Unlike the tolerance-based variants this does not go through an f32 cast,
43    /// so an f16 comparison stays an f16 comparison. Use it to assert that two
44    /// implementations of a kernel agree to within a known number of rounding
45    /// steps.
46    Ulp(u64),
47}
48
49impl PartialEq for Approximation {
50    fn eq(&self, other: &Self) -> bool {
51        use Approximation::*;
52        match (self, other) {
53            (Custom(aa, ar, ao), Custom(ba, br, bo)) => aa == ba && ar == br && bo == ao,
54            (Ulp(a), Ulp(b)) => a == b,
55            _ => std::mem::discriminant(self) == std::mem::discriminant(other),
56        }
57    }
58}
59
60impl Eq for Approximation {}
61
62impl From<bool> for Approximation {
63    fn from(b: bool) -> Self {
64        if b { Self::Approximate } else { Self::Exact }
65    }
66}
67
68impl Approximation {
69    fn atol_rtol_outliers(&self, dt: &DatumType) -> (f64, f64, f64) {
70        use Approximation::*;
71        match (self, dt) {
72            (Exact, _) => (0.0, 0.0, 0.0),
73            (Close, DatumType::F16) => (1e-3, 1e-3, 0.0),
74            (Approximate, DatumType::F16) => (1e-3, 5e-3, 0.0),
75            (Approximate, qp) if qp.is_quantized() => (qp.zp_scale().1 as f64, 0., 0.0),
76            (Close, _) => (1e-7, 1e-7, 0.0),
77            (Approximate, _) => (1e-4, 5e-4, 0.0),
78            (VeryApproximate, _) => (5e-2, 1e-2, 0.0),
79            (SuperApproximate, _) => (0.1, 0.05, 0.0001),
80            (UltraApproximate, _) => (0.2, 0.1, 0.0005),
81            (Custom(atol, rtol, out), _) => (*atol as _, *rtol as _, *out as _),
82            // Handled by a dedicated path in `Tensor::close_enough`; these values
83            // are never consulted.
84            (Ulp(_), _) => (0.0, 0.0, 0.0),
85        }
86    }
87}
88
89/// Tensor is a concrete tensor in tract.
90pub struct Tensor {
91    dt: DatumType,
92    shape: TVec<usize>,
93    strides: TVec<isize>,
94    len: usize,
95    storage: StorageKind,
96}
97
98impl Hash for Tensor {
99    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
100        self.dt.hash(state);
101        self.shape.hash(state);
102        if let Some(plain) = self.as_plain_ram() {
103            plain.layout().align().hash(state);
104            match self.dt {
105                DatumType::TDim => plain.as_slice::<TDim>().unwrap().hash(state),
106                DatumType::String => plain.as_slice::<String>().unwrap().hash(state),
107                DatumType::Blob => plain.as_slice::<Blob>().unwrap().hash(state),
108                _ => plain.as_bytes().hash(state),
109            }
110        } else {
111            self.storage.dyn_hash(state);
112        }
113    }
114}
115
116impl Clone for Tensor {
117    fn clone(&self) -> Tensor {
118        self.deep_clone()
119    }
120}
121
122impl Default for Tensor {
123    fn default() -> Tensor {
124        litteral::tensor0(0f32)
125    }
126}
127
128impl Drop for Tensor {
129    fn drop(&mut self) {
130        if self.as_plain_ram_storage().is_some() {
131            macro_rules! drop_in_place {
132                ($t: ty) => {
133                    if self.dt == <$t>::datum_type() {
134                        unsafe {
135                            let slice = self.as_slice_mut_unchecked::<$t>();
136                            std::ptr::drop_in_place(slice as *mut [$t]);
137                        }
138                    }
139                };
140            }
141            drop_in_place!(Blob);
142            drop_in_place!(String);
143            drop_in_place!(TDim);
144        }
145        // StorageKind::Exotic drops via Box<dyn TensorStorage> automatically
146    }
147}
148
149#[allow(unreachable_code)]
150pub fn vector_size() -> usize {
151    #[cfg(target_arch = "x86_64")]
152    {
153        return if is_x86_feature_detected!("avx512f") { 512 / 8 } else { 256 / 8 };
154    }
155    128 / 8
156}
157
158/// Copy `outer` blocks of `block` bytes from a contiguous source into a destination
159/// strided by `out_stride`, as `T`-sized items. Used for blocks too small for a
160/// `copy_nonoverlapping` call per block to pay for itself.
161///
162/// # Safety
163/// `block` and `out_stride` must be multiples of `size_of::<T>()`, both pointers must
164/// be `T`-aligned, and the two ranges must not overlap.
165#[inline]
166unsafe fn copy_blocks<T: Copy>(
167    src: *const u8,
168    dst: *mut u8,
169    outer: usize,
170    block: usize,
171    out_stride: usize,
172) {
173    unsafe {
174        let n = block / std::mem::size_of::<T>();
175        for o in 0..outer {
176            let s = src.add(o * block) as *const T;
177            let d = dst.add(o * out_stride) as *mut T;
178            for i in 0..n {
179                *d.add(i) = *s.add(i);
180            }
181        }
182    }
183}
184
185/// Transpose the `[i0, i1) × [m0, m1)` window of a `[a, mid]` matrix of N-byte
186/// cells into a `[mid, a]` matrix. `src` holds `a * mid` cells and `dst` `mid * a`
187/// cells, both densely packed.
188#[allow(clippy::too_many_arguments)]
189fn transpose_tile_cells<const N: usize>(
190    src: &[u8],
191    dst: &mut [u8],
192    i0: usize,
193    i1: usize,
194    m0: usize,
195    m1: usize,
196    a: usize,
197    mid: usize,
198) {
199    let (src, _) = src.as_chunks::<N>();
200    let (dst, _) = dst.as_chunks_mut::<N>();
201    if (a * N).is_multiple_of(4096) {
202        for (m, row) in dst.chunks_exact_mut(a).enumerate().take(m1).skip(m0) {
203            for (cell, i) in row[i0..i1].iter_mut().zip(i0..i1) {
204                *cell = src[i * mid + m];
205            }
206        }
207    } else {
208        let mut i = i0;
209        while i + 4 <= i1 {
210            let mut m = m0;
211            while m + 4 <= m1 {
212                let r0: &[[u8; N]; 4] = src[i * mid + m..i * mid + m + 4].try_into().unwrap();
213                let r1: &[[u8; N]; 4] =
214                    src[(i + 1) * mid + m..(i + 1) * mid + m + 4].try_into().unwrap();
215                let r2: &[[u8; N]; 4] =
216                    src[(i + 2) * mid + m..(i + 2) * mid + m + 4].try_into().unwrap();
217                let r3: &[[u8; N]; 4] =
218                    src[(i + 3) * mid + m..(i + 3) * mid + m + 4].try_into().unwrap();
219                for k in 0..4 {
220                    dst[(m + k) * a + i..(m + k) * a + i + 4]
221                        .copy_from_slice(&[r0[k], r1[k], r2[k], r3[k]]);
222                }
223                m += 4;
224            }
225            while m < m1 {
226                for ii in i..i + 4 {
227                    dst[m * a + ii] = src[ii * mid + m];
228                }
229                m += 1;
230            }
231            i += 4;
232        }
233        for i in i..i1 {
234            for (cell, m) in src[i * mid + m0..i * mid + m1].iter().zip(m0..m1) {
235                dst[m * a + i] = *cell;
236            }
237        }
238    }
239}
240
241/// Transpose the `[i0, i1) × [m0, m1)` window of a `[a, mid]` matrix of `item`-byte
242/// cells into a `[mid, a]` matrix. `src` holds `a * mid` cells and `dst` `mid * a`
243/// cells, both densely packed.
244#[allow(clippy::too_many_arguments)]
245fn transpose_tile(
246    src: &[u8],
247    dst: &mut [u8],
248    i0: usize,
249    i1: usize,
250    m0: usize,
251    m1: usize,
252    a: usize,
253    mid: usize,
254    item: usize,
255) {
256    match item {
257        1 => transpose_tile_cells::<1>(src, dst, i0, i1, m0, m1, a, mid),
258        2 => transpose_tile_cells::<2>(src, dst, i0, i1, m0, m1, a, mid),
259        4 => transpose_tile_cells::<4>(src, dst, i0, i1, m0, m1, a, mid),
260        8 => transpose_tile_cells::<8>(src, dst, i0, i1, m0, m1, a, mid),
261        16 => transpose_tile_cells::<16>(src, dst, i0, i1, m0, m1, a, mid),
262        _ => {
263            for i in i0..i1 {
264                for m in m0..m1 {
265                    let s = (i * mid + m) * item;
266                    let d = (m * a + i) * item;
267                    dst[d..d + item].copy_from_slice(&src[s..s + item]);
268                }
269            }
270        }
271    }
272}
273
274/// Transpose a `[a, mid]` matrix of `item`-byte cells into a `[mid, a]` matrix,
275/// visiting both in cache-sized tiles. `src` holds `a * mid` cells and `dst`
276/// `mid * a` cells, both densely packed.
277fn transpose_cells(src: &[u8], dst: &mut [u8], a: usize, mid: usize, item: usize) {
278    let tile = (64 / item).max(16);
279    let mut i0 = 0;
280    while i0 < a {
281        let i1 = (i0 + tile).min(a);
282        let mut m0 = 0;
283        while m0 < mid {
284            let m1 = (m0 + tile).min(mid);
285            transpose_tile(src, dst, i0, i1, m0, m1, a, mid, item);
286            m0 += tile;
287        }
288        i0 += tile;
289    }
290}
291
292/// Copy `src`, a `[outer, p, q, inner]` contiguous tensor of `elem_size`-byte
293/// elements, into `dst` laid out as `[outer, q, p, inner]` — the data movement
294/// performed by a single `move_axis` where `p` and `q` are the two extents the
295/// moved axis travels across. Both slices must cover `outer * p * q * inner *
296/// elem_size` bytes.
297fn move_axis_blocks(
298    src: &[u8],
299    dst: &mut [u8],
300    outer: usize,
301    p: usize,
302    q: usize,
303    inner: usize,
304    elem_size: usize,
305) {
306    let item = inner * elem_size;
307    let block = outer * p * q * item;
308    if p == 1 || q == 1 || inner == 0 {
309        dst[..block].copy_from_slice(&src[..block]);
310        return;
311    }
312    if item >= 64 {
313        for o in 0..outer {
314            for i in 0..p {
315                for m in 0..q {
316                    let s = ((o * p + i) * q + m) * item;
317                    let d = ((o * q + m) * p + i) * item;
318                    dst[d..d + item].copy_from_slice(&src[s..s + item]);
319                }
320            }
321        }
322    } else {
323        for o in 0..outer {
324            transpose_cells(
325                &src[o * p * q * item..(o + 1) * p * q * item],
326                &mut dst[o * p * q * item..(o + 1) * p * q * item],
327                p,
328                q,
329                item,
330            );
331        }
332    }
333}
334
335/// If `axes` is the identity permutation with one element moved — the shape of
336/// permutation `move_axis` produces — return the `(from, to)` of that move.
337fn move_axis_pair(axes: &[usize]) -> Option<(usize, usize)> {
338    let lo = (0..axes.len()).find(|&i| axes[i] != i)?;
339    let hi = (0..axes.len()).rev().find(|&i| axes[i] != i).unwrap();
340    if axes[hi] == lo && (lo..hi).all(|i| axes[i] == i + 1) {
341        return Some((lo, hi));
342    }
343    if axes[lo] == hi && (lo + 1..=hi).all(|i| axes[i] == i - 1) {
344        return Some((hi, lo));
345    }
346    None
347}
348
349impl Tensor {
350    /// Plain storage for this tensor's bytes, materializing it if the storage
351    /// keeps them elsewhere.
352    ///
353    /// Panics if the bytes cannot be produced, which is what the accessors
354    /// built on it (`as_bytes`, `as_ptr`, `as_slice_unchecked`) have always
355    /// done on non-plain storage. `try_as_plain_ram` is the fallible way in.
356    #[inline]
357    fn plain_ram_storage(&self) -> &PlainStorage {
358        self.storage.materialize_plain_ram().expect("Non-plain storage")
359    }
360
361    #[inline]
362    fn plain_ram_storage_mut(&mut self) -> &mut PlainStorage {
363        self.storage.as_plain_ram_mut().expect("Non-plain storage")
364    }
365
366    pub fn storage_as<T: TensorStorage>(&self) -> Option<&T> {
367        self.storage.as_storage().downcast_ref::<T>()
368    }
369
370    pub fn try_storage_as<T: TensorStorage>(&self) -> TractResult<&T> {
371        self.storage_as::<T>().context("Unexpected tensor storage type")
372    }
373
374    pub fn storage_as_mut<T: TensorStorage>(&mut self) -> Option<&mut T> {
375        self.storage.as_storage_mut().downcast_mut::<T>()
376    }
377
378    pub fn from_storage(
379        dt: DatumType,
380        shape: &[usize],
381        storage: impl TensorStorage + 'static,
382    ) -> Tensor {
383        let len = shape.iter().product::<usize>();
384        let strides = Self::natural_strides(shape);
385        Tensor {
386            dt,
387            shape: shape.into(),
388            strides,
389            len,
390            storage: StorageKind::Exotic(Box::new(storage)),
391        }
392    }
393
394    /// Returns an immutable [`PlainView`] if this tensor has plain storage.
395    #[inline]
396    pub fn as_plain_ram(&self) -> Option<PlainView<'_>> {
397        let storage = self.storage.as_plain_ram()?;
398        Some(PlainView::new(self, storage))
399    }
400
401    /// Returns an immutable [`PlainView`], or an error if storage is not plain.
402    ///
403    /// Unlike `as_plain_ram`, this materializes storage that holds its bytes
404    /// elsewhere, so it is the way to read a tensor whose storage may be
405    /// lazily host-backed.
406    #[inline]
407    pub fn try_as_plain_ram(&self) -> TractResult<PlainView<'_>> {
408        let storage = self.storage.materialize_plain_ram()?;
409        Ok(PlainView::new(self, storage))
410    }
411
412    /// Plain storage this tensor already holds in ram, if any. Never
413    /// materializes: the two axes at once, and the accessor to reach for
414    /// before a plain read.
415    #[inline]
416    pub fn as_plain_ram_storage(&self) -> Option<&PlainStorage> {
417        self.storage.as_plain_ram()
418    }
419
420    /// Mutable plain storage this tensor already holds in ram, if any. Never
421    /// materializes.
422    #[inline]
423    pub fn as_plain_ram_storage_mut(&mut self) -> Option<&mut PlainStorage> {
424        self.storage.as_plain_ram_mut()
425    }
426
427    /// Returns `true` if datum type and shape describe this tensor's layout on
428    /// their own.
429    ///
430    /// The layout axis, orthogonal to placement: a dense tensor is plain
431    /// wherever its bytes sit, block-quant weights are exotic wherever theirs
432    /// sit. Matches `TypedFact::is_plain`.
433    #[inline]
434    pub fn is_plain(&self) -> bool {
435        !self.storage.is_exotic()
436    }
437
438    /// Returns `true` if datum type and shape do not describe this tensor's
439    /// layout on their own, so a fact over it carries an `ExoticFact`.
440    #[inline]
441    pub fn is_exotic(&self) -> bool {
442        self.storage.is_exotic()
443    }
444
445    /// Returns `true` if this tensor's bytes can be read as plain host memory
446    /// right now: both axes at once, and what a caller gating an eager read or
447    /// an evaluation on cost is really asking.
448    #[inline]
449    pub fn is_plain_ram(&self) -> bool {
450        self.as_plain_ram_storage().is_some()
451    }
452
453    /// Returns `true` if this tensor's bytes are in host memory, readable
454    /// without a transfer.
455    ///
456    /// The placement axis, and a transient one: storage that leaves its bytes
457    /// on a device answers false until something materializes them, true
458    /// afterwards. It answers for the bytes in whatever layout the storage
459    /// keeps them, so it takes both axes -- `as_plain_ram_storage` -- for a
460    /// plain read to be sure to work.
461    #[inline]
462    pub fn in_ram(&self) -> bool {
463        self.storage.in_ram()
464    }
465
466    /// Build the `ExoticFact` matching this tensor's storage, or `None` for plain tensors.
467    pub fn exotic_fact(&self) -> TractResult<Option<Box<dyn crate::exotic::ExoticFact>>> {
468        self.storage.as_storage().exotic_fact(&self.shape)
469    }
470
471    /// Returns a mutable [`PlainViewMut`] if this tensor has plain storage.
472    #[inline]
473    pub fn as_plain_ram_mut(&mut self) -> Option<PlainViewMut<'_>> {
474        let storage = self.storage.as_plain_ram_mut()?;
475        Some(PlainViewMut::new(self.dt, &self.shape, &self.strides, self.len, storage))
476    }
477
478    /// Returns a mutable [`PlainViewMut`], or an error if storage is not plain.
479    #[inline]
480    pub fn try_as_plain_ram_mut(&mut self) -> TractResult<PlainViewMut<'_>> {
481        self.as_plain_ram_mut().context("Tensor storage is not plain")
482    }
483
484    /// Create an uninitialized tensor (dt as type paramater).
485    #[inline]
486    pub unsafe fn uninitialized<T: Datum>(shape: &[usize]) -> TractResult<Tensor> {
487        unsafe { Self::uninitialized_dt(T::datum_type(), shape) }
488    }
489
490    /// Create an uninitialized tensor (dt as regular parameter).
491    #[inline]
492    pub unsafe fn uninitialized_dt(dt: DatumType, shape: &[usize]) -> TractResult<Tensor> {
493        unsafe { Self::uninitialized_aligned_dt(dt, shape, vector_size()) }
494    }
495
496    /// Create an uninitialized tensor with a given alignment (in bytes).
497    #[inline]
498    pub unsafe fn uninitialized_aligned<T: Datum>(
499        shape: &[usize],
500        alignment: usize,
501    ) -> TractResult<Tensor> {
502        unsafe { Self::uninitialized_aligned_dt(T::datum_type(), shape, alignment) }
503    }
504
505    /// Create an uninitialized tensor with a given alignment (in bytes).
506    pub unsafe fn uninitialized_aligned_dt(
507        dt: DatumType,
508        shape: &[usize],
509        alignment: usize,
510    ) -> TractResult<Tensor> {
511        // `shape` and `dt` come from the model file. Computing the byte count
512        // with a plain product used to wrap around on overflow, silently
513        // allocating a buffer much smaller than the tensor claims (or asking
514        // the allocator for an absurd one). Check instead.
515        let bytes = shape
516            .iter()
517            .try_fold(dt.size_of(), |acc, &d| acc.checked_mul(d))
518            .filter(|&b| b <= isize::MAX as usize)
519            .ok_or_else(|| format_err!("tensor shape {shape:?} of {dt:?} is too large"))?;
520        let storage = StorageKind::Plain(PlainStorage::from(unsafe {
521            Blob::new_for_size_and_align(bytes, alignment)
522        }));
523        let mut tensor = Tensor { strides: tvec!(), dt, shape: shape.into(), storage, len: 0 };
524        if tensor.shape.len() == 0 {
525            tensor.len = 1;
526        } else {
527            tensor.update_strides_and_len();
528        }
529        if !tensor.storage.is_empty() {
530            unsafe fn write_defaults<T: Datum + Default>(tensor: &mut Tensor) {
531                unsafe {
532                    let len = tensor.len;
533                    let dst = tensor.as_slice_mut_unchecked::<T>().as_mut_ptr();
534                    for i in 0..len {
535                        std::ptr::write(dst.add(i), T::default());
536                    }
537                }
538            }
539            if dt == String::datum_type() {
540                unsafe { write_defaults::<String>(&mut tensor) }
541            } else if dt == Blob::datum_type() {
542                unsafe { write_defaults::<Blob>(&mut tensor) }
543            } else if dt == TDim::datum_type() {
544                unsafe { write_defaults::<TDim>(&mut tensor) }
545            } else if cfg!(debug_assertions) {
546                assert!(dt.is_copy());
547                if dt == DatumType::F32 {
548                    tensor.fill_t(f32::NAN).unwrap();
549                } else {
550                    // safe, non copy types have been dealt with
551                    tensor.as_bytes_mut().iter_mut().for_each(|x| *x = (-1i8) as u8);
552                }
553            }
554        }
555        Ok(tensor)
556    }
557
558    pub fn stack_tensors(
559        axis: usize,
560        tensors: &[impl std::borrow::Borrow<Tensor>],
561    ) -> TractResult<Tensor> {
562        ensure!(tensors.len() > 0);
563        let rank = tensors[0].borrow().rank();
564        ensure!(axis < rank);
565        ensure!(tensors.iter().all(|t| t.borrow().rank() == rank));
566        let dt = tensors[0].borrow().datum_type();
567        ensure!(tensors.iter().all(|t| t.borrow().datum_type() == dt));
568        let mut shape: TVec<usize> = tensors[0].borrow().shape().into();
569        for ax in 0..rank {
570            if ax != axis {
571                ensure!(tensors.iter().all(|t| t.borrow().shape()[ax] == shape[ax]));
572            }
573        }
574        shape[axis] = tensors.iter().map(|v| v.borrow().shape()[axis]).sum();
575        unsafe {
576            let mut result = Tensor::uninitialized_dt(dt, &shape)?;
577            // Every input keeps the same trailing block, so one outer stride walks
578            // them alongside the result and each contribution stays contiguous.
579            let outer: usize = shape[..axis].iter().product();
580            let out_stride = shape[axis..].iter().product::<usize>() * dt.size_of();
581            // Each contribution is `outer` blocks of `block` bytes, strided by
582            // `out_stride` in the result. At one f32 per block -- DTLN's
583            // [1, 2, 128, 2] axis-3 concat, FastEnhancer's [1, 256, 1, 2] -- a
584            // copy_nonoverlapping per block is `outer` calls to move four bytes
585            // each, and the generic strided assign below is no better. Copy those
586            // inline, typed, instead: no call, and the loop is a plain strided
587            // store LLVM can widen.
588            const SMALL_BLOCK_BYTES: usize = 64;
589            if dt.is_copy()
590                && outer > 0
591                && tensors.iter().all(|t| t.borrow().storage.as_plain_ram().is_some())
592            {
593                let out = result.plain_ram_storage_mut().as_mut_ptr();
594                let mut offset = 0isize;
595                for v in tensors {
596                    let v = v.borrow();
597                    let block = v.storage.byte_len() / outer;
598                    let src = v.plain_ram_storage().as_ptr();
599                    let dst = out.offset(offset);
600                    if outer == 1 {
601                        std::ptr::copy_nonoverlapping(src, dst, block);
602                    } else if block >= SMALL_BLOCK_BYTES {
603                        for o in 0..outer {
604                            std::ptr::copy_nonoverlapping(
605                                src.add(o * block),
606                                dst.add(o * out_stride),
607                                block,
608                            );
609                        }
610                    } else {
611                        // `block` and both pointers are multiples of the datum size,
612                        // so the typed copy stays aligned.
613                        match dt.size_of() {
614                            1 => copy_blocks::<u8>(src, dst, outer, block, out_stride),
615                            2 => copy_blocks::<u16>(src, dst, outer, block, out_stride),
616                            4 => copy_blocks::<u32>(src, dst, outer, block, out_stride),
617                            8 => copy_blocks::<u64>(src, dst, outer, block, out_stride),
618                            16 => copy_blocks::<u128>(src, dst, outer, block, out_stride),
619                            _ => {
620                                for o in 0..outer {
621                                    std::ptr::copy_nonoverlapping(
622                                        src.add(o * block),
623                                        dst.add(o * out_stride),
624                                        block,
625                                    );
626                                }
627                            }
628                        }
629                    }
630                    offset += block as isize;
631                }
632            } else {
633                let mut offset = 0;
634                for t in tensors {
635                    let t = t.borrow();
636                    let len = t.shape()[axis];
637                    result.assign_slice_from_resolved(
638                        &[],
639                        offset..offset + len,
640                        t,
641                        &[],
642                        0..len,
643                        axis,
644                    );
645                    offset += len;
646                }
647            }
648
649            Ok(result)
650        }
651    }
652
653    pub fn clear<T: Datum + num_traits::Zero + Clone>(&mut self) -> TractResult<()> {
654        self.fill_t(T::zero())
655    }
656
657    pub fn zero<T: Datum + num_traits::Zero>(shape: &[usize]) -> TractResult<Tensor> {
658        unsafe {
659            let mut t = Tensor::uninitialized::<T>(shape)?;
660            t.clear::<T>()?;
661            Ok(t)
662        }
663    }
664
665    pub fn zero_scalar<T: Datum + num_traits::Zero>() -> TractResult<Tensor> {
666        Tensor::zero::<T>(&[])
667    }
668
669    pub fn zero_scalar_dt(dt: DatumType) -> TractResult<Tensor> {
670        Tensor::zero_dt(dt, &[])
671    }
672
673    pub fn zero_dt(dt: DatumType, shape: &[usize]) -> TractResult<Tensor> {
674        Tensor::zero_aligned_dt(dt, shape, vector_size())
675    }
676
677    pub fn fill_t<T: Datum + Clone>(&mut self, value: T) -> TractResult<()> {
678        self.try_as_plain_ram_mut()?
679            .as_slice_mut::<T>()?
680            .iter_mut()
681            .for_each(|item| *item = value.clone());
682        Ok(())
683    }
684
685    pub fn zero_aligned_dt(
686        dt: DatumType,
687        shape: &[usize],
688        alignment: usize,
689    ) -> TractResult<Tensor> {
690        if shape.iter().product::<usize>() == 0 {
691            unsafe { return Tensor::uninitialized_dt(dt, shape) };
692        }
693        if dt.is_quantized() {
694            unsafe {
695                let mut t = Tensor::uninitialized_dt(dt, shape)?;
696                let zp = dt.zp_scale().0;
697                match dt.unquantized() {
698                    DatumType::I8 => t
699                        .try_as_plain_ram_mut()?
700                        .as_slice_mut::<i8>()?
701                        .iter_mut()
702                        .for_each(|item| *item = zp as _),
703                    DatumType::U8 => t
704                        .try_as_plain_ram_mut()?
705                        .as_slice_mut::<u8>()?
706                        .iter_mut()
707                        .for_each(|item| *item = zp as _),
708                    DatumType::I32 => t
709                        .try_as_plain_ram_mut()?
710                        .as_slice_mut::<i32>()?
711                        .iter_mut()
712                        .for_each(|item| *item = zp as _),
713                    _ => unreachable!(),
714                }
715                Ok(t)
716            }
717        } else if dt == DatumType::Bool {
718            let mut t = unsafe { Tensor::uninitialized_dt(dt, shape)? };
719            t.fill_t::<bool>(false)?;
720            Ok(t)
721        } else {
722            dispatch_zerolike!(Self::zero_aligned(dt)(shape, alignment))
723        }
724    }
725
726    pub fn zero_aligned<T: Datum + num_traits::Zero>(
727        shape: &[usize],
728        alignment: usize,
729    ) -> TractResult<Tensor> {
730        unsafe {
731            let mut tensor = Self::uninitialized_aligned::<T>(shape, alignment)?;
732            tensor.clear::<T>()?;
733            Ok(tensor)
734        }
735    }
736
737    /// Create a tensor with a given shape and a slice of elements.
738    /// The data is copied and aligned to size of T.
739    pub fn from_shape<T: Datum + Copy>(shape: &[usize], data: &[T]) -> TractResult<Tensor> {
740        Self::from_shape_align(shape, data, vector_size())
741    }
742
743    /// Create a tensor with a given shape and a slice of elements.
744    /// The data is copied and aligned to given alignment.
745    pub fn from_shape_align<T: Datum + Copy>(
746        shape: &[usize],
747        data: &[T],
748        align: usize,
749    ) -> TractResult<Tensor> {
750        ensure!(
751            data.len() == shape.iter().product::<usize>(),
752            "Shape product must be equal to data length"
753        );
754        unsafe {
755            let bytes = std::slice::from_raw_parts(
756                data.as_ptr() as *const u8,
757                data.len() * T::datum_type().size_of(),
758            );
759            let dt = T::datum_type();
760            Self::from_raw_dt_align(dt, shape, bytes, align)
761        }
762    }
763
764    /// Create a tensor from raw data.
765    ///
766    /// It copies the data, aligning it to the size of T.
767    pub unsafe fn from_raw<T: Datum>(shape: &[usize], content: &[u8]) -> TractResult<Tensor> {
768        unsafe { Tensor::from_raw_dt(T::datum_type(), shape, content) }
769    }
770
771    pub unsafe fn from_raw_aligned<T: Datum>(
772        shape: &[usize],
773        content: &[u8],
774        align: usize,
775    ) -> TractResult<Tensor> {
776        unsafe { Tensor::from_raw_dt_align(T::datum_type(), shape, content, align) }
777    }
778
779    pub unsafe fn from_raw_dt(
780        dt: DatumType,
781        shape: &[usize],
782        content: &[u8],
783    ) -> TractResult<Tensor> {
784        unsafe { Self::from_raw_dt_align(dt, shape, content, vector_size()) }
785    }
786
787    pub unsafe fn from_raw_dt_align(
788        dt: DatumType,
789        shape: &[usize],
790        content: &[u8],
791        align: usize,
792    ) -> TractResult<Tensor> {
793        // Check the declared shape against the payload *before* allocating.
794        // The shape is attacker-controlled, so allocating first lets a
795        // malformed model request an allocation of any size it likes, even
796        // when the payload that follows is a few bytes long.
797        let len = shape
798            .iter()
799            .try_fold(1usize, |acc, &d| acc.checked_mul(d))
800            .ok_or_else(|| format_err!("tensor shape {shape:?} overflows"))?;
801        let expected = len
802            .checked_mul(dt.size_of())
803            .ok_or_else(|| format_err!("tensor shape {shape:?} of {dt:?} is too large"))?;
804        ensure!(
805            content.len() == expected,
806            "Raw tensor data length ({}) does not match shape {:?} of {:?} ({} bytes)",
807            content.len(),
808            shape,
809            dt,
810            expected
811        );
812        let mut tensor = unsafe { Tensor::uninitialized_aligned_dt(dt, shape, align) }?;
813        tensor.as_bytes_mut().copy_from_slice(content);
814        Ok(tensor)
815    }
816
817    pub fn from_slice_align<T: Datum + Copy>(content: &[T], align: usize) -> TractResult<Tensor> {
818        Self::from_shape_align(&[content.len()], content, align)
819    }
820
821    /// Get the number of dimensions (or axes) of the tensor.
822    #[inline]
823    pub fn rank(&self) -> usize {
824        self.shape.len()
825    }
826
827    /// Get the shape of the tensor.
828    #[inline]
829    pub fn shape(&self) -> &[usize] {
830        &self.shape
831    }
832
833    /// Get the number of values in the tensor.
834    #[inline]
835    #[allow(clippy::len_without_is_empty)]
836    pub fn len(&self) -> usize {
837        self.len
838    }
839
840    /// Get the number of valeus in the tensor.
841    #[inline]
842    #[allow(clippy::len_without_is_empty)]
843    pub fn volume(&self) -> usize {
844        self.len
845    }
846
847    /// Get the shape of the tensor.
848    #[inline]
849    pub fn strides(&self) -> &[isize] {
850        &self.strides
851    }
852
853    fn update_strides_and_len(&mut self) {
854        self.strides.clear();
855        if self.shape.len() == 0 {
856            self.len = 1;
857            return;
858        }
859        compute_natural_stride_to(&mut self.strides, &self.shape);
860        self.len = self.strides[0] as usize * self.shape[0];
861    }
862
863    /// Force the tensor shape, no consistency check.
864    pub unsafe fn set_shape_unchecked(&mut self, shape: &[usize]) {
865        if shape != &*self.shape {
866            self.shape.clear();
867            self.shape.extend_from_slice(shape);
868            self.update_strides_and_len();
869        }
870    }
871
872    /// Force the tensor shape and strides, no consistency check.
873    pub unsafe fn set_geometry_unchecked(&mut self, shape: &[usize], strides: &[isize]) {
874        self.shape.clear();
875        self.shape.extend_from_slice(shape);
876        self.strides.clear();
877        self.strides.extend_from_slice(strides);
878    }
879
880    /// Force the tensor shape.
881    pub fn set_shape(&mut self, shape: &[usize]) -> TractResult<()> {
882        if self.len() != shape.iter().product::<usize>() {
883            bail!("Invalid reshape {:?} to {:?}", self.shape, shape);
884        }
885        unsafe { self.set_shape_unchecked(shape) }
886        Ok(())
887    }
888
889    /// `true` when the tensor is backed by plain contiguous storage laid out
890    /// with the natural strides of its shape, so the block move applies.
891    #[inline]
892    fn can_move_axis_blocks(&self) -> bool {
893        self.dt.is_copy()
894            && self.has_plain_ram_storage()
895            && self.strides[..] == natural_strides(&self.shape)[..]
896    }
897
898    /// Return a new tensor with the axis `from` moved to position `to`, in fresh
899    /// plain storage. Data is copied once. Falls back to a clone plus the
900    /// ndarray path when the tensor is not plainly and contiguously laid out.
901    pub fn moved_axis(&self, from: usize, to: usize) -> TractResult<Tensor> {
902        ensure!(from < self.rank());
903        ensure!(to < self.rank());
904        let mut new_shape: TVec<usize> = self.shape.clone();
905        let moved = new_shape.remove(from);
906        new_shape.insert(to, moved);
907        if !self.can_move_axis_blocks() {
908            let mut permutation: Vec<usize> = (0..self.rank()).collect();
909            permutation.remove(from);
910            permutation.insert(to, from);
911            return self.clone().permute_axes(&permutation);
912        }
913        let shape = &*self.shape;
914        let (outer, p, q, inner) = if from < to {
915            (
916                shape[..from].iter().product(),
917                shape[from],
918                shape[from + 1..=to].iter().product(),
919                shape[to + 1..].iter().product(),
920            )
921        } else {
922            (
923                shape[..to].iter().product(),
924                shape[to..from].iter().product(),
925                shape[from],
926                shape[from + 1..].iter().product(),
927            )
928        };
929        let mut output = Tensor::zero_dt(self.dt, &new_shape)?;
930        move_axis_blocks(
931            self.as_bytes(),
932            output.as_bytes_mut(),
933            outer,
934            p,
935            q,
936            inner,
937            self.dt.size_of(),
938        );
939        Ok(output)
940    }
941
942    pub fn permute_axes(self, axes: &[usize]) -> TractResult<Tensor> {
943        ensure!(axes.iter().duplicates().next().is_none());
944        ensure!(axes.iter().all(|a| *a < self.rank()));
945        if axes.iter().enumerate().all(|(i, a)| i == *a) {
946            return Ok(self);
947        }
948        if let Some((from, to)) = move_axis_pair(axes)
949            && self.can_move_axis_blocks()
950        {
951            return self.moved_axis(from, to);
952        }
953        unsafe {
954            #[inline]
955            unsafe fn permute<T: Datum>(axes: &[usize], input: Tensor) -> Tensor {
956                unsafe { input.into_array_unchecked::<T>().permuted_axes(axes).into_tensor() }
957            }
958            let dt = self.datum_type();
959            let mut t = dispatch_datum_by_size!(permute(self.datum_type())(axes, self));
960            t.set_datum_type(dt);
961            Ok(t)
962        }
963    }
964
965    pub fn move_axis(self, from: usize, to: usize) -> TractResult<Tensor> {
966        let mut permutation: Vec<usize> = (0..self.rank()).collect();
967        permutation.remove(from);
968        permutation.insert(to, from);
969        self.permute_axes(&permutation)
970    }
971
972    pub fn collapse_axis_with_next(mut self, axis: usize) -> Tensor {
973        let removed = self.shape.remove(axis + 1);
974        self.shape[axis] *= removed;
975        self.update_strides_and_len();
976        self
977    }
978
979    pub fn split_axis(mut self, axis: usize, outer_dim: usize) -> TractResult<Tensor> {
980        if !self.shape[axis].is_multiple_of(outer_dim) {
981            bail!(
982                "Invalid axis split, shape is {:?}, axis split at {}, outer {}",
983                self.shape,
984                axis,
985                outer_dim
986            );
987        }
988        self.shape.insert(axis + 1, self.shape[axis] / outer_dim);
989        self.shape[axis] = outer_dim;
990        self.update_strides_and_len();
991        Ok(self)
992    }
993
994    /// Reshape the tensor to `shape`.
995    pub fn into_shape(mut self, shape: &[usize]) -> TractResult<Tensor> {
996        self.set_shape(shape)?;
997        Ok(self)
998    }
999
1000    pub fn insert_axis(&mut self, axis: usize) -> TractResult<()> {
1001        self.shape.insert(axis, 1);
1002        self.strides.insert(axis, self.strides.get(axis).copied().unwrap_or(1));
1003        Ok(())
1004    }
1005
1006    pub fn remove_axis(&mut self, axis: usize) -> TractResult<()> {
1007        ensure!(self.shape[axis] == 1, "Remove a non-1 axis: axis {} in {:?}", axis, self);
1008        self.shape.remove(axis);
1009        self.strides.remove(axis);
1010        Ok(())
1011    }
1012
1013    pub fn broadcast_into_rank(mut self, rank: usize) -> TractResult<Tensor> {
1014        self.broadcast_to_rank(rank)?;
1015        self.update_strides_and_len();
1016        Ok(self)
1017    }
1018
1019    pub fn broadcast_to_rank(&mut self, rank: usize) -> TractResult<()> {
1020        if rank < self.rank() {
1021            bail!("Can only broadcast to higher rank")
1022        }
1023        while self.shape.len() < rank {
1024            self.shape.insert(0, 1)
1025        }
1026        self.update_strides_and_len();
1027        Ok(())
1028    }
1029
1030    pub fn broadcast_scalar_to_shape(&self, shape: &[usize]) -> TractResult<Tensor> {
1031        if self.rank() > 0 {
1032            bail!("broadcast_scalar_to_shape called on {:?}, which is not a salar", self);
1033        }
1034        unsafe fn make<T: Datum>(src: &Tensor, dst: &mut Tensor) {
1035            unsafe {
1036                let value: &T = src.to_scalar_unchecked::<T>();
1037                dst.as_slice_mut_unchecked::<T>().iter_mut().for_each(|item| *item = value.clone())
1038            };
1039        }
1040        unsafe {
1041            let mut t = Tensor::uninitialized_dt(self.datum_type(), shape)?;
1042            dispatch_datum_by_size!(make(self.datum_type())(self, &mut t));
1043            Ok(t)
1044        }
1045    }
1046
1047    fn broadcast_to_shape_t<T: Datum>(&self, shape: &[usize]) -> TractResult<Tensor> {
1048        unsafe {
1049            let view = self.to_array_view_unchecked::<T>();
1050            let mut output = view
1051                .broadcast(shape)
1052                .with_context(|| format!("Broadcasting {view:?} to {shape:?}"))?
1053                .into_owned()
1054                .into_tensor();
1055            output.set_datum_type(self.datum_type());
1056            Ok(output)
1057        }
1058    }
1059
1060    pub fn broadcast_to_shape(&self, shape: &[usize]) -> TractResult<Tensor> {
1061        if !self.dt.is_copy() {
1062            return dispatch_datum!(Self::broadcast_to_shape_t(self.dt)(self, shape));
1063        }
1064        ensure!(
1065            self.rank() <= shape.len(),
1066            "Broadcasting {self:?} to {shape:?} would lose {} axes",
1067            self.rank() - shape.len()
1068        );
1069        let offset = shape.len() - self.rank();
1070        let mut src: TVec<usize> = tvec!(1; shape.len());
1071        src[offset..].copy_from_slice(self.shape());
1072        ensure!(
1073            izip!(&src, shape).all(|(s, d)| *s == 1 || s == d),
1074            "Broadcasting {self:?} to {shape:?}"
1075        );
1076        // The axes from the innermost one down to the first broadcast axis are
1077        // one contiguous run of the source, so only the axes above it need a
1078        // coordinate walk, with a null source stride wherever they broadcast.
1079        let mut split = shape.len();
1080        while split > 0 && src[split - 1] == shape[split - 1] {
1081            split -= 1;
1082        }
1083        let dt_size = self.dt.size_of();
1084        let run = shape[split..].iter().product::<usize>() * dt_size;
1085        let outer: usize = shape[..split].iter().product();
1086        let mut src_strides: TVec<usize> = tvec!(0; split);
1087        let mut acc = run;
1088        for ax in (0..split).rev() {
1089            src_strides[ax] = if src[ax] == 1 { 0 } else { acc };
1090            acc *= src[ax];
1091        }
1092        let mut output = unsafe { Tensor::uninitialized_dt(self.dt, shape)? };
1093        if run == 0 || outer == 0 {
1094            return Ok(output);
1095        }
1096        let source = self.as_bytes();
1097        let dst = output.as_bytes_mut();
1098        // When the innermost source axes broadcast, `run` collapses to a single element and
1099        // the block walk below copies `dt_size` bytes per output element -- measured at ~15
1100        // cycles each, which is 6.2 ms for a 6.5 MB `1x16x1x1` -> `1x16x320x320` bias
1101        // broadcast. Every output cell is then one contiguous run of a single value, so lay
1102        // the cell down once and double it instead of walking it. `run == dt_size` holds
1103        // exactly when the innermost source axis is broadcast.
1104        if run == dt_size {
1105            let mut bs = shape.len();
1106            while bs > 0 && src[bs - 1] == 1 {
1107                bs -= 1;
1108            }
1109            let cell: usize = shape[bs..].iter().product();
1110            let cells: usize = shape[..bs].iter().product();
1111            if cell > 0 && cells > 0 {
1112                let mut src_strides: TVec<usize> = tvec!(0; bs);
1113                let mut acc = 1;
1114                for ax in (0..bs).rev() {
1115                    src_strides[ax] = if src[ax] == 1 { 0 } else { acc };
1116                    acc *= src[ax];
1117                }
1118                let cell_bytes = cell * dt_size;
1119                let mut coords: TVec<usize> = tvec!(0; bs);
1120                for cell_ix in 0..cells {
1121                    let from: usize =
1122                        izip!(&coords, &src_strides).map(|(c, s)| c * s).sum::<usize>() * dt_size;
1123                    let out = &mut dst[cell_ix * cell_bytes..][..cell_bytes];
1124                    out[..dt_size].copy_from_slice(&source[from..][..dt_size]);
1125                    let mut filled = dt_size;
1126                    while filled < cell_bytes {
1127                        let n = filled.min(cell_bytes - filled);
1128                        out.copy_within(..n, filled);
1129                        filled += n;
1130                    }
1131                    for ax in (0..bs).rev() {
1132                        coords[ax] += 1;
1133                        if coords[ax] < shape[ax] {
1134                            break;
1135                        }
1136                        coords[ax] = 0;
1137                    }
1138                }
1139                return Ok(output);
1140            }
1141        }
1142        let mut coords: TVec<usize> = tvec!(0; split);
1143        for block in 0..outer {
1144            let from: usize = izip!(&coords, &src_strides).map(|(c, s)| c * s).sum();
1145            dst[block * run..][..run].copy_from_slice(&source[from..][..run]);
1146            for ax in (0..split).rev() {
1147                coords[ax] += 1;
1148                if coords[ax] < shape[ax] {
1149                    break;
1150                }
1151                coords[ax] = 0;
1152            }
1153        }
1154        Ok(output)
1155    }
1156
1157    pub fn broadcast_vector_to_shape(&self, shape: &[usize], axis: usize) -> TractResult<Tensor> {
1158        ensure!(self.rank() == 1);
1159        ensure!(shape[axis] == self.len());
1160        if !self.datum_type().is_copy() {
1161            let mut vec_shape = vec![1; shape.len()];
1162            vec_shape[axis] = self.len();
1163            return self.clone().into_shape(&vec_shape)?.broadcast_to_shape(shape);
1164        }
1165        unsafe {
1166            let mut output = Tensor::uninitialized_dt(self.datum_type(), shape)?;
1167            if output.len() == 0 {
1168                return Ok(output);
1169            }
1170            let inner_len = shape[axis + 1..].iter().product::<usize>();
1171
1172            unsafe fn splat<T>(input: &Tensor, output: &mut Tensor, inner_len: usize)
1173            where
1174                T: Datum + Copy,
1175            {
1176                unsafe {
1177                    for ix in 0..input.len() {
1178                        let value: T = input.as_slice_unchecked()[ix];
1179                        output.as_slice_mut_unchecked::<T>()[ix * inner_len..(ix + 1) * inner_len]
1180                            .iter_mut()
1181                            .for_each(|item| *item = value);
1182                    }
1183                }
1184            }
1185            dispatch_copy_by_size!(splat(self.datum_type())(&self, &mut output, inner_len));
1186
1187            let outer_len = shape[0..axis].iter().product::<usize>();
1188            let repeat_bytes_len = inner_len * self.as_bytes().len();
1189            let bytes = output.as_bytes_mut();
1190            for ix in 1..outer_len {
1191                bytes.copy_within(0..repeat_bytes_len, ix * repeat_bytes_len);
1192            }
1193
1194            Ok(output)
1195        }
1196    }
1197    pub fn assign_slice(
1198        &mut self,
1199        range: impl std::ops::RangeBounds<usize>,
1200        src: &Tensor,
1201        src_range: impl std::ops::RangeBounds<usize>,
1202        axis: usize,
1203    ) -> TractResult<()> {
1204        self.assign_slice_at_prefix(&[], range, src, &[], src_range, axis)
1205    }
1206
1207    /// Assign `src`'s `src_range` along `axis` into `range` along `axis`, each
1208    /// taken in the sub-tensor at its prefix. A prefix indexes the leading axes
1209    /// as [`Tensor::view_at_prefix`] does, and both prefixes cover the same
1210    /// axes, whose extents may then differ. `axis` stays an axis of the whole
1211    /// tensors, so it has to sit past the prefixes.
1212    pub fn assign_slice_at_prefix(
1213        &mut self,
1214        prefix: &[usize],
1215        range: impl std::ops::RangeBounds<usize>,
1216        src: &Tensor,
1217        src_prefix: &[usize],
1218        src_range: impl std::ops::RangeBounds<usize>,
1219        axis: usize,
1220    ) -> TractResult<()> {
1221        ensure!(self.rank() == src.rank());
1222        ensure!(axis < self.rank());
1223        let range = clip_range_bounds(self.shape[axis], range);
1224        let src_range = clip_range_bounds(src.shape[axis], src_range);
1225        ensure!(
1226            src.datum_type() == self.datum_type(),
1227            "Attempt to assign into {:?} from {:?}, datum type mismatch",
1228            self.datum_type(),
1229            src.datum_type()
1230        );
1231        ensure!(
1232            src_range.len() == range.len(),
1233            "Attempt to assign a range of {:?} from a range of {:?}",
1234            range,
1235            src_range,
1236        );
1237        ensure!(
1238            prefix.len() == src_prefix.len() && prefix.len() <= axis,
1239            "Attempt to assign axis {axis} at prefixes {prefix:?} and {src_prefix:?}"
1240        );
1241        ensure!(
1242            izip!(prefix, self.shape()).all(|(ix, dim)| ix < dim)
1243                && izip!(src_prefix, src.shape()).all(|(ix, dim)| ix < dim),
1244            "Attempt to assign into {self:?} at {prefix:?} from {src:?} at {src_prefix:?}"
1245        );
1246        ensure!(
1247            izip!(prefix.len().., &self.shape[prefix.len()..], &src.shape[prefix.len()..])
1248                .all(|(ix, dst, src)| ix == axis || src == dst),
1249            "Attempt to assign a {}-axis range of {:?} from a range of {:?}",
1250            axis,
1251            self,
1252            src
1253        );
1254        ensure!(
1255            src_range.end <= src.shape()[axis],
1256            "Assigning from invalid slice (axis {}, {:?}) of {:?}",
1257            axis,
1258            src_range,
1259            src
1260        );
1261        ensure!(
1262            range.end <= self.shape()[axis],
1263            "Assigning to invalid slice (axis {}, {:?}) of {:?}",
1264            axis,
1265            range,
1266            self
1267        );
1268        unsafe { self.assign_slice_from_resolved(prefix, range, src, src_prefix, src_range, axis) };
1269        Ok(())
1270    }
1271
1272    pub unsafe fn assign_slice_unchecked(
1273        &mut self,
1274        range: impl std::ops::RangeBounds<usize>,
1275        src: &Tensor,
1276        src_range: impl std::ops::RangeBounds<usize>,
1277        axis: usize,
1278    ) {
1279        let range = clip_range_bounds(self.shape[axis], range);
1280        let src_range = clip_range_bounds(src.shape[axis], src_range);
1281        unsafe { self.assign_slice_from_resolved(&[], range, src, &[], src_range, axis) };
1282    }
1283
1284    /// The byte offset of the sub-tensor at `prefix`, which indexes the leading
1285    /// axes as [`Tensor::view_at_prefix`] does.
1286    fn prefix_offset(&self, prefix: &[usize]) -> usize {
1287        izip!(prefix, &self.strides).map(|(ix, stride)| ix * *stride as usize).sum::<usize>()
1288            * self.datum_type().size_of()
1289    }
1290
1291    #[allow(clippy::ptr_eq)]
1292    unsafe fn assign_slice_from_resolved(
1293        &mut self,
1294        prefix: &[usize],
1295        range: std::ops::Range<usize>,
1296        src: &Tensor,
1297        src_prefix: &[usize],
1298        src_range: std::ops::Range<usize>,
1299        axis: usize,
1300    ) {
1301        unsafe {
1302            use ndarray::Slice;
1303            unsafe fn assign_slice_t<T: Datum>(
1304                to: &mut Tensor,
1305                to_prefix: &[usize],
1306                to_range: Range<usize>,
1307                from: &Tensor,
1308                from_prefix: &[usize],
1309                from_range: Range<usize>,
1310                axis: usize,
1311            ) {
1312                unsafe {
1313                    let mut to_view = to.to_array_view_mut_unchecked::<T>();
1314                    let mut from_view = from.to_array_view_unchecked::<T>();
1315                    for (ax, (to, from)) in izip!(to_prefix, from_prefix).enumerate() {
1316                        to_view.slice_axis_inplace(Axis(ax), Slice::from(*to..*to + 1));
1317                        from_view.slice_axis_inplace(Axis(ax), Slice::from(*from..*from + 1));
1318                    }
1319                    to_view
1320                        .slice_axis_mut(Axis(axis), Slice::from(to_range))
1321                        .assign(&from_view.slice_axis(Axis(axis), Slice::from(from_range)))
1322                }
1323            }
1324            if self.datum_type().is_copy() {
1325                // Tensors carry natural strides, so a range along `axis` is one
1326                // contiguous run per coordinate of the axes between the prefix
1327                // and it, and both sides share the run length and the trailing
1328                // block.
1329                let post = self.strides[axis] as usize * self.datum_type().size_of();
1330                let len = post * range.len();
1331                if len > 0 {
1332                    let outer: usize = self.shape[prefix.len()..axis].iter().product();
1333                    let dst_block = post * self.shape[axis];
1334                    let src_block = post * src.shape[axis];
1335                    let src_ptr = src
1336                        .plain_ram_storage()
1337                        .as_ptr()
1338                        .add(src.prefix_offset(src_prefix) + post * src_range.start);
1339                    let aliasing =
1340                        self.plain_ram_storage().as_ptr() == src.plain_ram_storage().as_ptr();
1341                    let dst_offset = self.prefix_offset(prefix) + post * range.start;
1342                    let dst_ptr = self.plain_ram_storage_mut().as_mut_ptr().add(dst_offset);
1343                    for run in 0..outer {
1344                        let from = src_ptr.add(run * src_block);
1345                        let to = dst_ptr.add(run * dst_block);
1346                        if aliasing {
1347                            std::ptr::copy(from, to, len);
1348                        } else {
1349                            std::ptr::copy_nonoverlapping(from, to, len);
1350                        }
1351                    }
1352                }
1353            } else {
1354                dispatch_datum!(assign_slice_t(self.datum_type())(
1355                    self, prefix, range, src, src_prefix, src_range, axis
1356                ));
1357            }
1358        }
1359    }
1360    /// Fill `range` along `axis` with `value`, a one-element tensor of this
1361    /// tensor's datum type.
1362    pub fn fill_slice(
1363        &mut self,
1364        range: impl std::ops::RangeBounds<usize>,
1365        value: &Tensor,
1366        axis: usize,
1367    ) -> TractResult<()> {
1368        self.fill_slice_at_prefix(&[], range, value, axis)
1369    }
1370
1371    /// Fill `range` along `axis` of the sub-tensor at `prefix`, which indexes
1372    /// the leading axes as [`Tensor::view_at_prefix`] does, with `value`, a
1373    /// one-element tensor of this tensor's datum type. `axis` stays an axis of
1374    /// the whole tensor, so it has to sit past `prefix`.
1375    pub fn fill_slice_at_prefix(
1376        &mut self,
1377        prefix: &[usize],
1378        range: impl std::ops::RangeBounds<usize>,
1379        value: &Tensor,
1380        axis: usize,
1381    ) -> TractResult<()> {
1382        ensure!(axis < self.rank(), "Filling axis {axis} of {self:?}");
1383        ensure!(
1384            prefix.len() <= axis,
1385            "Filling axis {axis} of {self:?} at prefix {prefix:?}, which reaches it"
1386        );
1387        ensure!(
1388            izip!(prefix, self.shape()).all(|(ix, dim)| ix < dim),
1389            "Filling {self:?} at prefix {prefix:?}"
1390        );
1391        ensure!(
1392            value.datum_type() == self.datum_type() && value.len() == 1,
1393            "Filling {:?} with {value:?}",
1394            self.datum_type()
1395        );
1396        let range = clip_range_bounds(self.shape[axis], range);
1397        ensure!(
1398            range.end <= self.shape[axis],
1399            "Filling invalid slice (axis {axis}, {range:?}) of {self:?}"
1400        );
1401        if !self.datum_type().is_copy() {
1402            return dispatch_datum!(Self::fill_slice_t(self.datum_type())(
1403                self, prefix, range, value, axis
1404            ));
1405        }
1406        // Tensors carry natural strides, so the range is one contiguous run per
1407        // coordinate of the axes between the prefix and `axis`, and a run of one
1408        // datum grows to its whole length in log2(len) copies of itself.
1409        let dt_size = self.datum_type().size_of();
1410        let post = self.strides[axis] as usize * dt_size;
1411        let len = post * range.len();
1412        if len == 0 {
1413            return Ok(());
1414        }
1415        let block = post * self.shape[axis];
1416        let runs: usize = self.shape[prefix.len()..axis].iter().product();
1417        let start = self.prefix_offset(prefix) + range.start * post;
1418        let value = &value.as_bytes()[..dt_size];
1419        let data = self.as_bytes_mut();
1420        for run in 0..runs {
1421            let run = &mut data[start + run * block..start + run * block + len];
1422            run[..dt_size].copy_from_slice(value);
1423            let mut written = dt_size;
1424            while written < len {
1425                let grow = written.min(len - written);
1426                run.copy_within(0..grow, written);
1427                written += grow;
1428            }
1429        }
1430        Ok(())
1431    }
1432
1433    fn fill_slice_t<T: Datum>(
1434        &mut self,
1435        prefix: &[usize],
1436        range: Range<usize>,
1437        value: &Tensor,
1438        axis: usize,
1439    ) -> TractResult<()> {
1440        let value = value.try_as_plain_ram()?.to_scalar::<T>()?.clone();
1441        let mut view = self.to_plain_array_view_mut::<T>()?;
1442        for (ax, ix) in prefix.iter().enumerate() {
1443            view.slice_axis_inplace(Axis(ax), (*ix..*ix + 1).into());
1444        }
1445        view.slice_axis_mut(Axis(axis), range.into()).fill(value);
1446        Ok(())
1447    }
1448
1449    /// Get the datum type of the tensor.
1450    #[inline]
1451    pub fn datum_type(&self) -> DatumType {
1452        self.dt
1453    }
1454
1455    /// Set the datum type of the tensor.
1456    #[inline]
1457    pub unsafe fn set_datum_type(&mut self, dt: DatumType) {
1458        self.dt = dt
1459    }
1460
1461    /// Dump the tensor in a human readable form.
1462    ///
1463    /// `force_full` will force the tensor to be dump in full even if it is big.
1464    pub fn dump(&self, force_full: bool) -> TractResult<String> {
1465        if self.as_plain_ram_storage().is_none() {
1466            return Ok(format!(
1467                "{},{:?} (non-plain storage)",
1468                self.shape.iter().join(","),
1469                self.dt,
1470            ));
1471        }
1472        unsafe fn dump_t<D: Datum>(tensor: &Tensor, n: usize) -> String {
1473            unsafe {
1474                if let Some(qp) = tensor.datum_type().qparams() {
1475                    let integers = tensor.cast_to::<i32>().unwrap();
1476                    integers.as_slice_unchecked::<i32>()[0..n]
1477                        .iter()
1478                        .map(|x| format!("[{}]({})", x, qp.dq(*x)))
1479                        .join(", ")
1480                } else {
1481                    tensor.as_slice_unchecked::<D>()[0..n].iter().join(", ")
1482                }
1483            }
1484        }
1485        unsafe {
1486            let trunc = self.len() > 12 && !force_full;
1487            let data = dispatch_datum!(dump_t(self.datum_type())(
1488                self,
1489                if trunc { 12 } else { self.len() }
1490            ));
1491            Ok(format!(
1492                "{},{:?} {}{}",
1493                self.shape.iter().join(","),
1494                self.dt,
1495                data,
1496                if trunc { "..." } else { "" }
1497            ))
1498        }
1499    }
1500
1501    /// Compare two tensors, allowing for rounding errors.
1502    pub fn close_enough(
1503        &self,
1504        other: &Self,
1505        approx: impl Into<Approximation> + std::fmt::Debug,
1506    ) -> TractResult<()> {
1507        let approx = approx.into();
1508        if self.shape() != other.shape() {
1509            bail!("Shape mismatch {:?} != {:?}", self.shape(), other.shape())
1510        }
1511        if let Approximation::Ulp(max_ulp) = approx {
1512            return self.ulp_close_enough(other, max_ulp);
1513        }
1514        let (atol, rtol, outliers) = approx.atol_rtol_outliers(&self.datum_type());
1515        let ma = self.cast_to::<f32>()?;
1516        let ma = ma.to_plain_array_view::<f32>()?;
1517        let mb = other.cast_to::<f32>()?;
1518        let mb = mb.to_plain_array_view::<f32>()?;
1519        let mut first_outlier = None;
1520        let mut outliers_count = 0;
1521        ndarray::indices_of(&ma).into_iter().for_each(|indices| {
1522            let a = ma[&indices];
1523            let b = mb[&indices];
1524            if !((a.is_nan() && b.is_nan())
1525                || (a.is_infinite() && b.is_infinite() && a.signum() == b.signum())
1526                || (a - b).abs() <= atol as f32 + rtol as f32 * b.abs())
1527            {
1528                if outliers_count == 0 {
1529                    first_outlier = Some(indices.as_array_view().to_vec());
1530                }
1531                outliers_count += 1;
1532            }
1533        });
1534        if self.volume() > 0 && outliers_count as f64 / self.volume() as f64 > outliers {
1535            let indices = first_outlier.unwrap();
1536            let a = ma[&*indices];
1537            let b = mb[&*indices];
1538            let ulp = self
1539                .max_ulp_distance(other)
1540                .map(|(d, _)| format!("{d}"))
1541                .unwrap_or_else(|_| "n/a".to_string());
1542            bail!(
1543                "Mismatch. First outlier: {:?} for {:?}) at {:?} {} != {}. Outliers: {} / {} = {:0.5} > {:0.5}. Max ULP ({:?}): {}.",
1544                approx,
1545                self.datum_type(),
1546                indices,
1547                a,
1548                b,
1549                outliers_count,
1550                self.volume(),
1551                outliers_count as f64 / self.volume() as f64,
1552                outliers,
1553                self.ulp_comparison_dt(),
1554                ulp,
1555            );
1556        }
1557        Ok(())
1558    }
1559
1560    /// The float type ULP distances against this tensor are measured in.
1561    ///
1562    /// Float tensors are compared in their own type, so an f16 comparison stays an
1563    /// f16 comparison. Anything else falls back to f32, matching what
1564    /// `close_enough` does for its tolerance check.
1565    pub fn ulp_comparison_dt(&self) -> DatumType {
1566        match self.datum_type() {
1567            dt @ (DatumType::F16 | DatumType::F32 | DatumType::F64) => dt,
1568            _ => DatumType::F32,
1569        }
1570    }
1571
1572    /// Largest integer ULP distance between `self` and `other`, and the flat index
1573    /// where it occurs.
1574    ///
1575    /// Comparison happens in [`Self::ulp_comparison_dt`]. See [`crate::ulp`] for
1576    /// the exact convention around signed zeros, infinities and NaN.
1577    pub fn max_ulp_distance(&self, other: &Self) -> TractResult<(u64, Option<usize>)> {
1578        if self.shape() != other.shape() {
1579            bail!("Shape mismatch {:?} != {:?}", self.shape(), other.shape())
1580        }
1581        let dt = self.ulp_comparison_dt();
1582        let a = self.cast_to_dt(dt)?;
1583        let b = other.cast_to_dt(dt)?;
1584        fn worst<D: Datum + crate::ulp::UlpFloat>(
1585            a: &Tensor,
1586            b: &Tensor,
1587        ) -> TractResult<(u64, Option<usize>)> {
1588            let a = a.to_plain_array_view::<D>()?;
1589            let b = b.to_plain_array_view::<D>()?;
1590            Ok(crate::ulp::max_ulp_distance(a.iter().copied(), b.iter().copied()))
1591        }
1592        match dt {
1593            DatumType::F16 => worst::<f16>(&a, &b),
1594            DatumType::F32 => worst::<f32>(&a, &b),
1595            DatumType::F64 => worst::<f64>(&a, &b),
1596            dt => bail!("No ULP comparison for {dt:?}"),
1597        }
1598    }
1599
1600    /// Compare two tensors by integer ULP distance, accepting a distance up to
1601    /// `max_ulp`.
1602    fn ulp_close_enough(&self, other: &Self, max_ulp: u64) -> TractResult<()> {
1603        let (worst, at) = self.max_ulp_distance(other)?;
1604        if worst <= max_ulp {
1605            return Ok(());
1606        }
1607        let dt = self.ulp_comparison_dt();
1608        let indices = at
1609            .map(|flat| {
1610                let mut rest = flat;
1611                let mut indices = vec![0; self.rank()];
1612                for (ix, dim) in self.shape().iter().enumerate().rev() {
1613                    indices[ix] = rest % dim;
1614                    rest /= dim;
1615                }
1616                format!("{indices:?}")
1617            })
1618            .unwrap_or_else(|| "?".to_string());
1619        let a = self.cast_to::<f64>()?;
1620        let b = other.cast_to::<f64>()?;
1621        let (a, b) = (a.to_plain_array_view::<f64>()?, b.to_plain_array_view::<f64>()?);
1622        let flat = at.unwrap_or(0);
1623        bail!(
1624            "Mismatch. Max ULP distance ({dt:?}): {} > {}, at {} ({} != {}).",
1625            worst,
1626            max_ulp,
1627            indices,
1628            a.iter().nth(flat).copied().unwrap_or(f64::NAN),
1629            b.iter().nth(flat).copied().unwrap_or(f64::NAN),
1630        );
1631    }
1632
1633    /// Transform the tensor into a `ndarray::Array`.
1634    pub fn into_plain_array<D: Datum>(self) -> TractResult<ArrayD<D>> {
1635        Ok(self.to_plain_array_view::<D>()?.to_owned())
1636    }
1637
1638    /// Transform the tensor into a `ndarray::Array`.
1639    pub unsafe fn into_array_unchecked<D: Datum>(self) -> ArrayD<D> {
1640        unsafe { self.to_array_view_unchecked::<D>().to_owned() }
1641    }
1642
1643    /// Returns a plain array view of the tensor.
1644    ///
1645    /// Errors if the storage is not plain or the datum type does not match `D`.
1646    #[inline]
1647    pub fn to_plain_array_view<D: Datum>(&self) -> TractResult<ArrayViewD<'_, D>> {
1648        self.try_as_plain_ram()?.to_array_view::<D>()
1649    }
1650
1651    /// Returns a mutable plain array view of the tensor.
1652    ///
1653    /// Errors if the storage is not plain or the datum type does not match `D`.
1654    #[inline]
1655    pub fn to_plain_array_view_mut<D: Datum>(&mut self) -> TractResult<ArrayViewMutD<'_, D>> {
1656        self.check_for_access::<D>()?;
1657        ensure!(self.storage.as_plain_ram_mut().is_some(), "Tensor storage is not plain");
1658        unsafe { Ok(self.to_array_view_mut_unchecked()) }
1659    }
1660
1661    fn check_for_access<D: Datum>(&self) -> TractResult<()> {
1662        ensure!(
1663            self.datum_type().unquantized() == D::datum_type().unquantized(),
1664            "Tensor datum type error: tensor is {:?}, accessed as {:?}",
1665            self.datum_type(),
1666            D::datum_type(),
1667        );
1668        Ok(())
1669    }
1670
1671    /// Transform the data as a `ndarray::Array`.
1672    pub unsafe fn to_array_view_unchecked<D: Datum>(&self) -> ArrayViewD<'_, D> {
1673        if self.len() != 0 {
1674            unsafe {
1675                ArrayViewD::from_shape_ptr(
1676                    &*self.shape,
1677                    self.plain_ram_storage().as_ptr() as *const D,
1678                )
1679            }
1680        } else {
1681            ArrayViewD::from_shape(&*self.shape, &[]).unwrap()
1682        }
1683    }
1684
1685    /// Transform the data as a mutable `ndarray::Array`.
1686    pub unsafe fn to_array_view_mut_unchecked<D: Datum>(&mut self) -> ArrayViewMutD<'_, D> {
1687        if self.len() != 0 {
1688            unsafe {
1689                let ptr = self.plain_ram_storage_mut().as_mut_ptr() as *mut D;
1690                ArrayViewMutD::from_shape_ptr(&*self.shape, ptr)
1691            }
1692        } else {
1693            ArrayViewMutD::from_shape(&*self.shape, &mut []).unwrap()
1694        }
1695    }
1696
1697    /// Access the data as a pointer.
1698    pub fn as_ptr<D: Datum>(&self) -> TractResult<*const D> {
1699        self.check_for_access::<D>()?;
1700        Ok(self.plain_ram_storage().as_ptr() as *const D)
1701    }
1702
1703    /// Access the data as a pointer.
1704    pub unsafe fn as_ptr_unchecked<D: Datum>(&self) -> *const D {
1705        self.plain_ram_storage().as_ptr() as *const D
1706    }
1707
1708    /// Access the data as a pointer.
1709    pub unsafe fn as_ptr_mut_unchecked<D: Datum>(&mut self) -> *mut D {
1710        self.plain_ram_storage_mut().as_mut_ptr() as *mut D
1711    }
1712
1713    /// Access the data as a mutable pointer.
1714    pub fn as_ptr_mut<D: Datum>(&mut self) -> TractResult<*mut D> {
1715        self.check_for_access::<D>()?;
1716        Ok(self.plain_ram_storage_mut().as_mut_ptr() as *mut D)
1717    }
1718
1719    /// Access the data as a slice.
1720    pub unsafe fn as_slice_unchecked<D: Datum>(&self) -> &[D] {
1721        if self.storage.byte_len() == 0 {
1722            &[]
1723        } else {
1724            unsafe { std::slice::from_raw_parts::<D>(self.as_ptr_unchecked(), self.len()) }
1725        }
1726    }
1727
1728    /// Access the data as a mutable slice.
1729    pub unsafe fn as_slice_mut_unchecked<D: Datum>(&mut self) -> &mut [D] {
1730        if self.storage.byte_len() == 0 {
1731            &mut []
1732        } else {
1733            unsafe { std::slice::from_raw_parts_mut::<D>(self.as_ptr_mut_unchecked(), self.len()) }
1734        }
1735    }
1736
1737    /// Make the tensor a scalar tensor (assumes it contains a single value).
1738    pub fn to_scalar_tensor(&self) -> TractResult<Tensor> {
1739        fn to_scalar_tensor_t<D: Datum>(t: &Tensor) -> TractResult<Tensor> {
1740            Ok(litteral::tensor0(t.try_as_plain_ram()?.to_scalar::<D>()?.clone()))
1741        }
1742        dispatch_datum!(to_scalar_tensor_t(self.datum_type())(self))
1743    }
1744
1745    /// Access the data as a scalar.
1746    pub unsafe fn to_scalar_unchecked<D: Datum>(&self) -> &D {
1747        unsafe { &*(self.plain_ram_storage().as_ptr() as *const D) }
1748    }
1749
1750    /// Mutable access the data as a scalar.
1751    pub fn to_scalar_mut<D: Datum>(&mut self) -> TractResult<&mut D> {
1752        self.check_for_access::<D>()?;
1753        if self.len() == 0 {
1754            bail!("to_scalar_mut called on empty tensor ({:?})", self)
1755        }
1756        if self.len() > 1 {
1757            bail!("to_scalar called on a tensor with multiple values ({:?})", self)
1758        }
1759        unsafe { Ok(self.to_scalar_mut_unchecked()) }
1760    }
1761
1762    /// Mutable access the data as a scalar.
1763    pub unsafe fn to_scalar_mut_unchecked<D: Datum>(&mut self) -> &mut D {
1764        unsafe { &mut *(self.plain_ram_storage_mut().as_mut_ptr() as *mut D) }
1765    }
1766
1767    pub fn as_bytes(&self) -> &[u8] {
1768        self.plain_ram_storage().as_bytes()
1769    }
1770
1771    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
1772        self.plain_ram_storage_mut().as_bytes_mut()
1773    }
1774
1775    unsafe fn is_uniform_t<T: Datum>(&self) -> bool {
1776        let slice = unsafe { self.as_slice_unchecked::<T>() };
1777        slice[1..].iter().all(|x| x == &slice[0])
1778    }
1779
1780    pub fn is_uniform(&self) -> bool {
1781        if self.as_plain_ram_storage().is_none() {
1782            return false;
1783        }
1784        if self.len() <= 1 {
1785            return true;
1786        }
1787        unsafe { dispatch_datum!(Tensor::is_uniform_t(self.datum_type())(self)) }
1788    }
1789
1790    unsafe fn as_uniform_t<T: Datum>(&self) -> Tensor {
1791        let v: T = unsafe { self.as_slice_unchecked::<T>() }[0].clone();
1792        litteral::tensor0(v)
1793    }
1794
1795    pub fn as_uniform(&self) -> Option<Tensor> {
1796        if self.len() >= 1 && self.is_uniform() {
1797            unsafe {
1798                let mut t = dispatch_datum!(Tensor::as_uniform_t(self.datum_type())(self));
1799                t.set_datum_type(self.datum_type());
1800                Some(t)
1801            }
1802        } else {
1803            None
1804        }
1805    }
1806
1807    pub fn is_all_zero(&self) -> TractResult<bool> {
1808        Ok(self.len() == 0 || self.as_uniform().map(|t| t.is_zero().unwrap()).unwrap_or(false))
1809    }
1810
1811    pub fn is_zero(&self) -> TractResult<bool> {
1812        Ok(self == &Tensor::zero_scalar_dt(self.dt)?)
1813    }
1814
1815    unsafe fn natural_cast<
1816        Source: Datum + num_traits::AsPrimitive<Target>,
1817        Target: Datum + Copy,
1818    >(
1819        &self,
1820        other: &mut Tensor,
1821    ) {
1822        unsafe {
1823            self.as_slice_unchecked::<Source>()
1824                .iter()
1825                .zip(other.as_slice_mut_unchecked::<Target>().iter_mut())
1826                .for_each(|(s, d)| *d = s.as_())
1827        };
1828    }
1829
1830    unsafe fn cast_number_to_bool<Source: Datum + num_traits::Zero>(&self, other: &mut Tensor) {
1831        unsafe {
1832            self.as_slice_unchecked::<Source>()
1833                .iter()
1834                .zip(other.as_slice_mut_unchecked::<bool>().iter_mut())
1835                .for_each(|(s, d)| *d = !s.is_zero());
1836        }
1837    }
1838
1839    unsafe fn cast_from_string<Target: Datum + core::str::FromStr>(
1840        &self,
1841        other: &mut Tensor,
1842    ) -> TractResult<()> {
1843        unsafe {
1844            for (s, d) in self
1845                .as_slice_unchecked::<String>()
1846                .iter()
1847                .zip(other.as_slice_mut_unchecked::<Target>().iter_mut())
1848            {
1849                *d = s
1850                    .parse()
1851                    .map_err(|_| format_err!("Can not parse as {:?}", Target::datum_type()))?;
1852            }
1853            Ok(())
1854        }
1855    }
1856
1857    unsafe fn cast_to_string<Source: Datum>(&self, other: &mut Tensor) {
1858        unsafe {
1859            for (s, d) in self
1860                .as_slice_unchecked::<Source>()
1861                .iter()
1862                .zip(other.as_slice_mut_unchecked::<String>().iter_mut())
1863            {
1864                *d = s.to_string()
1865            }
1866        }
1867    }
1868
1869    /// Optionnaly convert data to a tensor for a new DatumType.
1870    pub fn cast_to<D: Datum>(&self) -> TractResult<Cow<'_, Tensor>> {
1871        self.cast_to_dt(D::datum_type())
1872    }
1873
1874    /// Optionnaly convert data to a tensor for a new DatumType.
1875    #[allow(clippy::redundant_closure_call)]
1876    pub fn cast_to_dt(&self, dst_dt: DatumType) -> TractResult<Cow<'_, Tensor>> {
1877        unsafe {
1878            if self.dt == dst_dt {
1879                return Ok(Cow::Borrowed(self));
1880            }
1881            if self.dt == TDim::datum_type() && (dst_dt.is_integer() || dst_dt.is_float()) {
1882                let slice = self.as_slice_unchecked::<TDim>();
1883                let mut ints = Self::uninitialized::<i64>(&self.shape)?;
1884                let ints_slice = ints.as_slice_mut_unchecked::<i64>();
1885                for i in 0..self.len() {
1886                    ints_slice[i] = slice[i].to_i64()?;
1887                }
1888                return Ok(Cow::Owned(ints.cast_to_dt(dst_dt)?.into_owned()));
1889            }
1890            if self.dt == bool::datum_type()
1891                && (dst_dt.is_integer() || dst_dt.is_float() || dst_dt == TDim::datum_type())
1892            {
1893                let slice = self.as_slice_unchecked::<bool>();
1894                let mut ints = Self::uninitialized::<i8>(&self.shape)?;
1895                let ints_slice = ints.as_slice_mut_unchecked::<i8>();
1896                for i in 0..self.len() {
1897                    ints_slice[i] = slice[i] as usize as i8;
1898                }
1899                return Ok(Cow::Owned(ints.cast_to_dt(dst_dt)?.into_owned()));
1900            }
1901            let mut result = Self::uninitialized_dt(dst_dt, &self.shape)?;
1902            if self.dt == DatumType::String {
1903                dispatch_numbers!(Self::cast_from_string(dst_dt)(self, &mut result))?;
1904                return Ok(Cow::Owned(result));
1905            }
1906            if dst_dt == DatumType::String {
1907                dispatch_datum!(Self::cast_to_string(self.dt)(self, &mut result));
1908                return Ok(Cow::Owned(result));
1909            }
1910            if self.dt == DatumType::F32 && dst_dt == DatumType::F16 {
1911                result
1912                    .as_slice_mut_unchecked::<f16>()
1913                    .convert_from_f32_slice(self.as_slice_unchecked::<f32>());
1914                return Ok(Cow::Owned(result));
1915            }
1916            if self.dt == DatumType::F16 && dst_dt == DatumType::F32 {
1917                self.as_slice_unchecked::<f16>()
1918                    .convert_to_f32_slice(result.as_slice_mut_unchecked::<f32>());
1919                return Ok(Cow::Owned(result));
1920            }
1921            macro_rules! n {
1922                ($source:ty) => {
1923                    if <$source>::datum_type() == self.datum_type() {
1924                        match dst_dt {
1925                            DatumType::I8 => self.natural_cast::<$source, i8>(&mut result),
1926                            DatumType::I16 => self.natural_cast::<$source, i16>(&mut result),
1927                            DatumType::I32 => self.natural_cast::<$source, i32>(&mut result),
1928                            DatumType::I64 => self.natural_cast::<$source, i64>(&mut result),
1929                            DatumType::U8 => self.natural_cast::<$source, u8>(&mut result),
1930                            DatumType::U16 => self.natural_cast::<$source, u16>(&mut result),
1931                            DatumType::U32 => self.natural_cast::<$source, u32>(&mut result),
1932                            DatumType::U64 => self.natural_cast::<$source, u64>(&mut result),
1933                            DatumType::F16 => self.natural_cast::<$source, f16>(&mut result),
1934                            DatumType::F32 => self.natural_cast::<$source, f32>(&mut result),
1935                            DatumType::F64 => self.natural_cast::<$source, f64>(&mut result),
1936                            DatumType::TDim => {
1937                                let ints = self.cast_to::<i64>()?;
1938                                let slice = ints.as_slice_unchecked::<i64>();
1939                                let result = result.as_slice_mut_unchecked::<TDim>();
1940                                for i in 0..self.len() {
1941                                    result[i] = slice[i].into();
1942                                }
1943                            }
1944                            DatumType::Bool => self.cast_number_to_bool::<$source>(&mut result),
1945                            _ => todo!(),
1946                        }
1947                        return Ok(Cow::Owned(result));
1948                    };
1949                };
1950            }
1951            //If there is no quantization
1952            if !dst_dt.is_quantized() && !self.datum_type().is_quantized() {
1953                n!(u8);
1954                n!(u16);
1955                n!(u32);
1956                n!(u64);
1957                n!(i8);
1958                n!(i16);
1959                n!(i32);
1960                n!(i64);
1961                n!(f16);
1962                n!(f32);
1963                n!(f64);
1964            } else {
1965                let (s_zp, s_scale) = self.datum_type().zp_scale();
1966                let (d_zp, d_scale) = dst_dt.zp_scale();
1967                if self.datum_type().is_quantized() && dst_dt.is_float() {
1968                    macro_rules! q_to_fp {
1969                        ($source:ty, $dest:ty) => {
1970                            if <$source>::datum_type().unquantized()
1971                                == self.datum_type().unquantized()
1972                                && <$dest>::datum_type().unquantized() == dst_dt.unquantized()
1973                            {
1974                                self.as_slice_unchecked::<$source>()
1975                                    .iter()
1976                                    .zip(result.as_slice_mut_unchecked::<$dest>().iter_mut())
1977                                    .for_each(|(&s, d)| {
1978                                        *d = (s as $dest - s_zp as $dest) * s_scale as $dest;
1979                                    });
1980                                return Ok(Cow::Owned(result));
1981                            }
1982                        };
1983                    }
1984                    q_to_fp!(i8, f64);
1985                    q_to_fp!(i8, f32);
1986                    q_to_fp!(u8, f64);
1987                    q_to_fp!(u8, f32);
1988                }
1989                //TODO: optimize scale_by
1990                macro_rules! q8_to_q8 {
1991                    ($typ:ty) => {
1992                        if dst_dt.unquantized() == <$typ>::datum_type() {
1993                            self.as_slice_unchecked::<$typ>()
1994                                .iter()
1995                                .zip(result.as_slice_mut_unchecked::<$typ>().iter_mut())
1996                                .for_each(|(&s, d)| {
1997                                    *d = (d_zp as i32
1998                                        + scale_by(s as i32 - s_zp as i32, s_scale / d_scale))
1999                                    .clamp_cast()
2000                                });
2001                            return Ok(Cow::Owned(result));
2002                        }
2003                    };
2004                }
2005
2006                macro_rules! q_via_f32 {
2007                    ($source:ty, $dest:ty, $round:expr) => {
2008                        if <$source>::datum_type().unquantized() == self.datum_type().unquantized()
2009                            && <$dest>::datum_type().unquantized() == dst_dt.unquantized()
2010                        {
2011                            self.as_slice_unchecked::<$source>()
2012                                .iter()
2013                                .zip(result.as_slice_mut_unchecked::<$dest>().iter_mut())
2014                                .for_each(|(&s, d)| {
2015                                    let s_float = (s as f32 - s_zp as f32) * s_scale as f32;
2016                                    let d_float = s_float as f32 / d_scale as f32 + d_zp as f32;
2017                                    *d = $round(d_float);
2018                                });
2019                            return Ok(Cow::Owned(result));
2020                        }
2021                    };
2022                }
2023
2024                macro_rules! q_n {
2025                    (clamp $source:ty, $dest:ty) => {{
2026                        if <$source>::datum_type().unquantized() == self.datum_type().unquantized()
2027                            && <$dest>::datum_type().unquantized() == dst_dt.unquantized()
2028                        {
2029                            self.as_slice_unchecked::<$source>()
2030                                .iter()
2031                                .zip(result.as_slice_mut_unchecked::<$dest>().iter_mut())
2032                                .for_each(|(&s, d)| {
2033                                    *d = s.clamp_cast();
2034                                });
2035                            return Ok(Cow::Owned(result));
2036                        }
2037                    }};
2038                    ($source:ty, $dest:ty) => {{
2039                        if <$source>::datum_type().unquantized() == self.datum_type().unquantized()
2040                            && <$dest>::datum_type().unquantized() == dst_dt.unquantized()
2041                        {
2042                            self.as_slice_unchecked::<$source>()
2043                                .iter()
2044                                .zip(result.as_slice_mut_unchecked::<$dest>().iter_mut())
2045                                .for_each(|(&s, d)| {
2046                                    *d = s as $dest;
2047                                });
2048                            return Ok(Cow::Owned(result));
2049                        }
2050                    }};
2051                }
2052
2053                if dst_dt.unquantized() == self.datum_type().unquantized()
2054                    && dst_dt.is_quantized()
2055                    && self.datum_type().is_quantized()
2056                {
2057                    q8_to_q8!(i8);
2058                    q8_to_q8!(u8);
2059                }
2060
2061                q_via_f32!(f32, i8, |f| round_ties_to_even(f).clamp_cast());
2062                q_via_f32!(f32, u8, |f| round_ties_to_even(f).clamp_cast());
2063                q_via_f32!(f32, i32, |f| round_ties_to_even(f).clamp_cast());
2064                q_via_f32!(i8, f32, |f| f);
2065                q_via_f32!(u8, f32, |f| f);
2066                q_via_f32!(i32, f32, |f| f);
2067
2068                if dst_dt.is_quantized() && self.datum_type().is_quantized() {
2069                    q_via_f32!(u8, i8, |f| round_ties_to_even(f).clamp_cast());
2070                    q_via_f32!(i8, u8, |f| round_ties_to_even(f).clamp_cast());
2071                    q_via_f32!(i32, u8, |f| round_ties_to_even(f).clamp_cast());
2072                    q_via_f32!(i32, i8, |f| round_ties_to_even(f).clamp_cast());
2073                    q_via_f32!(u8, i32, |f| round_ties_to_even(f).clamp_cast());
2074                    q_via_f32!(i8, i32, |f| round_ties_to_even(f).clamp_cast());
2075
2076                    // ensure cast to different scale offset work
2077                    q_via_f32!(i8, i8, |f| round_ties_to_even(f).clamp_cast());
2078                    q_via_f32!(u8, u8, |f| round_ties_to_even(f).clamp_cast());
2079                }
2080
2081                q_n!(i8, i32);
2082                q_n!(i8, u32);
2083                q_n!(u8, i32);
2084                q_n!(u8, u32);
2085                q_n!(clamp i32, i8);
2086                q_n!(clamp i32, u8);
2087                q_n!(clamp u32, i8);
2088                q_n!(clamp u32, u8);
2089                q_n!(i8, i8);
2090                q_n!(u8, u8);
2091                q_n!(i32, i32);
2092                q_n!(u32, u32);
2093            }
2094
2095            bail!("Unsupported cast from {:?} to {:?}", self.dt, dst_dt)
2096        }
2097    }
2098
2099    /// Access the data as a scalar, after a cast.
2100    pub fn cast_to_scalar<D: Datum + Copy>(&self) -> TractResult<D> {
2101        let casted = self.cast_to::<D>()?;
2102        casted.try_as_plain_ram()?.to_scalar::<D>().copied()
2103    }
2104
2105    /// Access the nth element of the tensor, returned as a 0-rank Tensor
2106    pub fn nth(&self, nth: usize) -> TractResult<Tensor> {
2107        if nth >= self.len() {
2108            bail!(
2109                "nth called with {}th element on a tensor of len {} ({:?}",
2110                nth,
2111                self.len(),
2112                self
2113            );
2114        }
2115        unsafe fn nth_t<T: Datum>(me: &Tensor, nth: usize, output: &mut Tensor) {
2116            unsafe {
2117                let value = me.as_slice_unchecked::<T>()[nth].clone();
2118                std::ptr::write(output.as_slice_mut_unchecked::<T>().as_mut_ptr(), value);
2119            }
2120        }
2121        unsafe {
2122            let mut output = Tensor::uninitialized_dt(self.datum_type(), &[])?;
2123            dispatch_datum_by_size!(nth_t(self.datum_type())(self, nth, &mut output));
2124            Ok(output)
2125        }
2126    }
2127
2128    /// Strict equality test on tensors.
2129    fn eq_dt(&self, other: &Tensor) -> TractResult<bool> {
2130        unsafe fn eq_t<D: Datum>(me: &Tensor, other: &Tensor) -> TractResult<bool> {
2131            unsafe {
2132                if D::datum_type().is_float() {
2133                    return dispatch_floatlike!(float_eq_t(D::datum_type())(me, other));
2134                }
2135                Ok(izip!(me.as_slice_unchecked::<D>(), other.as_slice_unchecked::<D>())
2136                    .all(|(a, b)| a == b))
2137            }
2138        }
2139
2140        unsafe fn float_eq_t<D: Datum + Float>(me: &Tensor, other: &Tensor) -> TractResult<bool> {
2141            unsafe {
2142                Ok(izip!(me.as_slice_unchecked::<D>(), other.as_slice_unchecked::<D>())
2143                    .all(|(a, b)| (a.is_nan() && b.is_nan()) || a == b))
2144            }
2145        }
2146
2147        unsafe {
2148            Ok(self.datum_type() == other.datum_type()
2149                && self.shape() == other.shape()
2150                && dispatch_datum!(eq_t(self.dt)(self, other))?)
2151        }
2152    }
2153
2154    fn from_datum<T: Datum>(mut it: ArrayD<T>) -> Tensor {
2155        unsafe {
2156            let mut t = Self::uninitialized::<T>(it.shape()).unwrap();
2157            if let Some(slice) = it.as_slice_mut() {
2158                if t.datum_type().is_copy() {
2159                    std::ptr::copy_nonoverlapping(
2160                        slice.as_ptr() as *const i8,
2161                        t.as_ptr_mut_unchecked(),
2162                        t.plain_ram_storage().layout().size(),
2163                    );
2164                } else {
2165                    t.as_slice_mut_unchecked::<T>()
2166                        .iter_mut()
2167                        .zip(slice.iter_mut())
2168                        .for_each(|(t, s)| *t = std::mem::take(s));
2169                }
2170                return t;
2171            }
2172            if it.strides().iter().all(|&s| s > 0) && it.as_slice_memory_order().is_some() {
2173                let mut len_and_strides: TVec<(usize, usize)> = tvec!();
2174                for (len, stride) in itertools::izip!(it.shape(), it.strides(), t.strides())
2175                    .sorted_by_key(|(_, src, _)| *src)
2176                    .map(|(l, _, dst)| (*l as isize, *dst))
2177                {
2178                    if !len_and_strides.is_empty()
2179                        && len_and_strides.last().unwrap().1 * len_and_strides.last().unwrap().0
2180                            == stride as usize
2181                    {
2182                        len_and_strides.last_mut().unwrap().0 *= len as usize;
2183                    } else {
2184                        len_and_strides.push((len as usize, stride as usize));
2185                    }
2186                }
2187                len_and_strides.reverse();
2188                crate::scatter::scatter_contig_data(
2189                    it.as_ptr(),
2190                    t.as_ptr_mut_unchecked(),
2191                    &len_and_strides,
2192                );
2193                return t;
2194            }
2195            // finally use ndarray into_iter()
2196            t.as_slice_mut_unchecked().iter_mut().zip(it).for_each(|(t, a)| *t = a);
2197            t
2198        }
2199    }
2200
2201    pub fn deep_clone(&self) -> Tensor {
2202        if self.as_plain_ram_storage().is_none() {
2203            return Tensor {
2204                dt: self.dt,
2205                shape: self.shape.clone(),
2206                strides: self.strides.clone(),
2207                len: self.len,
2208                storage: self.storage.deep_clone(),
2209            };
2210        }
2211        unsafe {
2212            let mut tensor = Tensor::uninitialized_dt(self.datum_type(), self.shape()).unwrap();
2213            if self.len() > 0 {
2214                if self.dt.is_copy() {
2215                    self.plain_ram_storage().as_ptr().copy_to_nonoverlapping(
2216                        tensor.as_bytes_mut().as_mut_ptr(),
2217                        self.plain_ram_storage().layout().size(),
2218                    )
2219                } else if self.dt == DatumType::String {
2220                    tensor
2221                        .as_slice_mut_unchecked::<String>()
2222                        .clone_from_slice(self.as_slice_unchecked());
2223                } else if self.dt == DatumType::Blob {
2224                    tensor
2225                        .as_slice_mut_unchecked::<Blob>()
2226                        .clone_from_slice(self.as_slice_unchecked());
2227                } else if self.dt == DatumType::TDim {
2228                    tensor
2229                        .as_slice_mut_unchecked::<TDim>()
2230                        .clone_from_slice(self.as_slice_unchecked());
2231                }
2232            }
2233            tensor
2234        }
2235    }
2236
2237    pub fn slice(&self, axis: usize, start: usize, end: usize) -> TractResult<Tensor> {
2238        if axis >= self.rank() {
2239            bail!("Can not slice at axis {} tensor {:?}", axis, self);
2240        }
2241        if start > self.shape[axis] || end > self.shape[axis] || start >= end {
2242            bail!("Invalid slicing range {start}..{end} on axis {axis} for {self:?}");
2243        }
2244        // Storage gets first refusal: one that can serve the slice without a
2245        // copy does so, anything else falls through to the copy below.
2246        if let Some(sliced) =
2247            self.storage.as_storage().slice(self.dt, self.shape(), axis, start, end)?
2248        {
2249            return Ok(sliced);
2250        }
2251        let mut shape: TVec<usize> = self.shape().into();
2252        shape[axis] = end - start;
2253        unsafe {
2254            let mut tensor = Tensor::uninitialized_dt(self.datum_type(), &shape)?;
2255            tensor.assign_slice_from_resolved(&[], 0..end - start, self, &[], start..end, axis);
2256            Ok(tensor)
2257        }
2258    }
2259
2260    /// A read-only view of the whole tensor. Panics if the storage is not plain.
2261    #[inline]
2262    pub fn view(&self) -> view::TensorView<'_> {
2263        view::TensorView::of_tensor(self)
2264    }
2265
2266    /// The sub-tensor at `prefix`: the trailing axes, from the item `prefix` points to.
2267    #[inline]
2268    pub fn view_at_prefix(&self, prefix: &[usize]) -> TractResult<view::TensorView<'_>> {
2269        view::TensorView::at_prefix(self, prefix)
2270    }
2271
2272    /// A view with the tensor's shape and strides whose origin is moved to `coords`.
2273    pub fn view_offsetting(&self, coords: &[usize]) -> TractResult<view::TensorView<'_>> {
2274        ensure!(
2275            coords.len() == self.rank() && coords.iter().zip(self.shape()).all(|(p, d)| p < d),
2276            "Invalid coords {:?} for shape {:?}",
2277            coords,
2278            self.shape()
2279        );
2280        let mut view = self.view();
2281        for (axis, &pos) in coords.iter().enumerate() {
2282            view.offset_axis(axis, pos)?;
2283        }
2284        Ok(view)
2285    }
2286
2287    /// A mutable view of the whole tensor. Panics if the storage is not plain.
2288    #[inline]
2289    pub fn view_mut(&mut self) -> view::TensorViewMut<'_> {
2290        view::TensorViewMut::of_tensor(self)
2291    }
2292
2293    /// The mutable counterpart of [`Self::view_offsetting`].
2294    pub fn view_offsetting_mut(
2295        &mut self,
2296        coords: &[usize],
2297    ) -> TractResult<view::TensorViewMut<'_>> {
2298        ensure!(
2299            coords.len() == self.rank() && coords.iter().zip(self.shape()).all(|(p, d)| p < d),
2300            "Invalid coords {:?} for shape {:?}",
2301            coords,
2302            self.shape()
2303        );
2304        let mut view = self.view_mut();
2305        for (axis, &pos) in coords.iter().enumerate() {
2306            view.offset_axis(axis, pos)?;
2307        }
2308        Ok(view)
2309    }
2310
2311    /// Offsets the tensor as an i8 type if it's an u8 type, otherwise passes it unchanged.
2312    pub fn offset_u8_as_i8(self: &Arc<Self>) -> Arc<Self> {
2313        let mut t = if let DatumType::U8 = self.dt.unquantized() {
2314            self.try_as_plain_ram()
2315                .unwrap()
2316                .to_array_view::<u8>()
2317                .unwrap()
2318                .mapv(|v| v.wrapping_sub(128) as i8)
2319                .into_tensor()
2320        } else {
2321            return self.clone();
2322        };
2323
2324        if let DatumType::QU8(qp) = self.dt {
2325            if let QParams::ZpScale { zero_point, scale } = qp {
2326                t.dt = DatumType::QI8(QParams::ZpScale { zero_point: zero_point - 128, scale });
2327            } else {
2328                t.dt = DatumType::QI8(qp);
2329            }
2330        }
2331
2332        t.into_arc_tensor()
2333    }
2334
2335    /// Offsets the tensor as an u8 type if it's an i8 type, otherwise passes it unchanged.
2336    pub fn offset_i8_as_u8(self: &Arc<Self>) -> Arc<Self> {
2337        let mut t = if let DatumType::I8 = self.dt.unquantized() {
2338            self.try_as_plain_ram()
2339                .unwrap()
2340                .to_array_view::<i8>()
2341                .unwrap()
2342                .mapv(|v| (v as u8).wrapping_add(128))
2343                .into_tensor()
2344        } else {
2345            return self.clone();
2346        };
2347
2348        if let DatumType::QI8(qp) = self.dt {
2349            if let QParams::ZpScale { zero_point, scale } = qp {
2350                t.dt = DatumType::QU8(QParams::ZpScale { zero_point: zero_point + 128, scale });
2351            } else {
2352                t.dt = DatumType::QU8(qp);
2353            }
2354        }
2355        t.into_arc_tensor()
2356    }
2357
2358    pub fn to_aligned_default(&self) -> TractResult<Self> {
2359        if self.dt.is_copy() {
2360            unsafe {
2361                let mut t = Self::uninitialized_dt(self.dt, &self.shape)?;
2362                t.as_bytes_mut().copy_from_slice(self.as_bytes());
2363                Ok(t)
2364            }
2365        } else {
2366            let mut t = Self::zero_dt(self.dt, &self.shape)?;
2367            if self.dt == String::datum_type() {
2368                t.try_as_plain_ram_mut()?
2369                    .as_slice_mut::<String>()?
2370                    .clone_from_slice(self.try_as_plain_ram()?.as_slice()?);
2371            } else if self.dt == Blob::datum_type() {
2372                t.try_as_plain_ram_mut()?
2373                    .as_slice_mut::<Blob>()?
2374                    .clone_from_slice(self.try_as_plain_ram()?.as_slice()?);
2375            } else if self.dt == TDim::datum_type() {
2376                t.try_as_plain_ram_mut()?
2377                    .as_slice_mut::<TDim>()?
2378                    .clone_from_slice(self.try_as_plain_ram()?.as_slice()?);
2379            }
2380            Ok(t)
2381        }
2382    }
2383
2384    pub fn natural_strides(shape: &[usize]) -> TVec<isize> {
2385        let mut strides = tvec!();
2386        compute_natural_stride_to(&mut strides, shape);
2387        strides
2388    }
2389
2390    /// Returns `true` if this tensor owns plain ram storage outright, rather
2391    /// than storage that produces or holds some -- a device readback that has
2392    /// come back still keeps its device tensor.
2393    #[inline]
2394    pub fn has_plain_ram_storage(&self) -> bool {
2395        matches!(self.storage, StorageKind::Plain(_))
2396    }
2397
2398    /// See [`TensorStorage::stays_lazy`].
2399    pub fn stays_lazy(&self) -> bool {
2400        matches!(&self.storage, StorageKind::Exotic(o) if o.stays_lazy())
2401    }
2402
2403    /// This tensor backed by plain ram storage of its own: bytes left on a
2404    /// device come back here, and exotic storage, which has no plain form,
2405    /// errors.
2406    pub fn into_plain_ram(mut self) -> TractResult<Tensor> {
2407        if self.has_plain_ram_storage() {
2408            return Ok(self);
2409        }
2410        ensure!(self.dt.is_copy());
2411        let storage =
2412            std::mem::replace(&mut self.storage, StorageKind::Plain(PlainStorage::default()));
2413        let storage = storage.into_plain_ram().context("Storage can not produce plain bytes")?;
2414        Ok(Tensor {
2415            dt: self.dt,
2416            shape: self.shape.clone(),
2417            strides: self.strides.clone(),
2418            len: self.len,
2419            storage: StorageKind::Plain(storage),
2420        })
2421    }
2422
2423    pub fn into_blob(mut self) -> TractResult<Blob> {
2424        ensure!(self.dt.is_copy());
2425        let storage =
2426            std::mem::replace(&mut self.storage, StorageKind::Plain(PlainStorage::default()));
2427        Ok(storage.into_plain_ram().context("Storage is not plain")?.into_blob())
2428    }
2429}
2430
2431impl PartialEq for Tensor {
2432    fn eq(&self, other: &Tensor) -> bool {
2433        if self.dt != other.dt || self.shape != other.shape {
2434            return false;
2435        }
2436        match (self.storage.as_plain_ram(), other.storage.as_plain_ram()) {
2437            (Some(_), Some(_)) => self.eq_dt(other).unwrap_or(false),
2438            (None, None) => self.storage == other.storage,
2439            _ => false,
2440        }
2441    }
2442}
2443
2444impl Eq for Tensor {}
2445
2446impl fmt::Debug for Tensor {
2447    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2448        let content = self.dump(false).unwrap_or_else(|e| format!("Error : {e:?}"));
2449        write!(formatter, "{content}")
2450    }
2451}
2452
2453#[cfg(feature = "complex")]
2454pub fn reinterpret_inner_dim_as_complex(mut t: Tensor) -> TractResult<Tensor> {
2455    ensure!(
2456        t.shape().last() == Some(&2),
2457        "The last dimension in the tensor shape {:?} must be 2",
2458        t.shape()
2459    );
2460    unsafe {
2461        t.shape.pop();
2462        t.set_datum_type(t.datum_type().complexify()?);
2463        t.update_strides_and_len();
2464        Ok(t)
2465    }
2466}
2467
2468#[cfg(feature = "complex")]
2469pub fn reinterpret_complex_as_inner_dim(mut t: Tensor) -> TractResult<Tensor> {
2470    unsafe {
2471        t.shape.push(2);
2472        t.set_datum_type(t.datum_type().decomplexify()?);
2473        t.update_strides_and_len();
2474        Ok(t)
2475    }
2476}
2477
2478pub fn clip_range_bounds(len: usize, range: impl std::ops::RangeBounds<usize>) -> Range<usize> {
2479    use std::ops::Bound;
2480    let start = match range.start_bound() {
2481        Bound::Included(ix) => *ix,
2482        Bound::Excluded(ix) => ix + 1,
2483        Bound::Unbounded => 0,
2484    };
2485    let end = match range.end_bound() {
2486        Bound::Included(ix) => *ix + 1,
2487        Bound::Excluded(ix) => *ix,
2488        Bound::Unbounded => len,
2489    };
2490    start..end
2491}
2492
2493pub fn natural_strides(shape: &[usize]) -> TVec<isize> {
2494    let mut strides = tvec!();
2495    compute_natural_stride_to(&mut strides, shape);
2496    strides
2497}
2498
2499fn compute_natural_stride_to(strides: &mut TVec<isize>, shape: &[usize]) {
2500    match shape.len() {
2501        0 => (),
2502        1 => strides.push(1),
2503        2 => strides.extend_from_slice(&[shape[1] as isize, 1]),
2504        3 => strides.extend_from_slice(&[(shape[1] * shape[2]) as isize, shape[2] as _, 1]),
2505        4 => strides.extend_from_slice(&[
2506            (shape[1] * shape[2] * shape[3]) as isize,
2507            (shape[2] * shape[3]) as _,
2508            shape[3] as _,
2509            1,
2510        ]),
2511        _ => {
2512            strides.push(1);
2513            for dim in shape.as_ref().iter().skip(1).rev() {
2514                let previous = *strides.last().unwrap();
2515                strides.push(previous * *dim as isize)
2516            }
2517            strides.reverse();
2518        }
2519    }
2520}
2521
2522impl<D: ::ndarray::Dimension, T: Datum> From<Array<T, D>> for Tensor {
2523    fn from(it: Array<T, D>) -> Tensor {
2524        Tensor::from_datum(it.into_dyn())
2525    }
2526}
2527
2528/// Convenient conversion to Tensor.
2529pub trait IntoTensor: Sized {
2530    /// Convert Self to a Tensor.
2531    ///
2532    /// May perform a copy
2533    fn into_tensor(self) -> Tensor;
2534}
2535
2536/// Convenient conversion to Arc<Tensor>.
2537pub trait IntoArcTensor: Sized {
2538    /// Convert Self to a Arc<Tensor>.
2539    ///
2540    /// May perform a copy
2541    fn into_arc_tensor(self) -> Arc<Tensor>;
2542}
2543
2544impl<D: ::ndarray::Dimension, T: Datum> IntoTensor for Array<T, D> {
2545    fn into_tensor(self) -> Tensor {
2546        Tensor::from(self)
2547    }
2548}
2549
2550impl<D: ::ndarray::Dimension, T: Datum> IntoArcTensor for Array<T, D> {
2551    fn into_arc_tensor(self) -> Arc<Tensor> {
2552        Arc::new(Tensor::from(self))
2553    }
2554}
2555
2556impl IntoTensor for Tensor {
2557    fn into_tensor(self) -> Tensor {
2558        self
2559    }
2560}
2561
2562impl IntoTensor for Arc<Tensor> {
2563    fn into_tensor(self) -> Tensor {
2564        Arc::try_unwrap(self).unwrap_or_else(|t| (*t).clone())
2565    }
2566}
2567
2568impl IntoArcTensor for Tensor {
2569    fn into_arc_tensor(self) -> Arc<Tensor> {
2570        Arc::new(self)
2571    }
2572}
2573
2574impl IntoArcTensor for Arc<Tensor> {
2575    fn into_arc_tensor(self) -> Arc<Tensor> {
2576        self
2577    }
2578}
2579
2580#[cfg(test)]
2581mod tests {
2582    use crate::dim::SymbolScope;
2583    use crate::prelude::tensor1;
2584
2585    use super::*;
2586    use litteral::tensor0;
2587    use proptest::collection::vec;
2588    use proptest::prelude::*;
2589
2590    // Regression for sonos/tract#2390: from_raw must reject a content length that
2591    // does not match the declared shape rather than panicking in copy_from_slice.
2592    #[test]
2593    fn from_raw_rejects_length_mismatch() {
2594        // shape [2, 3] of f32 needs 24 bytes; supply 12.
2595        let err = unsafe { Tensor::from_raw_dt(f32::datum_type(), &[2, 3], &[0u8; 12]) }
2596            .expect_err("from_raw must reject a short content buffer, not panic");
2597        assert!(err.to_string().contains("does not match shape"), "unexpected error: {err}");
2598        // Too-long content is rejected as well.
2599        assert!(unsafe { Tensor::from_raw_dt(f32::datum_type(), &[2, 3], &[0u8; 32]) }.is_err());
2600        // Exact match still succeeds.
2601        assert!(unsafe { Tensor::from_raw_dt(f32::datum_type(), &[2, 3], &[0u8; 24]) }.is_ok());
2602    }
2603
2604    #[derive(Debug)]
2605    struct PermuteAxisProblem {
2606        shape: Vec<usize>,
2607        permutation: Vec<usize>,
2608    }
2609
2610    impl Arbitrary for PermuteAxisProblem {
2611        type Strategy = BoxedStrategy<PermuteAxisProblem>;
2612        type Parameters = ();
2613
2614        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
2615            (0..8usize)
2616                .prop_flat_map(|rank| {
2617                    let permute: Vec<usize> = (0..rank).collect();
2618                    (proptest::collection::vec(1..5usize, rank), Just(permute).prop_shuffle())
2619                })
2620                .prop_map(|(shape, permutation)| PermuteAxisProblem { shape, permutation })
2621                .boxed()
2622        }
2623    }
2624
2625    impl PermuteAxisProblem {
2626        fn input(&self) -> ArrayD<i32> {
2627            let mut i = 0;
2628            ArrayD::from_shape_simple_fn(&*self.shape, || {
2629                i += 1;
2630                i
2631            })
2632            .permuted_axes(&*self.permutation)
2633        }
2634
2635        fn reference(&self) -> Tensor {
2636            let values: Vec<i32> = self.input().iter().copied().collect();
2637            let shape = self.permutation.iter().map(|ix| self.shape[*ix]).collect::<TVec<usize>>();
2638            super::litteral::tensor1(&values).into_shape(&shape).unwrap()
2639        }
2640
2641        fn tract(&self) -> Tensor {
2642            Tensor::from(self.input())
2643        }
2644
2645        fn check(&self) -> proptest::test_runner::TestCaseResult {
2646            prop_assert_eq!(self.tract(), self.reference());
2647            Ok(())
2648        }
2649    }
2650
2651    proptest::proptest! {
2652        #[test]
2653        fn prop(pb: PermuteAxisProblem) {
2654            pb.check().unwrap();
2655        }
2656    }
2657
2658    #[test]
2659    fn t_1_2() {
2660        PermuteAxisProblem { shape: vec![2, 1], permutation: vec![1, 0] }.check().unwrap();
2661    }
2662
2663    #[test]
2664    fn t_2_2() {
2665        PermuteAxisProblem { shape: vec![2, 2], permutation: vec![1, 0] }.check().unwrap();
2666    }
2667
2668    fn for_each_shape(rank: usize, max_dim: usize, mut f: impl FnMut(&[usize])) {
2669        let mut shape = vec![1usize; rank];
2670        loop {
2671            f(&shape);
2672            let mut i = rank;
2673            loop {
2674                if i == 0 {
2675                    return;
2676                }
2677                i -= 1;
2678                shape[i] += 1;
2679                if shape[i] <= max_dim {
2680                    break;
2681                }
2682                shape[i] = 1;
2683            }
2684        }
2685    }
2686
2687    fn check_moved_axis<T: Datum + num_traits::NumCast + Copy>(
2688        shape: &[usize],
2689        from: usize,
2690        to: usize,
2691    ) {
2692        let n: usize = shape.iter().product();
2693        let data: Vec<T> = (0..n).map(|i| T::from(i % 251).unwrap()).collect();
2694        let t = Tensor::from_shape::<T>(shape, &data).unwrap();
2695        let mut permutation: Vec<usize> = (0..shape.len()).collect();
2696        permutation.remove(from);
2697        permutation.insert(to, from);
2698        let reference = unsafe {
2699            t.clone().into_array_unchecked::<T>().permuted_axes(&*permutation).into_tensor()
2700        };
2701        let got = t.moved_axis(from, to).unwrap();
2702        assert_eq!(got.shape(), reference.shape(), "{shape:?} {from}->{to}");
2703        assert_eq!(got.as_bytes(), reference.as_bytes(), "{shape:?} {from}->{to}");
2704    }
2705
2706    #[test]
2707    fn moved_axis_matches_permuted_axes() {
2708        for (rank, max_dim) in [(2, 7), (3, 7), (4, 6), (5, 4)] {
2709            for_each_shape(rank, max_dim, |shape| {
2710                for from in 0..rank {
2711                    for to in 0..rank {
2712                        check_moved_axis::<u8>(shape, from, to);
2713                        check_moved_axis::<f16>(shape, from, to);
2714                        check_moved_axis::<f32>(shape, from, to);
2715                        check_moved_axis::<f64>(shape, from, to);
2716                    }
2717                }
2718            });
2719        }
2720    }
2721
2722    #[test]
2723    fn moved_axis_matches_permuted_axes_across_tiles() {
2724        // Past the 16- and 64-cell tile edges, and onto the page-aligned destination-stride rows.
2725        for shape in [
2726            vec![1030usize, 17],
2727            vec![1024, 5],
2728            vec![4096, 3],
2729            vec![2048, 64],
2730            vec![3, 1024, 7],
2731            vec![2, 70, 33],
2732            vec![1, 64, 100, 96],
2733        ] {
2734            for from in 0..shape.len() {
2735                for to in 0..shape.len() {
2736                    check_moved_axis::<u8>(&shape, from, to);
2737                    check_moved_axis::<f16>(&shape, from, to);
2738                    check_moved_axis::<f32>(&shape, from, to);
2739                    check_moved_axis::<f64>(&shape, from, to);
2740                }
2741            }
2742        }
2743    }
2744
2745    #[test]
2746    fn moved_axis_falls_back_on_non_contiguous() {
2747        let mut t =
2748            Tensor::from_shape::<f32>(&[4, 3], &(0..12).map(|i| i as f32).collect_vec()).unwrap();
2749        unsafe { t.set_geometry_unchecked(&[3, 4], &[1, 4]) };
2750        let got = t.moved_axis(0, 1).unwrap();
2751        let reference = unsafe {
2752            t.clone().into_array_unchecked::<f32>().permuted_axes(&[1, 0][..]).into_tensor()
2753        };
2754        assert_eq!(got.shape(), reference.shape());
2755        assert_eq!(got.as_bytes(), reference.as_bytes());
2756    }
2757
2758    #[test]
2759    fn permute_axes_scalar() {
2760        let t = tensor0(1f32);
2761        assert_eq!(t.clone().permute_axes(&[]).unwrap(), t);
2762    }
2763
2764    #[derive(Debug)]
2765    struct BroadcastVecToShape {
2766        vec: Vec<f32>,
2767        axis: usize,
2768        shape: TVec<usize>,
2769    }
2770
2771    impl BroadcastVecToShape {
2772        fn check(&self) -> proptest::test_runner::TestCaseResult {
2773            let input = tensor1(&self.vec);
2774            let mut intermediate = tvec![1usize; self.shape.len()];
2775            intermediate[self.axis] = self.vec.len();
2776            let reference = input
2777                .clone()
2778                .into_shape(&intermediate)
2779                .unwrap()
2780                .broadcast_to_shape(&self.shape)
2781                .unwrap();
2782            prop_assert_eq!(
2783                reference,
2784                input.broadcast_vector_to_shape(&self.shape, self.axis).unwrap()
2785            );
2786            Ok(())
2787        }
2788    }
2789
2790    impl Arbitrary for BroadcastVecToShape {
2791        type Strategy = BoxedStrategy<BroadcastVecToShape>;
2792        type Parameters = ();
2793
2794        fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
2795            vec(0usize..5, 0usize..4)
2796                .prop_flat_map(|shape| {
2797                    (vec(-10f32..10f32, 0usize..5), Just(shape.clone()), 0..shape.len() + 1)
2798                })
2799                .prop_map(|(vec, mut shape, axis)| {
2800                    shape.insert(axis, vec.len());
2801                    BroadcastVecToShape { vec, shape: shape.into(), axis }
2802                })
2803                .boxed()
2804        }
2805    }
2806
2807    proptest::proptest! {
2808        #[test]
2809        fn broadcast_vector_to_shape_prop(pb: BroadcastVecToShape) {
2810            pb.check().unwrap()
2811        }
2812    }
2813
2814    #[test]
2815    #[cfg(feature = "complex")]
2816    fn test_reinterpret_inner_dim_as_complex() -> TractResult<()> {
2817        let input = crate::internal::tensor2(&[[1.0f32, 2.0], [3.0, 4.0], [5.0, 6.0]]);
2818        let cplx_input = reinterpret_inner_dim_as_complex(input)?;
2819        let expected = crate::internal::tensor1(&[
2820            Complex::new(1.0f32, 2.0),
2821            Complex::new(3.0, 4.0),
2822            Complex::new(5.0, 6.0),
2823        ]);
2824        assert_eq!(expected, cplx_input);
2825        Ok(())
2826    }
2827
2828    #[test]
2829    #[cfg(feature = "complex")]
2830    fn test_reinterpret_inner_dim_as_complex_2() -> TractResult<()> {
2831        let input =
2832            crate::internal::tensor3(&[[[1i32, 2], [1, 2]], [[3, 4], [3, 4]], [[5, 6], [5, 6]]]);
2833        let cplx_input = reinterpret_inner_dim_as_complex(input)?;
2834        let expected = crate::internal::tensor2(&[
2835            [Complex::new(1i32, 2), Complex::new(1, 2)],
2836            [Complex::new(3, 4), Complex::new(3, 4)],
2837            [Complex::new(5, 6), Complex::new(5, 6)],
2838        ]);
2839        assert_eq!(expected, cplx_input);
2840        Ok(())
2841    }
2842
2843    #[test]
2844    fn clone_tdim_tensor() {
2845        let symbols = SymbolScope::default();
2846        let a = symbols.sym("a");
2847        let t = tensor0(TDim::from(a));
2848        let _ = t.clone();
2849    }
2850
2851    #[test]
2852    fn ulp_approximation_accepts_within_bound() -> TractResult<()> {
2853        let a = tensor1(&[1.0f32, 2.0, 3.0]);
2854        let b = tensor1(&[
2855            f32::from_bits(1.0f32.to_bits() + 1),
2856            2.0,
2857            f32::from_bits(3.0f32.to_bits() + 2),
2858        ]);
2859        a.close_enough(&b, Approximation::Ulp(2))?;
2860        assert!(a.close_enough(&b, Approximation::Ulp(1)).is_err());
2861        assert_eq!(a.max_ulp_distance(&b)?, (2, Some(2)));
2862        Ok(())
2863    }
2864
2865    #[test]
2866    fn ulp_approximation_uses_the_tensor_own_float_type() -> TractResult<()> {
2867        // One f16 rounding step is ~8192 f32 steps. Measuring in f32 would make an
2868        // adjacent-f16 pair look wildly off, so the comparison must stay in f16.
2869        let one = f16::from_f32(1.0);
2870        let a = tensor1(&[one]);
2871        let b = tensor1(&[f16::from_bits(one.to_bits() + 1)]);
2872        assert_eq!(a.ulp_comparison_dt(), DatumType::F16);
2873        assert_eq!(a.max_ulp_distance(&b)?, (1, Some(0)));
2874        a.close_enough(&b, Approximation::Ulp(1))?;
2875        Ok(())
2876    }
2877
2878    #[test]
2879    fn ulp_approximation_is_scale_free() -> TractResult<()> {
2880        // The same relative error at wildly different magnitudes reads the same,
2881        // which a shared atol cannot do.
2882        let a = tensor1(&[1e-30f32, 1e30]);
2883        let b = tensor1(&[
2884            f32::from_bits(1e-30f32.to_bits() + 1),
2885            f32::from_bits(1e30f32.to_bits() + 1),
2886        ]);
2887        a.close_enough(&b, Approximation::Ulp(1))?;
2888        Ok(())
2889    }
2890
2891    #[test]
2892    fn ulp_approximation_rejects_shape_mismatch() {
2893        let a = tensor1(&[1.0f32, 2.0]);
2894        let b = tensor1(&[1.0f32]);
2895        assert!(a.close_enough(&b, Approximation::Ulp(1000)).is_err());
2896    }
2897
2898    // stack_tensors picks between three copy strategies by block size; they must
2899    // all agree with plain index arithmetic. Sizes 1/2/4/8 cover the typed-copy
2900    // dispatch, and a trailing axis of 1 gives the one-datum blocks that
2901    // FastEnhancer's [1, 256, 1, 2] and DTLN's [1, 2, 128, 2] concats produce.
2902    fn stack_reference<T: Datum + Copy + num_traits::Zero>(
2903        axis: usize,
2904        tensors: &[Tensor],
2905    ) -> Tensor {
2906        let mut shape: TVec<usize> = tensors[0].shape().into();
2907        shape[axis] = tensors.iter().map(|t| t.shape()[axis]).sum();
2908        let mut out = Tensor::zero::<T>(&shape).unwrap();
2909        let outer: usize = shape[..axis].iter().product();
2910        let inner: usize = shape[axis + 1..].iter().product();
2911        let mid = shape[axis];
2912        let ov = unsafe { out.as_slice_mut_unchecked::<T>() };
2913        let mut base = 0;
2914        for t in tensors {
2915            let m = t.shape()[axis];
2916            let tv = unsafe { t.as_slice_unchecked::<T>() };
2917            for o in 0..outer {
2918                for j in 0..m {
2919                    for i in 0..inner {
2920                        ov[(o * mid + base + j) * inner + i] = tv[(o * m + j) * inner + i];
2921                    }
2922                }
2923            }
2924            base += m;
2925        }
2926        out
2927    }
2928
2929    fn ramp<T: Datum + Copy + From<u8>>(shape: &[usize], seed: u8) -> Tensor {
2930        let n: usize = shape.iter().product();
2931        let v: Vec<T> = (0..n).map(|i| T::from(seed.wrapping_add(i as u8))).collect();
2932        Tensor::from_shape(shape, &v).unwrap()
2933    }
2934
2935    macro_rules! stack_agrees_for {
2936        ($name:ident, $t:ty) => {
2937            #[test]
2938            fn $name() {
2939                for shape in [
2940                    tvec!(1usize, 256, 1, 1),
2941                    tvec!(1usize, 2, 128, 1),
2942                    tvec!(1usize, 35, 35, 8),
2943                    tvec!(4usize, 3),
2944                    tvec!(7usize),
2945                ] {
2946                    for axis in 0..shape.len() {
2947                        let a: Tensor = ramp::<$t>(&shape, 1);
2948                        let b: Tensor = ramp::<$t>(&shape, 100);
2949                        let c: Tensor = ramp::<$t>(&shape, 200);
2950                        for n in 1..=3 {
2951                            let ins = [a.clone(), b.clone(), c.clone()][..n].to_vec();
2952                            let got = Tensor::stack_tensors(axis, &ins).unwrap();
2953                            let want = stack_reference::<$t>(axis, &ins);
2954                            assert_eq!(got, want, "shape {shape:?} axis {axis} n {n}");
2955                        }
2956                    }
2957                }
2958            }
2959        };
2960    }
2961
2962    stack_agrees_for!(stack_tensors_agrees_u8, u8);
2963    stack_agrees_for!(stack_tensors_agrees_u16, u16);
2964    stack_agrees_for!(stack_tensors_agrees_u32, u32);
2965    stack_agrees_for!(stack_tensors_agrees_u64, u64);
2966
2967    // A zero extent before the concatenated axis makes `outer` zero; the block
2968    // path divides by it, so it must not be taken.
2969    #[test]
2970    fn stack_tensors_tolerates_a_zero_outer_extent() {
2971        let a = Tensor::zero::<f32>(&[0, 2, 3]).unwrap();
2972        let stacked = Tensor::stack_tensors(2, &[a.clone(), a.clone()]).unwrap();
2973        assert_eq!(stacked.shape(), &[0, 2, 6]);
2974    }
2975
2976    // assign_slice copies one contiguous run per coordinate of the axes before
2977    // `axis`; the runs must agree with plain index arithmetic for every axis,
2978    // including the trailing one where each run is a single datum.
2979    fn assign_slice_reference<T: Datum + Copy>(
2980        dst: &Tensor,
2981        dst_range: Range<usize>,
2982        src: &Tensor,
2983        src_range: Range<usize>,
2984        axis: usize,
2985    ) -> Tensor {
2986        let mut out = dst.clone();
2987        let outer: usize = dst.shape()[..axis].iter().product();
2988        let inner: usize = dst.shape()[axis + 1..].iter().product();
2989        let dst_mid = dst.shape()[axis];
2990        let src_mid = src.shape()[axis];
2991        let sv = unsafe { src.as_slice_unchecked::<T>() };
2992        let ov = unsafe { out.as_slice_mut_unchecked::<T>() };
2993        for o in 0..outer {
2994            for j in 0..dst_range.len() {
2995                for i in 0..inner {
2996                    ov[(o * dst_mid + dst_range.start + j) * inner + i] =
2997                        sv[(o * src_mid + src_range.start + j) * inner + i];
2998                }
2999            }
3000        }
3001        out
3002    }
3003
3004    macro_rules! assign_slice_agrees_for {
3005        ($name:ident, $t:ty) => {
3006            #[test]
3007            fn $name() {
3008                for (shape, axis, dst_mid, src_mid, dst_start, len, src_start) in [
3009                    (tvec!(1usize, 56, 24), 2, 24, 8, 16, 8, 0),
3010                    (tvec!(1usize, 56, 24), 2, 24, 24, 0, 16, 8),
3011                    (tvec!(1usize, 32, 4, 128), 3, 128, 128, 0, 64, 64),
3012                    (tvec!(1usize, 8, 16, 64), 2, 16, 1, 3, 1, 0),
3013                    (tvec!(3usize, 5), 0, 3, 7, 1, 2, 4),
3014                    (tvec!(4usize, 3), 1, 3, 3, 0, 3, 0),
3015                    (tvec!(7usize), 0, 7, 7, 2, 0, 5),
3016                ] {
3017                    let mut dst_shape = shape.clone();
3018                    dst_shape[axis] = dst_mid;
3019                    let mut src_shape = shape.clone();
3020                    src_shape[axis] = src_mid;
3021                    let mut got: Tensor = ramp::<$t>(&dst_shape, 1);
3022                    let src: Tensor = ramp::<$t>(&src_shape, 100);
3023                    let want = assign_slice_reference::<$t>(
3024                        &got,
3025                        dst_start..dst_start + len,
3026                        &src,
3027                        src_start..src_start + len,
3028                        axis,
3029                    );
3030                    got.assign_slice(
3031                        dst_start..dst_start + len,
3032                        &src,
3033                        src_start..src_start + len,
3034                        axis,
3035                    )
3036                    .unwrap();
3037                    assert_eq!(got, want, "shape {dst_shape:?} axis {axis}");
3038                }
3039            }
3040        };
3041    }
3042
3043    assign_slice_agrees_for!(assign_slice_agrees_u8, u8);
3044    assign_slice_agrees_for!(assign_slice_agrees_u16, u16);
3045    assign_slice_agrees_for!(assign_slice_agrees_u32, u32);
3046    assign_slice_agrees_for!(assign_slice_agrees_u64, u64);
3047
3048    // The prefixed assign copies the same runs inside one sub-tensor of each
3049    // side, and the prefixed axes are free to differ in extent.
3050    macro_rules! assign_slice_at_prefix_agrees_for {
3051        ($name:ident, $t:ty) => {
3052            #[test]
3053            fn $name() {
3054                for (shape, prefix, src_lead, src_prefix, axis, start, len, src_start) in [
3055                    (tvec!(3usize, 5, 7), tvec!(2usize), 4, tvec!(3usize), 2, 3, 4, 0),
3056                    (tvec!(3usize, 5, 7), tvec!(0usize), 1, tvec!(0usize), 1, 1, 3, 2),
3057                    (tvec!(2usize, 4, 8, 3), tvec!(1usize, 2), 2, tvec!(0usize, 1), 3, 0, 3, 0),
3058                    (tvec!(4usize, 6), tvec!(), 4, tvec!(), 1, 2, 4, 2),
3059                ] {
3060                    let mut src_shape = shape.clone();
3061                    src_shape[0] = src_lead;
3062                    let mut got: Tensor = ramp::<$t>(&shape, 1);
3063                    let src: Tensor = ramp::<$t>(&src_shape, 100);
3064                    // A prefixed assign is the same assign between the two
3065                    // sub-tensors, which a slice materializes.
3066                    let mut want_sub = sub_tensor(&got, &prefix);
3067                    want_sub
3068                        .assign_slice(
3069                            start..start + len,
3070                            &sub_tensor(&src, &src_prefix),
3071                            src_start..src_start + len,
3072                            axis - prefix.len(),
3073                        )
3074                        .unwrap();
3075                    got.assign_slice_at_prefix(
3076                        &prefix,
3077                        start..start + len,
3078                        &src,
3079                        &src_prefix,
3080                        src_start..src_start + len,
3081                        axis,
3082                    )
3083                    .unwrap();
3084                    assert_eq!(
3085                        sub_tensor(&got, &prefix),
3086                        want_sub,
3087                        "shape {shape:?} prefix {prefix:?} axis {axis}"
3088                    );
3089                }
3090            }
3091        };
3092    }
3093
3094    fn sub_tensor(t: &Tensor, prefix: &[usize]) -> Tensor {
3095        let mut sub = t.clone();
3096        for ix in prefix {
3097            sub = sub.slice(0, *ix, ix + 1).unwrap();
3098            sub.remove_axis(0).unwrap();
3099        }
3100        sub
3101    }
3102
3103    assign_slice_at_prefix_agrees_for!(assign_slice_at_prefix_agrees_u8, u8);
3104    assign_slice_at_prefix_agrees_for!(assign_slice_at_prefix_agrees_u16, u16);
3105    assign_slice_at_prefix_agrees_for!(assign_slice_at_prefix_agrees_u32, u32);
3106    assign_slice_at_prefix_agrees_for!(assign_slice_at_prefix_agrees_u64, u64);
3107
3108    // fill_slice writes one contiguous run per coordinate of the axes between
3109    // the prefix and `axis`; the runs must agree with plain index arithmetic,
3110    // including on the trailing axis where each run is a single datum.
3111    fn fill_slice_reference<T: Datum + Copy>(
3112        data: &Tensor,
3113        prefix: &[usize],
3114        range: Range<usize>,
3115        value: T,
3116        axis: usize,
3117    ) -> Tensor {
3118        let mut out = data.clone();
3119        let shape = data.shape().to_vec();
3120        let inner: usize = shape[axis + 1..].iter().product();
3121        let mid = shape[axis];
3122        let outer: usize = shape[prefix.len()..axis].iter().product();
3123        let at: usize = izip!(prefix, data.strides()).map(|(ix, s)| ix * *s as usize).sum();
3124        let ov = unsafe { out.as_slice_mut_unchecked::<T>() };
3125        for o in 0..outer {
3126            for j in range.clone() {
3127                for i in 0..inner {
3128                    ov[at + (o * mid + j) * inner + i] = value;
3129                }
3130            }
3131        }
3132        out
3133    }
3134
3135    macro_rules! fill_slice_agrees_for {
3136        ($name:ident, $t:ty) => {
3137            #[test]
3138            fn $name() {
3139                for (shape, prefix, axis, start, len) in [
3140                    (tvec!(1usize, 56, 24), tvec!(), 2, 16, 8),
3141                    (tvec!(3usize, 5, 7), tvec!(), 1, 1, 3),
3142                    (tvec!(3usize, 5, 7), tvec!(2usize), 2, 3, 4),
3143                    (tvec!(3usize, 5, 7), tvec!(1usize, 4), 2, 0, 7),
3144                    (tvec!(4usize, 3), tvec!(), 0, 1, 2),
3145                    (tvec!(2usize, 8, 16, 64), tvec!(1usize), 2, 3, 1),
3146                    (tvec!(7usize), tvec!(), 0, 2, 0),
3147                ] {
3148                    let value: $t = 42 as $t;
3149                    let mut got: Tensor = ramp::<$t>(&shape, 1);
3150                    let want =
3151                        fill_slice_reference::<$t>(&got, &prefix, start..start + len, value, axis);
3152                    got.fill_slice_at_prefix(&prefix, start..start + len, &tensor0(value), axis)
3153                        .unwrap();
3154                    assert_eq!(got, want, "shape {shape:?} prefix {prefix:?} axis {axis}");
3155                }
3156            }
3157        };
3158    }
3159
3160    fill_slice_agrees_for!(fill_slice_agrees_u8, u8);
3161    fill_slice_agrees_for!(fill_slice_agrees_u16, u16);
3162    fill_slice_agrees_for!(fill_slice_agrees_u32, u32);
3163    fill_slice_agrees_for!(fill_slice_agrees_u64, u64);
3164
3165    #[test]
3166    fn fill_slice_carries_non_copy_data() {
3167        let strings = |v: [&str; 6]| {
3168            ndarray::Array2::from_shape_vec((2, 3), v.iter().map(|s| s.to_string()).collect())
3169                .unwrap()
3170                .into_tensor()
3171        };
3172        let mut data = strings(["a", "b", "c", "d", "e", "f"]);
3173        data.fill_slice(1..3, &tensor0("x".to_string()), 1).unwrap();
3174        assert_eq!(data, strings(["a", "x", "x", "d", "x", "x"]));
3175    }
3176
3177    #[test]
3178    fn assign_slice_carries_non_copy_data() {
3179        let strings = |v: [&str; 6]| {
3180            ndarray::Array2::from_shape_vec((2, 3), v.iter().map(|s| s.to_string()).collect())
3181                .unwrap()
3182                .into_tensor()
3183        };
3184        let mut dst = strings(["a", "b", "c", "d", "e", "f"]);
3185        let src = ndarray::Array2::from_shape_vec((2, 1), vec!["x".to_string(), "y".to_string()])
3186            .unwrap()
3187            .into_tensor();
3188        dst.assign_slice(1..2, &src, 0..1, 1).unwrap();
3189        assert_eq!(dst, strings(["a", "x", "c", "d", "y", "f"]));
3190    }
3191
3192    // The run-based broadcast must agree with the ndarray view it replaced, over
3193    // leading, middle and trailing broadcast axes and over ranks that grow.
3194    #[test]
3195    fn broadcast_to_shape_agrees_with_the_view() {
3196        for (src, dst) in [
3197            (tvec!(1usize, 8, 1, 7, 4), tvec!(1usize, 8, 4, 7, 4)),
3198            (tvec!(1usize, 1, 1, 7), tvec!(2usize, 3, 5, 7)),
3199            (tvec!(4usize), tvec!(2usize, 3, 5, 4)),
3200            (tvec!(1usize, 5, 3), tvec!(6usize, 5, 3)),
3201            (tvec!(2usize, 3), tvec!(2usize, 3)),
3202            (tvec!(1usize), tvec!(3usize, 1, 2)),
3203            (tvec!(3usize, 1), tvec!(3usize, 0)),
3204            // Innermost-axis broadcasts take the repeated-cell path: one contiguous run of
3205            // one value per cell, and cells that differ only on the axes below the walk.
3206            (tvec!(3usize, 1), tvec!(3usize, 5)),
3207            (tvec!(2usize, 1, 1), tvec!(2usize, 4, 3)),
3208            (tvec!(1usize, 16, 1, 1), tvec!(1usize, 16, 4, 4)),
3209            (tvec!(1usize, 1), tvec!(2usize, 3, 4)),
3210            (tvec!(1024usize, 1, 1), tvec!(1024usize, 4, 1)),
3211        ] {
3212            for dt in [f32::datum_type(), u8::datum_type(), i32::datum_type()] {
3213                let t = Tensor::zero_dt(dt, &src).unwrap().cast_to_dt(dt).unwrap().into_owned();
3214                let got = t.broadcast_to_shape(&dst).unwrap();
3215                let want = dispatch_datum!(Tensor::broadcast_to_shape_t(dt)(&t, &dst)).unwrap();
3216                assert_eq!(got.shape(), &*dst, "{src:?} -> {dst:?}");
3217                assert_eq!(got, want, "{src:?} -> {dst:?} {dt:?}");
3218            }
3219        }
3220    }
3221
3222    /// The repeated-cell path is only correct if every cell lands on the source element its
3223    /// coordinates name, so check it against the reference on values rather than on zeros.
3224    #[test]
3225    fn broadcast_to_shape_repeats_innermost_cells_with_the_right_value() {
3226        for (src, dst) in [
3227            (tvec!(3usize, 1), tvec!(3usize, 5)),
3228            (tvec!(2usize, 1, 1), tvec!(2usize, 4, 3)),
3229            (tvec!(1usize, 16, 1, 1), tvec!(1usize, 16, 4, 4)),
3230            (tvec!(1usize, 1), tvec!(2usize, 3, 4)),
3231            (tvec!(1024usize, 1, 1), tvec!(1024usize, 4, 1)),
3232            (tvec!(4usize, 1, 7), tvec!(4usize, 3, 7)),
3233            (tvec!(2usize, 3, 1, 1), tvec!(2usize, 3, 5, 6)),
3234        ] {
3235            let t = ramp::<u32>(&src, 0);
3236            let got = t.broadcast_to_shape(&dst).unwrap();
3237            let want = Tensor::broadcast_to_shape_t::<u32>(&t, &dst).unwrap();
3238            assert_eq!(got, want, "{src:?} -> {dst:?}");
3239        }
3240    }
3241
3242    #[test]
3243    fn broadcast_to_shape_carries_values_and_rejects_mismatches() {
3244        let t = tensor2(&[[1u8, 2, 3], [4, 5, 6]]);
3245        let got = t.clone().into_shape(&[2, 1, 3]).unwrap().broadcast_to_shape(&[2, 2, 3]).unwrap();
3246        assert_eq!(got, tensor3(&[[[1u8, 2, 3], [1, 2, 3]], [[4, 5, 6], [4, 5, 6]]]));
3247        assert!(t.broadcast_to_shape(&[3, 3]).is_err());
3248        assert!(t.broadcast_to_shape(&[3]).is_err());
3249    }
3250
3251    #[test]
3252    fn slice_keeps_the_datum_type_and_the_values() {
3253        let t = ramp::<u32>(&tvec!(2usize, 3, 4), 0);
3254        let got = t.slice(1, 1, 3).unwrap();
3255        let mut want = Tensor::zero::<u32>(&[2, 2, 4]).unwrap();
3256        want.assign_slice(0..2, &t, 1..3, 1).unwrap();
3257        assert_eq!(got, want);
3258        let quantized = Tensor::zero_dt(
3259            i8::datum_type().quantize(QParams::ZpScale { zero_point: 3, scale: 0.5 }),
3260            &[2, 4],
3261        )
3262        .unwrap();
3263        assert_eq!(quantized.slice(1, 0, 2).unwrap().datum_type(), quantized.datum_type());
3264    }
3265
3266    #[test]
3267    fn f32_f16_casts_round_like_scalar_conversion() {
3268        let f32s: Vec<f32> = (0..=u32::MAX).step_by(65521).map(f32::from_bits).collect();
3269        let to_f16 = tensor1(&f32s).cast_to::<f16>().unwrap().into_owned();
3270        for (s, d) in f32s.iter().zip(to_f16.try_as_plain_ram().unwrap().as_slice::<f16>().unwrap())
3271        {
3272            assert_eq!(f16::from_f32(*s).to_bits(), d.to_bits(), "{s:e}");
3273        }
3274        let f16s: Vec<f16> = (0..=u16::MAX).map(f16::from_bits).collect();
3275        let to_f32 = tensor1(&f16s).cast_to::<f32>().unwrap().into_owned();
3276        for (s, d) in f16s.iter().zip(to_f32.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap())
3277        {
3278            assert_eq!(s.to_f32().to_bits(), d.to_bits(), "{s:e}");
3279        }
3280    }
3281
3282    #[test]
3283    fn ulp_bounds_are_distinguished_by_equality() {
3284        assert_eq!(Approximation::Ulp(1), Approximation::Ulp(1));
3285        assert_ne!(Approximation::Ulp(1), Approximation::Ulp(2));
3286    }
3287
3288    /// Storage that keeps its bytes "elsewhere" until asked, standing in for a
3289    /// device-backed one so the seam can be tested without a GPU.
3290    #[derive(Debug)]
3291    struct LateStorage {
3292        elsewhere: Vec<u8>,
3293        here: std::sync::OnceLock<PlainStorage>,
3294        materializations: std::sync::atomic::AtomicUsize,
3295    }
3296
3297    impl LateStorage {
3298        fn new(bytes: &[u8]) -> LateStorage {
3299            LateStorage {
3300                elsewhere: bytes.to_vec(),
3301                here: std::sync::OnceLock::new(),
3302                materializations: std::sync::atomic::AtomicUsize::new(0),
3303            }
3304        }
3305        fn count(t: &Tensor) -> usize {
3306            t.storage_as::<LateStorage>()
3307                .unwrap()
3308                .materializations
3309                .load(std::sync::atomic::Ordering::Relaxed)
3310        }
3311    }
3312
3313    impl PartialEq for LateStorage {
3314        fn eq(&self, other: &Self) -> bool {
3315            self.elsewhere == other.elsewhere
3316        }
3317    }
3318    impl Eq for LateStorage {}
3319
3320    impl std::fmt::Display for LateStorage {
3321        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3322            write!(f, "LateStorage")
3323        }
3324    }
3325
3326    impl TensorStorage for LateStorage {
3327        fn byte_len(&self) -> usize {
3328            self.elsewhere.len()
3329        }
3330        fn is_empty(&self) -> bool {
3331            self.elsewhere.is_empty()
3332        }
3333        fn deep_clone(&self) -> Box<dyn TensorStorage> {
3334            Box::new(LateStorage::new(&self.elsewhere))
3335        }
3336        fn as_plain_ram(&self) -> Option<&PlainStorage> {
3337            self.here.get()
3338        }
3339        fn as_plain_ram_mut(&mut self) -> Option<&mut PlainStorage> {
3340            None
3341        }
3342        fn into_plain_ram(self: Box<Self>) -> Option<PlainStorage> {
3343            let me = *self;
3344            me.materialize_plain_ram().ok()?;
3345            me.here.into_inner()
3346        }
3347        fn dyn_hash(&self, _state: &mut dyn std::hash::Hasher) {}
3348        fn exotic_fact(&self, _shape: &[usize]) -> TractResult<Option<Box<dyn ExoticFact>>> {
3349            Ok(None)
3350        }
3351        fn is_exotic(&self) -> bool {
3352            false
3353        }
3354        fn in_ram(&self) -> bool {
3355            self.here.get().is_some()
3356        }
3357        fn materialize_plain_ram(&self) -> TractResult<&PlainStorage> {
3358            if let Some(here) = self.here.get() {
3359                return Ok(here);
3360            }
3361            self.materializations.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3362            let blob = Blob::from_bytes(&self.elsewhere)?;
3363            Ok(self.here.get_or_init(|| PlainStorage::from(blob)))
3364        }
3365        fn slice(
3366            &self,
3367            dt: DatumType,
3368            shape: &[usize],
3369            axis: usize,
3370            start: usize,
3371            end: usize,
3372        ) -> TractResult<Option<Tensor>> {
3373            // Only the outermost axis is a contiguous byte range here.
3374            if axis != 0 || shape[..axis].iter().product::<usize>() != 1 {
3375                return Ok(None);
3376            }
3377            let row = shape[1..].iter().product::<usize>() * dt.size_of();
3378            let mut sliced: TVec<usize> = shape.into();
3379            sliced[0] = end - start;
3380            Ok(Some(Tensor::from_storage(
3381                dt,
3382                &sliced,
3383                LateStorage::new(&self.elsewhere[start * row..end * row]),
3384            )))
3385        }
3386    }
3387
3388    fn late_tensor(shape: &[usize], values: &[f32]) -> Tensor {
3389        let host = Tensor::from_shape(shape, values).unwrap();
3390        Tensor::from_storage(f32::datum_type(), shape, LateStorage::new(host.as_bytes()))
3391    }
3392
3393    #[test]
3394    fn late_storage_stays_put_until_the_bytes_are_read() {
3395        let t = late_tensor(&[2, 3], &[1f32, 2., 3., 4., 5., 6.]);
3396        // Predicates must not drag the bytes back.
3397        assert!(!t.in_ram());
3398        assert!(t.as_plain_ram().is_none());
3399        assert_eq!(t.datum_type(), f32::datum_type());
3400        assert_eq!(t.shape(), &[2, 3]);
3401        assert_eq!(LateStorage::count(&t), 0);
3402        // Reading them does, once.
3403        assert_eq!(
3404            t.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap(),
3405            &[1f32, 2., 3., 4., 5., 6.]
3406        );
3407        assert_eq!(LateStorage::count(&t), 1);
3408        assert_eq!(t.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap()[0], 1f32);
3409        assert_eq!(LateStorage::count(&t), 1);
3410    }
3411
3412    #[test]
3413    fn late_storage_reads_through_a_view() {
3414        let t = late_tensor(&[2, 3], &[1f32, 2., 3., 4., 5., 6.]);
3415        let row = t.view_at_prefix(&[1]).unwrap();
3416        assert_eq!(row.as_slice::<f32>().unwrap(), &[4f32, 5., 6.]);
3417    }
3418
3419    #[test]
3420    fn late_storage_is_plain_but_not_in_ram_until_asked() {
3421        let t = late_tensor(&[2, 3], &[1f32, 2., 3., 4., 5., 6.]);
3422        assert!(t.is_plain());
3423        assert!(!t.in_ram());
3424        let t = t.into_plain_ram().unwrap();
3425        assert!(t.in_ram());
3426        assert!(t.has_plain_ram_storage());
3427        assert_eq!(
3428            t.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap(),
3429            &[1f32, 2., 3., 4., 5., 6.]
3430        );
3431    }
3432
3433    #[test]
3434    fn late_storage_slices_without_materializing_when_it_can() {
3435        let t = late_tensor(&[2, 3], &[1f32, 2., 3., 4., 5., 6.]);
3436        let row = t.slice(0, 1, 2).unwrap();
3437        assert_eq!(LateStorage::count(&t), 0);
3438        assert!(row.storage_as::<LateStorage>().is_some());
3439        assert_eq!(row.shape(), &[1, 3]);
3440        assert_eq!(row.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap(), &[4f32, 5., 6.]);
3441    }
3442
3443    #[test]
3444    fn late_storage_falls_back_to_a_copy_on_a_gappy_slice() {
3445        let t = late_tensor(&[2, 3], &[1f32, 2., 3., 4., 5., 6.]);
3446        let col = t.slice(1, 1, 3).unwrap();
3447        // Storage refused, so the generic path copied: material, and correct.
3448        assert!(col.in_ram());
3449        assert_eq!(col.shape(), &[2, 2]);
3450        assert_eq!(col.try_as_plain_ram().unwrap().as_slice::<f32>().unwrap(), &[2f32, 3., 5., 6.]);
3451        assert_eq!(LateStorage::count(&t), 1);
3452    }
3453}