TensorHandle

Struct TensorHandle 

Source
pub struct TensorHandle<T>
where T: Clone + Num,
{ pub repr: TensorRepr<T>, pub axes: Vec<AxisMeta>, }
Expand description

Main tensor handle unifying all representations.

TensorHandle provides a unified interface for working with tensors regardless of their internal representation (dense, sparse, or low-rank). This enables polymorphic tensor operations and automatic representation selection.

§Design Goals

  • Unified API: Same interface for dense, sparse, and low-rank tensors
  • Metadata Tracking: Axis names and sizes for better debugging
  • Type Safety: Compile-time guarantees about tensor properties
  • Zero-Cost Abstraction: No runtime overhead when representation is known

§Examples

§Creating from Dense Tensors

use tenrso_core::{DenseND, TensorHandle, AxisMeta};

// With explicit axis metadata
let tensor = DenseND::<f64>::zeros(&[32, 128]);
let axes = vec![
    AxisMeta::new("batch", 32),
    AxisMeta::new("features", 128),
];
let handle = TensorHandle::from_dense(tensor, axes);

assert_eq!(handle.rank(), 2);
assert_eq!(handle.axes[0].name, "batch");

§Automatic Axis Naming

use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::ones(&[2, 3, 4]);
let handle = TensorHandle::from_dense_auto(tensor);

// Axes are named "axis_0", "axis_1", "axis_2"
assert_eq!(handle.axes[0].name, "axis_0");
assert_eq!(handle.axes[1].name, "axis_1");
assert_eq!(handle.axes[2].name, "axis_2");

§Querying Tensor Properties

use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::zeros(&[10, 20, 30]);
let handle = TensorHandle::from_dense_auto(tensor);

// Get rank and shape
assert_eq!(handle.rank(), 3);
assert_eq!(handle.shape().as_slice(), &[10, 20, 30]);

// Access the underlying dense tensor
if let Some(dense) = handle.as_dense() {
    assert_eq!(dense.len(), 6000);
}

§Converting Between Representations

use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::random_uniform(&[5, 5], 0.0, 1.0);
let handle = TensorHandle::from_dense_auto(tensor);

// Convert to dense (no-op if already dense)
let dense = handle.to_dense().unwrap();
assert_eq!(dense.shape(), &[5, 5]);

Fields§

§repr: TensorRepr<T>

Internal representation (Dense/Sparse/LowRank)

§axes: Vec<AxisMeta>

Axis metadata with symbolic names and sizes

Implementations§

Source§

impl<T> TensorHandle<T>
where T: Clone + Num,

Source

pub fn from_dense(dense: DenseND<T>, axes: Vec<AxisMeta>) -> TensorHandle<T>

Create a tensor handle from a dense tensor

§Arguments
  • dense - The dense tensor
  • axes - Axis metadata (must match tensor shape)
§Examples
use tenrso_core::{DenseND, TensorHandle, AxisMeta};

let tensor = DenseND::<f64>::zeros(&[2, 3]);
let axes = vec![
    AxisMeta::new("rows", 2),
    AxisMeta::new("cols", 3),
];
let handle = TensorHandle::from_dense(tensor, axes);
assert_eq!(handle.rank(), 2);
Source

pub fn from_dense_auto(dense: DenseND<T>) -> TensorHandle<T>

Create a tensor handle from a dense tensor with automatic axis naming

Axes are named “axis_0”, “axis_1”, etc.

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::zeros(&[2, 3, 4]);
let handle = TensorHandle::from_dense_auto(tensor);
assert_eq!(handle.rank(), 3);
assert_eq!(handle.axes[0].name, "axis_0");
Source

pub fn rank(&self) -> usize

Get the rank (number of dimensions) of this tensor.

§Complexity

O(1) - reads cached value from axis metadata

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::zeros(&[2, 3, 4]);
let handle = TensorHandle::from_dense_auto(tensor);

assert_eq!(handle.rank(), 3);
Source

pub fn shape(&self) -> SmallVec<[usize; 6]>

Get the shape of this tensor.

Returns a SmallVec containing the size of each dimension.

§Complexity

O(rank) - constructs SmallVec from axis metadata

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::zeros(&[10, 20, 30]);
let handle = TensorHandle::from_dense_auto(tensor);

let shape = handle.shape();
assert_eq!(shape.as_slice(), &[10, 20, 30]);
Source

pub fn as_dense(&self) -> Option<&DenseND<T>>

Get a reference to the dense representation if this is a dense tensor.

Returns None if the tensor is stored in sparse or low-rank format.

§Complexity

O(1) - pattern matching on enum variant

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::ones(&[5, 5]);
let handle = TensorHandle::from_dense_auto(tensor);

// Access the underlying dense tensor
if let Some(dense) = handle.as_dense() {
    assert_eq!(dense.shape(), &[5, 5]);
    assert_eq!(dense.len(), 25);
}
Source

pub fn as_dense_mut(&mut self) -> Option<&mut DenseND<T>>

Get a mutable reference to the dense representation if this is a dense tensor.

Returns None if the tensor is stored in sparse or low-rank format.

§Complexity

O(1) - pattern matching on enum variant

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::zeros(&[3, 3]);
let mut handle = TensorHandle::from_dense_auto(tensor);

// Modify the underlying dense tensor
if let Some(dense) = handle.as_dense_mut() {
    dense.as_array_mut()[[0, 0]] = 1.0;
}

assert_eq!(handle.as_dense().unwrap()[&[0, 0]], 1.0);
Source

pub fn to_dense(&self) -> Result<DenseND<T>, Error>

Convert this tensor to dense representation if not already dense.

For dense tensors, this clones the underlying data. For sparse and low-rank tensors, this will be implemented in future releases.

§Complexity
  • Dense: O(n) where n is the number of elements (clone operation)
  • Sparse: Not yet implemented
  • LowRank: Not yet implemented
§Errors

Returns an error if the tensor is sparse or low-rank (not yet implemented).

§Examples
use tenrso_core::{DenseND, TensorHandle};

let tensor = DenseND::<f64>::ones(&[4, 4]);
let handle = TensorHandle::from_dense_auto(tensor);

// Convert to dense (clones the data)
let dense = handle.to_dense().unwrap();
assert_eq!(dense.shape(), &[4, 4]);
assert_eq!(dense.len(), 16);

Trait Implementations§

Source§

impl<T> Clone for TensorHandle<T>
where T: Clone + Num,

Source§

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

Returns a duplicate of the value. Read more
1.0.0§

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

Performs copy-assignment from source. Read more
Source§

impl<T> Debug for TensorHandle<T>
where T: Debug + Clone + Num,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for TensorHandle<T>

§

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

§

impl<T> Send for TensorHandle<T>
where T: Send,

§

impl<T> Sync for TensorHandle<T>
where T: Sync,

§

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

§

impl<T> UnwindSafe for TensorHandle<T>

Blanket Implementations§

§

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

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

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

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

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

§

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

Mutably borrows from an owned value. Read more
§

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

§

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

§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
§

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

§

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
§

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

§

type Owned = T

The resulting type after obtaining ownership.
§

fn to_owned(&self) -> T

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

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

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

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

§

type Error = Infallible

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

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

Performs the conversion.
§

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

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

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> Allocation for T
where T: RefUnwindSafe + Send + Sync,