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