Tensor

Struct Tensor 

Source
pub struct Tensor<T: Scalar, B: Backend> { /* private fields */ }
Expand description

A multi-dimensional tensor with stride-based layout.

Tensors support zero-copy view operations (permute, reshape) and automatically make data contiguous when needed for operations like GEMM.

§Type Parameters

  • T - The scalar element type (f32, f64, etc.)
  • B - The backend type (Cpu, Cuda)

§Example

use omeinsum::{Tensor, Cpu};

let a = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
let b = a.permute(&[1, 0]);  // Zero-copy transpose
let c = b.contiguous();      // Make contiguous copy

Implementations§

Source§

impl<T: Scalar, B: Backend> Tensor<T, B>

Source

pub fn contract_binary<A: Algebra<Scalar = T, Index = u32>>( &self, other: &Self, ia: &[usize], ib: &[usize], iy: &[usize], ) -> Self
where T: BackendScalar<B>,

Binary tensor contraction using reshape-to-GEMM strategy.

§Arguments
  • other - The other tensor to contract with
  • ia - Index labels for self
  • ib - Index labels for other
  • iy - Output index labels
§Example
use omeinsum::{Tensor, Cpu};
use omeinsum::algebra::MaxPlus;

// A[i,j,k] × B[j,k,l] → C[i,l]
let a = Tensor::<f32, Cpu>::from_data(&(0..24).map(|x| x as f32).collect::<Vec<_>>(), &[2, 3, 4]);
let b = Tensor::<f32, Cpu>::from_data(&(0..60).map(|x| x as f32).collect::<Vec<_>>(), &[3, 4, 5]);
let c = a.contract_binary::<MaxPlus<f32>>(&b, &[0, 1, 2], &[1, 2, 3], &[0, 3]);
assert_eq!(c.shape(), &[2, 5]);
Source

pub fn contract_binary_with_argmax<A: Algebra<Scalar = T, Index = u32>>( &self, other: &Self, ia: &[usize], ib: &[usize], iy: &[usize], ) -> (Self, Tensor<u32, B>)
where T: BackendScalar<B>,

Binary contraction with argmax tracking.

Source§

impl<T: Scalar, B: Backend> Tensor<T, B>

Source

pub fn from_data(data: &[T], shape: &[usize]) -> Self
where B: Default,

Create a tensor from data with the given shape.

Data is assumed to be in column-major (Fortran) order.

Source

pub fn from_data_with_backend(data: &[T], shape: &[usize], backend: B) -> Self

Create a tensor from data with explicit backend.

Source

pub fn zeros(shape: &[usize]) -> Self
where B: Default,

Create a zero-filled tensor.

Source

pub fn zeros_with_backend(shape: &[usize], backend: B) -> Self

Create a zero-filled tensor with explicit backend.

Source

pub fn from_storage(storage: B::Storage<T>, shape: &[usize], backend: B) -> Self

Create a tensor from storage with given shape.

The storage must be contiguous and have exactly shape.iter().product() elements.

Source

pub fn storage(&self) -> Option<&B::Storage<T>>

Get a reference to the underlying storage.

Returns Some(&storage) only if the tensor is contiguous and has no offset. For non-contiguous tensors, call contiguous() first.

Source

pub fn shape(&self) -> &[usize]

Get the shape of the tensor.

Source

pub fn strides(&self) -> &[usize]

Get the strides of the tensor.

Source

pub fn ndim(&self) -> usize

Get the number of dimensions.

Source

pub fn numel(&self) -> usize

Get the total number of elements.

Source

pub fn backend(&self) -> &B

Get the backend.

Source

pub fn is_contiguous(&self) -> bool

Check if the tensor is contiguous in memory (row-major).

Source

pub fn to_vec(&self) -> Vec<T>

Copy all data to a Vec.

Source

pub fn as_slice(&self) -> Option<&[T]>
where B::Storage<T>: AsRef<[T]>,

Get underlying storage (only if contiguous).

Source

pub fn get(&self, index: usize) -> T

Get element at linear index (column-major).

This is an O(ndim) operation that directly accesses storage without allocating memory. The linear index is interpreted in column-major order.

§Arguments
  • index - Linear index into the flattened tensor (column-major order)
§Panics

Panics if index is out of bounds.

§Example
use omeinsum::{Tensor, Cpu};

let t = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
assert_eq!(t.get(0), 1.0);
assert_eq!(t.get(3), 4.0);
Source

pub fn permute(&self, axes: &[usize]) -> Self

Permute dimensions (zero-copy).

§Example
use omeinsum::{Tensor, Cpu};

let data: Vec<f32> = (0..24).map(|x| x as f32).collect();
let a = Tensor::<f32, Cpu>::from_data(&data, &[2, 3, 4]);
let b = a.permute(&[2, 0, 1]);  // Shape becomes [4, 2, 3]
assert_eq!(b.shape(), &[4, 2, 3]);
Source

pub fn t(&self) -> Self

Transpose (2D shorthand for permute).

Source

pub fn reshape(&self, new_shape: &[usize]) -> Self

Reshape to a new shape (zero-copy if contiguous).

§Example
use omeinsum::{Tensor, Cpu};

let a = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
let b = a.reshape(&[6]);      // Flatten
let c = a.reshape(&[3, 2]);   // Different shape, same data
assert_eq!(b.shape(), &[6]);
assert_eq!(c.shape(), &[3, 2]);
Source

pub fn contiguous(&self) -> Self

Make tensor contiguous in memory.

If already contiguous, returns a clone (shared storage). Otherwise, copies data to a new contiguous buffer.

Source

pub fn sum<A: Algebra<Scalar = T>>(&self) -> T

Sum all elements using the algebra’s addition.

§Type Parameters
  • A - The algebra to use for summation
§Example
use omeinsum::{Tensor, Cpu, Standard};

let t = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
let sum = t.sum::<Standard<f32>>();
assert_eq!(sum, 10.0);
Source

pub fn sum_axis<A: Algebra<Scalar = T>>(&self, axis: usize) -> Self
where B: Default,

Sum along a specific axis using the algebra’s addition.

The result has one fewer dimension than the input.

§Arguments
  • axis - The axis to sum over
§Panics

Panics if axis is out of bounds.

§Example
use omeinsum::{Tensor, Cpu, Standard};

// Column-major: data [1, 2, 3, 4] with shape [2, 2] represents:
// [[1, 3],
//  [2, 4]]
let t = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
// Sum over axis 1 (columns): [1+3, 2+4] = [4, 6]
let result = t.sum_axis::<Standard<f32>>(1);
assert_eq!(result.to_vec(), vec![4.0, 6.0]);
Source

pub fn diagonal(&self) -> Self
where B: Default,

Extract diagonal elements from a 2D tensor.

§Panics

Panics if the tensor is not 2D or not square.

§Example
use omeinsum::{Tensor, Cpu};

let t = Tensor::<f32, Cpu>::from_data(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
let diag = t.diagonal();
assert_eq!(diag.to_vec(), vec![1.0, 4.0]);

Trait Implementations§

Source§

impl<T: Clone + Scalar, B: Clone + Backend> Clone for Tensor<T, B>
where B::Storage<T>: Clone,

Source§

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

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: Scalar, B: Backend> Debug for Tensor<T, B>

Source§

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

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

impl<'a, T: Scalar, B: Backend> From<&'a Tensor<T, B>> for TensorView<'a, T, B>

Source§

fn from(tensor: &'a Tensor<T, B>) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

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

§

impl<T, B> RefUnwindSafe for Tensor<T, B>

§

impl<T, B> Send for Tensor<T, B>

§

impl<T, B> Sync for Tensor<T, B>

§

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

§

impl<T, B> UnwindSafe for Tensor<T, B>
where B: UnwindSafe, <B as Backend>::Storage<T>: RefUnwindSafe,

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
§

impl<T> ByRef<T> for T

§

fn by_ref(&self) -> &T

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
§

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

§

fn rand<T>(&self, rng: &mut (impl Rng + ?Sized)) -> T
where Self: Distribution<T>,

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

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

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,

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

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V