Skip to main content

SparseTensor

Struct SparseTensor 

Source
pub struct SparseTensor<T: TensorElement> { /* private fields */ }
Expand description

Sparse tensor in COO (Coordinate) format

COO format stores sparse tensors efficiently by only keeping track of non-zero elements and their coordinates. This is particularly useful for tensors with high sparsity ratios.

§Format

  • indices: N x D matrix where N is the number of non-zero elements and D is the number of dimensions
  • values: N-length vector containing the non-zero values
  • shape: The shape of the full dense tensor

§Example

use torsh_tensor::sparse::SparseTensor;

// Create a 3x3 sparse matrix with values at (0,0)=1.0, (1,2)=2.0, (2,1)=3.0
let indices = vec![vec![0, 0], vec![1, 2], vec![2, 1]];
let values = vec![1.0, 2.0, 3.0];
let shape = vec![3, 3];

let sparse = SparseTensor::from_coo(indices, values, shape).expect("sparse tensor creation should succeed");

Implementations§

Source§

impl<T: TensorElement> SparseTensor<T>

Source

pub fn from_coo( indices: Vec<Vec<usize>>, values: Vec<T>, shape: Vec<usize>, ) -> Result<Self>

Create a new sparse tensor from COO format

§Arguments
  • indices - Coordinates of non-zero elements (each inner vector is one coordinate)
  • values - Non-zero values corresponding to the indices
  • shape - Shape of the full dense tensor
§Returns

A new sparse tensor in COO format

§Errors

Returns error if indices and values have mismatched lengths or if coordinates are out of bounds

Source

pub fn from_dense(dense: &Tensor<T>, tolerance: T) -> Result<Self>
where T: Copy + PartialOrd + Zero + Signed,

Create a sparse tensor from a dense tensor by extracting non-zero elements

§Arguments
  • dense - The dense tensor to convert
  • tolerance - Values with absolute value below this threshold are considered zero
§Returns

A new sparse tensor containing only the non-zero elements

Source

pub fn to_dense(&self) -> Result<Tensor<T>>
where T: Copy + Zero,

Convert this sparse tensor to a dense tensor

§Returns

A dense tensor with zeros filled in for missing elements

Source

pub fn nnz(&self) -> usize

Get the number of non-zero elements

Source

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

Get the shape of the sparse tensor

Source

pub fn device(&self) -> DeviceType

Get the device where the tensor resides

Source

pub fn indices(&self) -> &[Vec<usize>]

Get the indices (coordinates) of non-zero elements

Source

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

Get the non-zero values

Source

pub fn sparsity(&self) -> f64

Calculate the sparsity ratio (fraction of zero elements)

Source

pub fn memory_usage(&self) -> usize

Get the memory footprint of the sparse representation in bytes

Source

pub fn memory_efficiency(&self) -> f64

Compare memory usage with equivalent dense representation

Source

pub fn add(&self, other: &Self) -> Result<Self>
where T: Copy + Add<Output = T> + Zero + PartialEq,

Element-wise addition with another sparse tensor

§Arguments
  • other - The other sparse tensor to add
§Returns

A new sparse tensor containing the sum

Source

pub fn mul(&self, other: &Self) -> Result<Self>
where T: Copy + Mul<Output = T> + Zero + PartialEq,

Element-wise multiplication with another sparse tensor

For sparse tensors, multiplication only produces non-zero results where both tensors have non-zero elements at the same location.

Source

pub fn mul_scalar(&self, scalar: T) -> Result<Self>
where T: Copy + Mul<Output = T> + Zero + PartialEq,

Scalar multiplication

Source

pub fn matmul(&self, other: &Self) -> Result<Self>
where T: Copy + Add<Output = T> + Mul<Output = T> + Zero + PartialEq,

Matrix multiplication for 2D sparse tensors

§Arguments
  • other - The other 2D sparse tensor to multiply with
§Returns

A new sparse tensor containing the matrix product

Source

pub fn transpose(&self) -> Result<Self>
where T: Copy,

Transpose a 2D sparse tensor

Source

pub fn map<F>(&self, f: F) -> Result<Self>
where F: Fn(T) -> T, T: Copy + Zero + PartialEq,

Apply a function to all non-zero values

Source

pub fn is_valid(&self) -> bool

Check if the sparse tensor is structurally valid

Source

pub fn coalesce(&mut self) -> Result<()>
where T: Copy + AddAssign + Zero + PartialEq,

Remove duplicate indices by summing their values

Source§

impl<T: TensorElement> SparseTensor<T>

Conversion utilities for sparse tensors

Source

pub fn eye(size: usize) -> Result<Self>
where T: Copy + One,

Create a sparse identity matrix

Source

pub fn from_triplets( rows: Vec<usize>, cols: Vec<usize>, vals: Vec<T>, shape: Vec<usize>, ) -> Result<Self>

Create a sparse tensor from triplets (row, col, value) for 2D case

Trait Implementations§

Source§

impl<T: Clone + TensorElement> Clone for SparseTensor<T>

Source§

fn clone(&self) -> SparseTensor<T>

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: Debug + TensorElement> Debug for SparseTensor<T>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for SparseTensor<T>

§

impl<T> RefUnwindSafe for SparseTensor<T>
where T: RefUnwindSafe,

§

impl<T> Send for SparseTensor<T>

§

impl<T> Sync for SparseTensor<T>

§

impl<T> Unpin for SparseTensor<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for SparseTensor<T>

§

impl<T> UnwindSafe for SparseTensor<T>
where T: 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> 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> 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

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,

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

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

Source§

fn vzip(self) -> V