Struct zyx_cpu::Tensor

source ·
pub struct Tensor<B>
where B: Backend,
{ /* private fields */ }
Expand description

Tensor is the core object of zyx. It is multidimensional array.

Implementations§

source§

impl<B> Tensor<B>
where B: Backend,

source

pub fn id(&self) -> Id

Tensor’s unique identification. All tensors on one backend will always have different ids.

source

pub fn shape(&self) -> Shape

Returns the shape of the self tensor.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
assert_eq!(x.shape(), [2, 3]);
source

pub fn numel(&self) -> usize

Returns number of elements in the self tensor.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
assert_eq!(x.numel(), 6);
source

pub fn dtype(&self) -> DType

Returns the dtype of the self tensor.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
assert_eq!(x.dtype(), zyx_opencl::DType::I32);
source

pub fn rank(&self) -> usize

Returns the rank of the self tensor. This is the number of tensor’s dimensions.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
assert_eq!(x.rank(), 2);
source

pub fn backend(&self) -> B

Returns the backend of the self tensor.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
let y = x.backend().randn([2, 4, 3], zyx_opencl::DType::F32);
source

pub fn detach(&self) -> Tensor<B>

Detach gradient tape from tensor. This means that resulting tensor is a shallow copy of self, but it’s gradient will be ones. Result of this operation can only be differentiated by itself.

let dev = zyx_opencl::device()?;
let x = dev.tensor([2, 3]);
let y = &x + &x;
let g = y.backward([&x]).pop().unwrap().unwrap();
assert_eq!(g, [2, 2]);
let z = y.detach();
let g = z.backward([&z]).pop().unwrap().unwrap();
assert_eq!(g, [1, 1]);
let g = z.backward([&x]).pop().unwrap();
assert_eq!(g, None);
source

pub fn to_vec<T>(&self) -> Result<Vec<T>, ZyxError>
where T: Scalar,

Load tensor from backend into vector

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
let xvec: Vec<i32> = x.to_vec()?;
assert_eq!(xvec, vec![2, 3, 1, 4, 1, 3]);
source

pub fn item<T>(&self) -> Result<T, ZyxError>
where T: Scalar,

Returns first element stored in this tensor. Usually used for tensors with exactly one element. Error is returned if self tensor contains zero elements or if backend returns error.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 1], [4, 1, 3]]);
let xitem: i32 = x.item()?;
assert_eq!(xitem, 2);
source

pub fn backward<'a>( &'a self, sources: impl IntoIterator<Item = &'a Tensor<B>> ) -> Vec<Option<Tensor<B>>>
where B: 'a,

Returns gradients of self w.r.t. sources.

let dev = zyx_opencl::device()?;
let x = dev.tensor([3., 2., 1.]);
let y = x.exp() + &x;
let x_grad = y.backward([&x]).into_iter().next().unwrap().unwrap();
assert_eq!(x_grad, [21.0855369, 8.3890561, 3.7182818]);
source

pub fn cast(&self, dtype: DType) -> Tensor<B>

Cast self into dtype.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[3, 4, 2], [4, 5, 2]]);
let y = x.cast(DType::F32);
assert_eq!(y.dtype(), DType::F32);
assert_eq!(y, [[3f32, 4., 2.], [4., 5., 2.]]);
source

pub fn relu(&self) -> Tensor<B>

Returns a new tensor with the rectified linear unit function applied to the elements of self.

source

pub fn sin(&self) -> Tensor<B>

Returns a new tensor with the sine of the elements of self.

source

pub fn cos(&self) -> Tensor<B>

Returns a new tensor with the cosine of the elements of self.

source

pub fn ln(&self) -> Tensor<B>

Returns a new tensor with the natural logarithm of the elements of self. Due to performance reasons, this function does not check if self fits into domain of ln(x). Result on out of domain numbers is implementation defined (when x <= 0).

source

pub fn exp(&self) -> Tensor<B>

Returns a new tensor with the exponential of the elements of self.

source

pub fn tanh(&self) -> Tensor<B>

Returns a new tensor with the hyperbolic tangent of the elements of self.

source

pub fn sqrt(&self) -> Tensor<B>

Returns a new tensor with the square root of the elements of self. Due to performance reasons, this function does not check if self fits into domain of ln(x). Result on out of domain numbers is implementation defined (when x < 0).

source

pub fn reciprocal(&self) -> Tensor<B>

Returns 1/self

source

pub fn rsqrt(&self) -> Tensor<B>

Returns 1/self.sqrt()

source

pub fn dropout(&self, probability: impl Scalar) -> Tensor<B>

Returns a new tensor with each element of self randomly zeroed with given probability.

source

pub fn abs(&self) -> Tensor<B>

Returns a new tensor with the absolute value of the elements of self.

source

pub fn sigmoid(&self) -> Tensor<B>

Returns a new tensor with the sigmoid (logistic function) of the elements of self.

source

pub fn swish(&self) -> Tensor<B>

Returns a new tensor with the swish/silu of the elements of self.

source

pub fn mish(&self) -> Tensor<B>

Returns a new tensor with the mish of the elements of self.

source

pub fn softplus(&self, beta: impl Scalar, threshold: impl Scalar) -> Tensor<B>

Returns a new tensor with the softplus of the elements of self.

source

pub fn tan(&self) -> Tensor<B>

Returns a new tensor with the tangent of the elements of self.

source

pub fn leaky_relu(&self, neg_slope: impl Scalar) -> Tensor<B>

Returns a new tensor with the leaky relu of the elements of self.

source

pub fn elu(&self, alpha: impl Scalar) -> Tensor<B>

Returns a new tensor with the elu of the elements of self.

source

pub fn selu(&self) -> Tensor<B>

Returns a new tensor with the selu of the elements of self.

source

pub fn celu(&self, alpha: impl Scalar) -> Tensor<B>

Returns a new tensor with the celu of the elements of self.

source

pub fn gelu(&self) -> Tensor<B>

Returns a new tensor with the gelu of the elements of self.

source

pub fn quick_gelu(&self) -> Tensor<B>

Returns a new tensor with the quick gelu of the elements of self.

source

pub fn softmax(&self, axes: impl IntoAxes) -> Tensor<B>

Returns a new tensor with the softmax of the elements of self.

source

pub fn ln_softmax(&self, axes: impl IntoAxes) -> Tensor<B>

Returns a new tensor with the log softmax of the elements of self.

source

pub fn l1_loss(&self, target: impl IntoTensor<B>) -> Tensor<B>

Measures the mean absolute error (MAE) between each element in the input self and target.

source

pub fn mse_loss(&self, target: impl IntoTensor<B>) -> Tensor<B>

Measures the mean squared error (MSE) between each element in the input self and target.

source

pub fn cross_entropy_loss( &self, target: impl IntoTensor<B>, axes: impl IntoAxes ) -> Tensor<B>

Computes the cross entropy loss between self logits and target. This function expects self to contain probabilities for each class.

source

pub fn pow(&self, exponent: impl IntoTensor<B>) -> Tensor<B>

Exponentiation on self

source

pub fn cmplt(&self, rhs: impl IntoTensor<B>) -> Tensor<B>

Elementwise compare less than between self and rhs

source

pub fn where_( &self, if_true: impl IntoTensor<B>, if_false: impl IntoTensor<B> ) -> Tensor<B>

Returns a new tensor with the true values replaced with if_true and the false values replaced with if_false.

source

pub fn cosine_similarity( &self, rhs: impl IntoTensor<B>, eps: impl IntoTensor<B> ) -> Tensor<B>

Returns cosine_similarity between self and rhs, computed along axes.

source

pub fn dot(&self, rhs: impl IntoTensor<B>) -> Tensor<B>

Dot product (mathematical multiplication) of self and rhs.

let dev = zyx_opencl::device()?;
let x = dev.tensor([[3, 4, 2], [4, 5, 2]]);
let y = dev.tensor([[3], [1], [4]]);
assert_eq!(x.dot(y), [[21], [25]]);
source

pub fn reshape(&self, shape: impl Into<Shape>) -> Tensor<B>

Reshape self to shape.

§Panics

Following must hold: self.numel() == shape.numel()

source

pub fn expand(&self, shape: impl Into<Shape>) -> Tensor<B>

Expand self into bigger shape

source

pub fn pad( &self, padding: impl IntoIterator<Item = (i64, i64)>, value: impl IntoTensor<B> ) -> Tensor<B>

Constant padding

This can both add and remove values from tensor. Negative padding removes values, positive padding adds values.

Pad last dimension by (1, 2)

use zyx_opencl;
let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3],
                    [4, 1]]);
let z = x.pad([(1, 2)], 0);
std::println!("{}", z);
assert_eq!(z, [[0, 2, 3, 0, 0],
               [0, 4, 1, 0, 0]]);

Pad last dimension by (2, -1) and second last dimension by (1, 1)

let z = x.pad([(2, -1), (1, 1)], 0);
println!("z: {z}");
assert_eq!(z, [[0, 0, 0],
               [0, 0, 2],
               [0, 0, 4],
               [0, 0, 0]]);
§Panics

T must be of the same dtype as Tensor’s dtype, otherwise this function panics.

source

pub fn permute(&self, axes: impl IntoAxes) -> Tensor<B>

Reorder axes of self

source

pub fn transpose(&self) -> Tensor<B>

Swap last two axes of self. If self has rank == 1 and numel == n, then result will have shape /[n, 1/]

source

pub fn flatten(&self, axes: impl FlattenAxes) -> Tensor<B>

Flatten. Joins axes into one dimension,

source

pub fn sum(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by summing along axes. Shape is not squeezed.

use zyx_opencl;
let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3], [4, 1]]);
let z = x.sum(-1);
assert_eq!(z.shape(), [2, 1]);
let z = x.sum(0);
assert_eq!(z.shape(), [1, 2]);
let z = x.sum(..);
assert_eq!(z.shape(), [1, 1]);
source

pub fn max(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by maximizing along axes. Shape is not squeezed.

use zyx_opencl;
let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3], [4, 1]]);
let z = x.max(-1);
assert_eq!(z.shape(), [2, 1]);
let z = x.max(0);
assert_eq!(z.shape(), [1, 2]);
let z = x.max(..);
assert_eq!(z.shape(), [1, 1]);
source

pub fn mean(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by calculating mean along axes

source

pub fn var(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by calculating variance along axes

source

pub fn std(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by calculating standard deviation along axes

source

pub fn norm(&self, axes: impl IntoAxes, p: impl Scalar) -> Tensor<B>

Reduce self by calculating norm along axes

source

pub fn product(&self, axes: impl IntoAxes) -> Tensor<B>

Reduce self by calculating product of elements along axes

source

pub fn diagonal(&self) -> Tensor<B>

Get elements on diagonal of square matrix

source

pub fn get(&self, index: impl IntoIndex) -> Tensor<B>

Tensor indexing.

Tensors can be indexed by tuples of any combination of values or ranges of i64. If indexing along more than 8 dimensions, use &[Range<i64>] or &[i64]

use zyx_opencl;
let dev = zyx_opencl::device()?;
let x = dev.tensor([[2, 3, 4],
                    [4, 1, 8]]);
let y: i32 = x.get((-1, -3)).item()?;
assert_eq!(y, 4);
source

pub fn cat<'a>( tensors: impl IntoIterator<Item = &'a Tensor<B>>, dim: i64 ) -> Tensor<B>
where B: 'a,

Concatenate multiple tensors together along dim.

Trait Implementations§

source§

impl<B, IT> Add<IT> for &Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the + operator.
source§

fn add(self, rhs: IT) -> <&Tensor<B> as Add<IT>>::Output

Performs the + operation. Read more
source§

impl<B, IT> Add<IT> for Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the + operator.
source§

fn add(self, rhs: IT) -> <Tensor<B> as Add<IT>>::Output

Performs the + operation. Read more
source§

impl<B> Clone for Tensor<B>
where B: Backend,

source§

fn clone(&self) -> Tensor<B>

Returns a copy 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<B> Debug for Tensor<B>
where B: Backend,

source§

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

Formats the value using the given formatter. Read more
source§

impl<B> Display for Tensor<B>
where B: Backend,

source§

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

Formats the value using the given formatter. Read more
source§

impl<B, IT> Div<IT> for &Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the / operator.
source§

fn div(self, rhs: IT) -> <&Tensor<B> as Div<IT>>::Output

Performs the / operation. Read more
source§

impl<B, IT> Div<IT> for Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the / operator.
source§

fn div(self, rhs: IT) -> <Tensor<B> as Div<IT>>::Output

Performs the / operation. Read more
source§

impl<B> Drop for Tensor<B>
where B: Backend,

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<B> IntoTensor<B> for &Tensor<B>
where B: Backend,

source§

fn into_tensor(self, _backend: B) -> Tensor<B>

Convert self into tensor
source§

impl<B> IntoTensor<B> for Tensor<B>
where B: Backend,

source§

fn into_tensor(self, _backend: B) -> Tensor<B>

Convert self into tensor
source§

impl<B, IT> Mul<IT> for &Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the * operator.
source§

fn mul(self, rhs: IT) -> <&Tensor<B> as Mul<IT>>::Output

Performs the * operation. Read more
source§

impl<B, IT> Mul<IT> for Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the * operator.
source§

fn mul(self, rhs: IT) -> <Tensor<B> as Mul<IT>>::Output

Performs the * operation. Read more
source§

impl<B> Neg for &Tensor<B>
where B: Backend,

§

type Output = Tensor<B>

The resulting type after applying the - operator.
source§

fn neg(self) -> <&Tensor<B> as Neg>::Output

Performs the unary - operation. Read more
source§

impl<B> Neg for Tensor<B>
where B: Backend,

§

type Output = Tensor<B>

The resulting type after applying the - operator.
source§

fn neg(self) -> <Tensor<B> as Neg>::Output

Performs the unary - operation. Read more
source§

impl<B, IT> PartialEq<IT> for Tensor<B>
where B: Backend, IT: IntoTensor<B> + Clone,

source§

fn eq(&self, other: &IT) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<B, IT> Sub<IT> for &Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the - operator.
source§

fn sub(self, rhs: IT) -> <&Tensor<B> as Sub<IT>>::Output

Performs the - operation. Read more
source§

impl<B, IT> Sub<IT> for Tensor<B>
where B: Backend, IT: IntoTensor<B>,

§

type Output = Tensor<B>

The resulting type after applying the - operator.
source§

fn sub(self, rhs: IT) -> <Tensor<B> as Sub<IT>>::Output

Performs the - operation. Read more

Auto Trait Implementations§

§

impl<B> Freeze for Tensor<B>
where B: Freeze,

§

impl<B> RefUnwindSafe for Tensor<B>
where B: RefUnwindSafe,

§

impl<B> Send for Tensor<B>
where B: Send,

§

impl<B> Sync for Tensor<B>
where B: Sync,

§

impl<B> Unpin for Tensor<B>
where B: Unpin,

§

impl<B> UnwindSafe for Tensor<B>
where B: UnwindSafe,

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> 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> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

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

§

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§

default 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>,

§

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>,

§

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.