Tensor

Struct Tensor 

Source
pub struct Tensor<T, const N: usize, A: TensorAllocator> {
    pub storage: TensorStorage<T, A>,
    pub shape: [usize; N],
    pub strides: [usize; N],
}
Expand description

A data structure to represent a multi-dimensional tensor.

NOTE: Internally, the data is stored as an arrow::ScalarBuffer which represents a contiguous memory region that can be shared with other buffers and across thread boundaries.

§Attributes

  • storage - The storage of the tensor.
  • shape - The shape of the tensor.
  • strides - The strides of the tensor data in memory.

§Example

use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(t.shape, [2, 2]);

Fields§

§storage: TensorStorage<T, A>

The storage of the tensor.

§shape: [usize; N]

The shape of the tensor.

§strides: [usize; N]

The strides of the tensor data in memory.

Implementations§

Source§

impl<T, const N: usize, A: TensorAllocator> Tensor<T, N, A>

Source

pub fn as_slice(&self) -> &[T]

Get the data of the tensor as a slice.

§Returns

A slice containing the data of the tensor.

Source

pub fn as_slice_mut(&mut self) -> &mut [T]

Get the data of the tensor as a mutable slice.

§Returns

A mutable slice containing the data of the tensor.

Source

pub fn as_ptr(&self) -> *const T

Get the data of the tensor as a pointer.

§Returns

A pointer to the data of the tensor.

Source

pub fn as_mut_ptr(&mut self) -> *mut T

Get the data of the tensor as a mutable pointer.

§Returns

A mutable pointer to the data of the tensor.

Source

pub fn into_vec(self) -> Vec<T>

Consumes the tensor and returns the underlying vector.

This method destroys the tensor and returns ownership of the underlying data. The returned vector will have a length equal to the total number of elements in the tensor.

Source

pub fn from_shape_vec( shape: [usize; N], data: Vec<T>, alloc: A, ) -> Result<Self, TensorError>

Creates a new Tensor with the given shape and data.

§Arguments
  • shape - An array containing the shape of the tensor.
  • data - A vector containing the data of the tensor.
  • alloc - The allocator to use.
§Returns

A new Tensor instance.

§Errors

If the number of elements in the data does not match the shape of the tensor, an error is returned.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(t.shape, [2, 2]);
Source

pub fn from_shape_slice( shape: [usize; N], data: &[T], alloc: A, ) -> Result<Self, TensorError>
where T: Clone,

Creates a new Tensor with the given shape and slice of data.

§Arguments
  • shape - An array containing the shape of the tensor.
  • data - A slice containing the data of the tensor.
  • alloc - The allocator to use.
§Returns

A new Tensor instance.

§Errors

If the number of elements in the data does not match the shape of the tensor, an error is returned.

Source

pub unsafe fn from_raw_parts( shape: [usize; N], data: *const T, len: usize, alloc: A, ) -> Result<Self, TensorError>
where T: Clone,

Creates a new Tensor with the given shape and raw parts.

§Arguments
  • shape - An array containing the shape of the tensor.
  • data - A pointer to the data of the tensor.
  • len - The length of the data.
  • alloc - The allocator to use.
§Safety

The pointer must be non-null and the length must be valid.

Source

pub fn from_shape_val(shape: [usize; N], value: T, alloc: A) -> Self
where T: Clone,

Creates a new Tensor with the given shape and a default value. Creates a new Tensor with the given shape and a default value.

§Arguments
  • shape - An array containing the shape of the tensor.
  • value - The default value to fill the tensor with.
§Returns

A new Tensor instance.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_val([4], 0, CpuAllocator);
assert_eq!(t.as_slice(), vec![0, 0, 0, 0]);

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_val([2, 2], 1, CpuAllocator);
assert_eq!(t.as_slice(), vec![1, 1, 1, 1]);

let t = Tensor::<u8, 3, CpuAllocator>::from_shape_val([2, 1, 3], 2, CpuAllocator);
assert_eq!(t.as_slice(), vec![2, 2, 2, 2, 2, 2]);
Source

pub fn from_shape_fn<F>(shape: [usize; N], alloc: A, f: F) -> Self
where F: Fn([usize; N]) -> T,

Create a new Tensor with the given shape and a function to generate the data.

The function f is called with the index of the element to generate.

§Arguments
  • shape - An array containing the shape of the tensor.
  • f - The function to generate the data.
§Returns

A new Tensor instance.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_fn([4], CpuAllocator, |[i]| i as u8);
assert_eq!(t.as_slice(), vec![0, 1, 2, 3]);

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_fn([2, 2], CpuAllocator, |[i, j]| (i * 2 + j) as u8);
assert_eq!(t.as_slice(), vec![0, 1, 2, 3]);
Source

pub fn numel(&self) -> usize

Returns the number of elements in the tensor.

§Returns

The number of elements in the tensor.

Source

pub fn get_iter_offset(&self, index: [usize; N]) -> Option<usize>

Get the offset of the element at the given index.

§Arguments
  • index - The list of indices to get the element from.
§Returns

The offset of the element at the given index.

Source

pub fn get_iter_offset_unchecked(&self, index: [usize; N]) -> usize

Get the offset of the element at the given index without checking dim sizes.

§Arguments
  • index - The list of indices to get the element from.
§Returns

The offset of the element at the given index.

Source

pub fn get_index_unchecked(&self, offset: usize) -> [usize; N]

Get the index of the element at the given offset without checking dim sizes. The reverse of Self::get_iter_offset_unchecked.

§Arguments
  • offset - The offset of the element at the given index.
§Returns

The array of indices to get the element from.

Source

pub fn get_index(&self, offset: usize) -> Result<[usize; N], TensorError>

Get the index of the element at the given offset. The reverse of Self::get_iter_offset.

§Arguments
  • offset - The offset of the element at the given index.
§Returns

The array of indices to get the element from.

§Errors

If the offset is out of bounds (>= numel), an error is returned.

Source

pub fn get_unchecked(&self, index: [usize; N]) -> &T

Get the element at the given index without checking if the index is out of bounds.

§Arguments
  • index - The list of indices to get the element from.
§Returns

A reference to the element at the given index.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();
assert_eq!(*t.get_unchecked([0, 0]), 1);
assert_eq!(*t.get_unchecked([0, 1]), 2);
assert_eq!(*t.get_unchecked([1, 0]), 3);
assert_eq!(*t.get_unchecked([1, 1]), 4);
Source

pub fn get(&self, index: [usize; N]) -> Option<&T>

Get the element at the given index, checking if the index is out of bounds.

§Arguments
  • index - The list of indices to get the element from.
§Returns

A reference to the element at the given index.

§Errors

If the index is out of bounds, an error is returned.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 2, CpuAllocator>::from_shape_vec([2, 2], data, CpuAllocator).unwrap();

assert_eq!(t.get([0, 0]), Some(&1));
assert_eq!(t.get([0, 1]), Some(&2));
assert_eq!(t.get([1, 0]), Some(&3));
assert_eq!(t.get([1, 1]), Some(&4));

assert!(t.get([2, 0]).is_none());
Source

pub fn reshape<const M: usize>( &self, shape: [usize; M], ) -> Result<TensorView<'_, T, M, A>, TensorError>

Reshape the tensor to a new shape.

§Arguments
  • shape - The new shape of the tensor.
§Returns

A new TensorView instance.

§Errors

If the number of elements in the new shape does not match the number of elements in the tensor, an error is returned.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];

let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();
let t2 = t.reshape([2, 2]).unwrap();
assert_eq!(t2.shape, [2, 2]);
assert_eq!(t2.as_slice(), vec![1, 2, 3, 4]);
assert_eq!(t2.strides, [2, 1]);
assert_eq!(t2.numel(), 4);
Source

pub fn permute_axes(&self, axes: [usize; N]) -> TensorView<'_, T, N, A>

Permute the dimensions of the tensor.

The permutation is given as an array of indices, where the value at each index is the new index of the dimension. The data is not moved, only the order of the dimensions is changed.

§Arguments
  • axes - The new order of the dimensions.
§Returns

A view of the tensor with the dimensions permuted.

Source

pub fn view(&self) -> TensorView<'_, T, N, A>

Return a view of the tensor.

The view is a reference to the tensor storage with a different shape and strides.

§Returns

A TensorView instance.

Source

pub fn zeros(shape: [usize; N], alloc: A) -> Tensor<T, N, A>
where T: Clone + Zero,

Create a new tensor with all elements set to zero.

§Arguments
  • shape - The shape of the tensor.
  • alloc - The allocator to use.
§Returns
Source

pub fn map<U, F>(&self, f: F) -> Tensor<U, N, A>
where F: Fn(&T) -> U,

Apply a function to each element of the tensor.

§Arguments
  • f - The function to apply to each element.
§Returns

A new Tensor instance.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();

let t2 = t.map(|x| *x + 1);
assert_eq!(t2.as_slice(), vec![2, 3, 4, 5]);
Source

pub fn is_standard_layout(&self) -> bool

Checks if the Tensor has a standard contiguous layout according to its shape and strides.

§Returns

boolean, true if contiguous and false if not

§Examples
use kornia_tensor::{Tensor, CpuAllocator};
let data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let mut t = Tensor::<u8, 3, CpuAllocator>::from_shape_vec([2, 2, 3], data, CpuAllocator).unwrap();
// arbitrary incorrect stride
t.strides = [10, 5, 1];
assert!(!t.is_standard_layout());
Source

pub fn to_standard_layout(&self, alloc: A) -> Result<Self, TensorError>
where T: Clone + Debug,

Copy Tensor storage data into contiguous memory if not already

§Returns

A new Tensor with contiguous storage

§Examples
use kornia_tensor::{Tensor, CpuAllocator};
let data: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let mut t = Tensor::<u8, 3, CpuAllocator>::from_shape_vec([2, 2, 3], data.clone(), CpuAllocator).unwrap();
// altering strides
t.strides = [1, 6, 2];
assert!(!t.is_standard_layout());
let t2 = t.to_standard_layout(CpuAllocator);
match t.to_standard_layout(CpuAllocator) {
    Ok(t2) => {
        assert!(t2.is_standard_layout());
    }
    Err(e) => {
        eprintln!("to_standard_layout failed: {}", e);
    }
}
Source

pub fn cast<U>(&self) -> Tensor<U, N, CpuAllocator>
where U: From<T>, T: Clone,

Cast the tensor to a new type.

§Returns

A new Tensor instance.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data: Vec<u8> = vec![1, 2, 3, 4];
let t = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data, CpuAllocator).unwrap();

let t2 = t.cast::<f32>();
assert_eq!(t2.as_slice(), vec![1.0, 2.0, 3.0, 4.0]);
Source

pub fn element_wise_op<F>( &self, other: &Tensor<T, N, CpuAllocator>, op: F, ) -> Result<Tensor<T, N, CpuAllocator>, TensorError>
where F: Fn(&T, &T) -> T,

Perform an element-wise operation on two tensors.

§Arguments
  • other - The other tensor to perform the operation with.
  • op - The operation to perform.
§Returns

A new Tensor instance.

§Example
use kornia_tensor::{Tensor, CpuAllocator};

let data1: Vec<u8> = vec![1, 2, 3, 4];
let t1 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data1, CpuAllocator).unwrap();

let data2: Vec<u8> = vec![1, 2, 3, 4];
let t2 = Tensor::<u8, 1, CpuAllocator>::from_shape_vec([4], data2, CpuAllocator).unwrap();

let t3 = t1.element_wise_op(&t2, |a, b| *a + *b).unwrap();
assert_eq!(t3.as_slice(), vec![2, 4, 6, 8]);

let t4 = t1.element_wise_op(&t2, |a, b| *a - *b).unwrap();
assert_eq!(t4.as_slice(), vec![0, 0, 0, 0]);

let t5 = t1.element_wise_op(&t2, |a, b| *a * *b).unwrap();
assert_eq!(t5.as_slice(), vec![1, 4, 9, 16]);

let t6 = t1.element_wise_op(&t2, |a, b| *a / *b).unwrap();
assert_eq!(t6.as_slice(), vec![1, 1, 1, 1]);

Trait Implementations§

Source§

impl<T, const N: usize, A> Clone for Tensor<T, N, A>
where T: Clone, A: TensorAllocator + Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, const N: usize, A> Display for Tensor<T, N, A>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T, const N: usize, A> Freeze for Tensor<T, N, A>
where A: Freeze,

§

impl<T, const N: usize, A> RefUnwindSafe for Tensor<T, N, A>

§

impl<T, const N: usize, A> Send for Tensor<T, N, A>

§

impl<T, const N: usize, A> Sync for Tensor<T, N, A>

§

impl<T, const N: usize, A> Unpin for Tensor<T, N, A>
where A: Unpin,

§

impl<T, const N: usize, A> UnwindSafe for Tensor<T, N, A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.