Skip to main content

Tensor

Struct Tensor 

Source
pub struct Tensor { /* private fields */ }
Expand description

Dynamic tensor over the supported scalar types.

The erased tensor keeps dtype and rank dynamic: each preset scalar retains its typed owner without constructing a group, while caller-owned scalars remain External payloads recovered by their own type. Use TypedTensor<T, R> directly when the scalar type or rank should be represented in Rust’s type system.

§Examples

use tenferro_tensor::{DType, Tensor};

let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert_eq!(tensor.dtype(), DType::F64);

Implementations§

Source§

impl Tensor

Source

pub fn linear_offset(&self, indices: &[usize]) -> Result<usize, Error>

Compute the linear physical-buffer offset for a logical index.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2, 3], vec![0.0_f64; 6]).unwrap();
assert_eq!(t.linear_offset(&[1, 2])?, 5);
§Errors

Returns crate::Error::Validation containing tenferro_tensor_core::ValidationError::RankMismatch when indices has a rank different from the tensor, tenferro_tensor_core::ValidationError::InvalidArgument when an index is outside its axis extent, or tenferro_tensor_core::ValidationError::IntegerOverflow when checked offset arithmetic overflows.

Source

pub fn linear_offset2(&self, i: usize, j: usize) -> Result<usize, Error>

Compute the linear physical-buffer offset for a rank-2 logical index.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2, 3], vec![0.0_f64; 6]).unwrap();
assert_eq!(t.linear_offset2(1, 2)?, 5);
§Errors

Returns crate::Error::Validation containing tenferro_tensor_core::ValidationError::RankMismatch when the tensor rank is not two, tenferro_tensor_core::ValidationError::InvalidArgument when i or j is outside its axis extent, or tenferro_tensor_core::ValidationError::IntegerOverflow when checked offset arithmetic overflows.

Source

pub fn linear_offset3( &self, i: usize, j: usize, k: usize, ) -> Result<usize, Error>

Compute the linear physical-buffer offset for a rank-3 logical index.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2, 3, 2], vec![0.0_f64; 12]).unwrap();
assert_eq!(t.linear_offset3(1, 2, 1)?, 11);
§Errors

Returns crate::Error::Validation containing tenferro_tensor_core::ValidationError::RankMismatch when the tensor rank is not three, tenferro_tensor_core::ValidationError::InvalidArgument when i, j, or k is outside its axis extent, or tenferro_tensor_core::ValidationError::IntegerOverflow when checked offset arithmetic overflows.

Source

pub fn get<T>(&self, indices: &[usize]) -> Result<&T, Error>
where T: TensorScalar,

Borrow a single typed element by multi-index.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
assert_eq!(t.get::<f64>(&[1])?, &2.0);
assert!(t.get::<f32>(&[1]).is_err());
§Errors

Returns crate::Error::Validation containing tenferro_tensor_core::ValidationError::RankMismatch or tenferro_tensor_core::ValidationError::InvalidArgument for an invalid index, tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState for a device-backed tensor.

Source

pub fn get_mut<T>(&mut self, indices: &[usize]) -> Result<&mut T, Error>
where T: TensorScalar,

Mutably borrow a single typed element by multi-index.

§Examples
use tenferro_tensor::Tensor;

let mut t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
*t.get_mut::<f64>(&[0])? = 2.0;
assert_eq!(t.as_slice::<f64>()?, &[2.0]);
§Errors

Returns crate::Error::Validation containing tenferro_tensor_core::ValidationError::RankMismatch or tenferro_tensor_core::ValidationError::InvalidArgument for an invalid index, tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState for a device-backed tensor.

Source

pub unsafe fn get_unchecked<T>(&self, indices: &[usize]) -> Result<&T, Error>
where T: TensorScalar,

Try to borrow a single typed element by multi-index without release-mode bounds checks.

Debug builds still validate the rank and bounds. Dtype and backend host-access failures are still reported as errors.

§Safety

indices must have the same rank as this tensor and every index must be in bounds.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
assert_eq!(unsafe { *t.get_unchecked::<f64>(&[1])? }, 2.0);
§Errors

Returns crate::Error::RuntimeState for a device-backed tensor and tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype.

§Panics

May panic if the unsafe rank/bounds precondition is violated and the checked linear-offset calculation overflows.

Source

pub unsafe fn get_unchecked_mut<T>( &mut self, indices: &[usize], ) -> Result<&mut T, Error>
where T: TensorScalar,

Try to mutably borrow a single typed element by multi-index without release-mode bounds checks.

Debug builds still validate the rank and bounds. Dtype and backend host-access failures are still reported as errors.

§Safety

indices must have the same rank as this tensor and every index must be in bounds.

§Examples
use tenferro_tensor::Tensor;

let mut t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
unsafe {
    *t.get_unchecked_mut::<f64>(&[0])? = 2.0;
}
assert_eq!(t.as_slice::<f64>()?, &[2.0]);
§Errors

Returns crate::Error::RuntimeState for a device-backed tensor and tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype.

§Panics

May panic if the unsafe rank/bounds precondition is violated and the checked linear-offset calculation overflows.

Source

pub fn as_slice_mut<T>(&mut self) -> Result<&mut [T], Error>
where T: TensorScalar,

Mutably borrow the host data as a typed slice.

§Examples
use tenferro_tensor::Tensor;

let mut t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
t.as_slice_mut::<f64>()?[0] = 3.0;
assert_eq!(t.as_slice::<f64>()?, &[3.0, 2.0]);
assert!(t.as_slice_mut::<f32>().is_err());
§Errors

Returns tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState when the tensor is backed by a device buffer.

Source

pub fn iter<T>(&self) -> Result<Iter<'_, T>, Error>
where T: TensorScalar,

Iterate over the contiguous host buffer in physical memory order.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
let sum: f64 = t.iter::<f64>()?.copied().sum();
assert_eq!(sum, 3.0);
assert!(t.iter::<f32>().is_err());
§Errors

Returns tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState when the tensor is backed by a device buffer.

Source

pub fn iter_mut<T>(&mut self) -> Result<IterMut<'_, T>, Error>
where T: TensorScalar,

Mutably iterate over the contiguous host buffer in physical memory order.

§Examples
use tenferro_tensor::Tensor;

let mut t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
for value in t.iter_mut::<f64>()? {
    *value += 1.0;
}
assert_eq!(t.as_slice::<f64>()?, &[2.0, 3.0]);
assert!(t.iter_mut::<f32>().is_err());
§Errors

Returns tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState when the tensor is backed by a device buffer.

Source§

impl Tensor

Source

pub fn index_select( &self, axis: isize, positions: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor, Error>

Select entries from one axis using host-known positions.

§Examples
use tenferro_tensor::{BackendSession, Tensor};

fn select_last_axis(
    session: &mut dyn BackendSession,
    x: &Tensor,
) -> tenferro_tensor::Result<Tensor> {
    x.index_select(-1, &[2, 0], session)
}
§Errors

Returns crate::Error::Validation with a typed shape, axis, or argument source when the inputs cannot be packed without violating their metadata.

Source

pub fn stack( tensors: &[&Tensor], dim: isize, session: &mut dyn BackendSession, ) -> Result<Tensor, Error>

Stack tensors along a newly inserted axis.

§Examples
use tenferro_tensor::{BackendSession, Tensor};

fn stack_scalars(
    session: &mut dyn BackendSession,
    a: &Tensor,
    b: &Tensor,
) -> tenferro_tensor::Result<Tensor> {
    Tensor::stack(&[a, b], -1, session)
}
§Errors

Returns crate::Error::Validation with a typed shape, axis, or argument source when the inputs cannot be packed without violating their metadata.

Source§

impl Tensor

Source

pub fn external(payload: ErasedHostTensor) -> Tensor

Carry an externally defined scalar as a caller-owned payload.

The payload keeps its own element type and is recovered by that type, so no bytes are reinterpreted. Placement defaults to unpinned host memory, which is where a caller-owned payload lives.

§Examples
use tenferro_tensor::{DType, Tensor};
use tenferro_tensor::{DynRank, ErasedHostTensor, Host, TypedTensor};

let payload = ErasedHostTensor::new(
    TypedTensor::<f64, DynRank, Host>::from_host_vec_col_major(vec![1], vec![1.0_f64])?,
);
let element = payload.element_type_id();
let tensor = Tensor::external(payload);
assert_eq!(tensor.dtype(), DType::External(element));
assert_eq!(tensor.shape(), &[1]);
Source

pub fn from_typed<T>(typed: TypedTensor<T>) -> Tensor
where T: TensorScalar,

Build a tensor from a typed one, without naming its variant.

A call site that constructs a tensor from a typed tensor should use this rather than a variant, so that changing how the erased representation is stored changes this function and not its 1290 call sites. The variants remain until the removal’s last step, so both forms currently produce the same value.

§Examples
use tenferro_tensor::Tensor;

let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
let typed = tensor.into_typed::<f64>().unwrap();
let rebuilt = Tensor::from_typed(typed);
assert_eq!(rebuilt.as_typed::<f64>().unwrap().shape(), &[2]);
Source

pub fn external_payload(&self) -> Option<&ErasedHostTensor>

Borrow the erased payload of an externally defined tensor.

This is the counterpart of Tensor::external for dispatch: a table that matches on Tensor::dtype reaches the externally defined tag and needs the payload that tag stands for, just as the typed tags reach theirs through Tensor::as_typed. Every other tag returns None.

§Examples
use tenferro_tensor::Tensor;
use tenferro_tensor::{DynRank, ErasedHostTensor, Host, TypedTensor};

let payload = ErasedHostTensor::new(
    TypedTensor::<f64, DynRank, Host>::from_host_vec_col_major(vec![1], vec![1.0_f64])?,
);
let tensor = Tensor::external(payload);
assert!(tensor.external_payload().is_some());
Source

pub fn external_with_placement( payload: ErasedHostTensor, placement: Placement, ) -> Tensor

Carry an externally defined payload with an explicit placement.

Tensor::external defaults the placement to unpinned host memory, which is where a caller-owned payload normally lives; this entry point is for a caller that knows the placement it wants.

§Examples
use tenferro_tensor::{Placement, Tensor};
use tenferro_tensor::{DynRank, ErasedHostTensor, Host, TypedTensor};

let payload = ErasedHostTensor::new(
    TypedTensor::<f64, DynRank, Host>::from_host_vec_col_major(vec![1], vec![1.0_f64])?,
);
let tensor = Tensor::external_with_placement(payload, Placement::default());
assert!(tensor.external_payload().is_some());
Source

pub fn external_payload_mut(&mut self) -> Option<&mut ErasedHostTensor>

Mutably borrow the erased payload of an externally defined tensor.

The counterpart of Tensor::external_payload for callers that update the payload in place, such as a mutation test that checks the copy boundary.

§Examples
use tenferro_tensor::Tensor;
use tenferro_tensor::{DynRank, ErasedHostTensor, Host, TypedTensor};

let mut tensor = Tensor::external(ErasedHostTensor::new(
    TypedTensor::<f64, DynRank, Host>::from_host_vec_col_major(vec![1], vec![1.0_f64])?,
));
assert!(tensor.external_payload_mut().is_some());
Source§

impl Tensor

Source

pub fn as_real_view(&self) -> Result<TensorView<'_>, Error>

Borrow a complex tensor as its sealed interleaved real representation.

§Errors

Returns crate::Error::Unsupported for a non-complex dtype and ValidationError::ViewOutOfBounds or ValidationError::InvalidArgument for invalid layout metadata.

Source

pub fn as_real_view_mut(&mut self) -> Result<TensorViewMut<'_>, Error>

Borrow a complex tensor mutably as its sealed interleaved real representation.

§Errors

Returns crate::Error::Unsupported for a non-complex dtype and ValidationError::ViewOutOfBounds or ValidationError::InvalidArgument for invalid layout metadata.

Source

pub fn into_real(self) -> Result<Tensor, ReinterpretError<Tensor>>

Consume a complex tensor and reinterpret its owner as real without copying.

§Errors

Returns ReinterpretError::error containing ValidationError::InvalidArgument or ValidationError::ViewOutOfBounds while retaining the unchanged owner.

Source

pub fn as_complex_view(&self) -> Result<TensorView<'_>, Error>

Borrow an interleaved real tensor as its sealed complex representation.

§Errors

Returns crate::Error::Unsupported for a non-real dtype and ValidationError::ViewOutOfBounds or ValidationError::InvalidArgument for invalid layout metadata.

Source

pub fn as_complex_view_mut(&mut self) -> Result<TensorViewMut<'_>, Error>

Borrow an interleaved real tensor mutably as its sealed complex representation.

§Errors

Returns crate::Error::Unsupported for a non-real dtype and ValidationError::ViewOutOfBounds or ValidationError::InvalidArgument for invalid layout metadata.

Source

pub fn into_complex(self) -> Result<Tensor, ReinterpretError<Tensor>>

Consume a real tensor and reinterpret its owner as complex without copying.

§Errors

Returns ReinterpretError::error containing ValidationError::InvalidArgument or ValidationError::ViewOutOfBounds while retaining the unchanged owner.

Source

pub fn duplicate(&self) -> Result<Tensor, Error>

Make an explicit owning copy of this dtype-erased tensor.

Tensor deliberately does not implement Clone: copying can fail (device-only storage is rejected) and allocates a new, independent owner, so it is an explicit fallible call rather than an infallible clone(). The copy shares nothing with self; mutating one never affects the other. To share one tensor between several users without copying, wrap it in std::sync::Arc or borrow views of it.

§Examples
use std::sync::Arc;
use tenferro_tensor::Tensor;

let weights = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
// Two independent owners of the same values.
let copy = weights.duplicate()?;
assert_eq!(copy.as_slice::<f64>()?, weights.as_slice::<f64>()?);

// A shared, read-only handle instead of a copy.
let shared = Arc::new(weights);
let other = Arc::clone(&shared);
assert_eq!(other.shape(), &[2]);
§Errors

Returns crate::Error::RuntimeState or crate::Error::Unsupported when the selected backend/storage owner cannot be duplicated.

Source

pub fn from_vec_col_major<T>( shape: impl IntoShapeVec, data: Vec<T>, ) -> Result<Tensor, Error>
where T: TensorScalar,

Create a tensor from a shape and column-major flat data.

This is the Tensor-level equivalent of TypedTensor::<T>::from_vec_col_major.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 3.0, 2.0, 4.0]).unwrap();
assert_eq!(t.shape(), &[2, 2]);
assert_eq!(t.as_slice::<f64>().unwrap(), &[1.0, 3.0, 2.0, 4.0]);
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::ShapeDataLengthMismatch when the shape product differs from data.len(), or tenferro_tensor_core::ValidationError::IntegerOverflow when shape arithmetic overflows.

Source

pub fn from_vec_row_major<T>( shape: impl IntoShapeVec, data: Vec<T>, ) -> Result<Tensor, Error>
where T: TensorScalar,

Create a tensor from a shape and row-major (C-order) flat data.

The values are reordered once into tenferro’s column-major storage; no row-major owner is created. Use this for buffers authored in PyTorch/NumPy/C order instead of passing them to Self::from_vec_col_major, which would reinterpret them silently. This is the Tensor-level equivalent of TypedTensor::<T>::from_vec_row_major.

§Examples
use tenferro_tensor::Tensor;

// Row-major [[1, 2, 3], [4, 5, 6]].
let t = Tensor::from_vec_row_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0])?;
assert_eq!(t.shape(), &[2, 3]);
assert_eq!(t.as_slice::<f64>()?, &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::ShapeDataLengthMismatch when the shape product differs from data.len(), or tenferro_tensor_core::ValidationError::IntegerOverflow when shape arithmetic overflows.

Source

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

Tensor shape.

§Examples
use tenferro_tensor::{Tensor, TypedTensor};

let t = Tensor::from_typed(TypedTensor::from_vec_col_major(vec![2], vec![1.0, 2.0]).unwrap());
assert_eq!(t.shape(), &[2]);
Source

pub fn dtype(&self) -> DType

Tensor dtype tag.

§Examples
use tenferro_tensor::{DType, Tensor, TypedTensor};

let t = Tensor::from_typed(TypedTensor::from_vec_col_major(vec![], vec![1.0]).unwrap());
assert_eq!(t.dtype(), DType::F64);
Source

pub fn placement(&self) -> &Placement

Return placement metadata for this dtype-erased tensor.

§Examples
use tenferro_tensor::{MemoryKind, Tensor};

let t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
assert_eq!(t.placement().memory_kind, MemoryKind::UnpinnedHost);
Source

pub fn is_backend_buffer(&self) -> bool

Return whether this tensor is backed by backend-native storage.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
assert!(!t.is_backend_buffer());
Source

pub fn layout_linear_offset(&self, indices: &[usize]) -> Result<usize, Error>

Compute the physical element offset for a logical index.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert_eq!(t.layout_linear_offset(&[1])?, 1);
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::RankMismatch when indices has the wrong rank, tenferro_tensor_core::ValidationError::InvalidArgument when an index is outside its axis extent, or tenferro_tensor_core::ValidationError::IntegerOverflow when offset arithmetic overflows.

Source

pub fn is_col_major_contiguous(&self) -> Result<bool, Error>

Return whether this tensor is compact column-major.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert!(t.is_col_major_contiguous()?);
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::IntegerOverflow when compactness arithmetic overflows.

Source

pub fn layout_summary(&self) -> String

Return a compact string summary of this tensor’s layout metadata.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert!(t.layout_summary().contains("shape=[2]"));
Source

pub fn assert_col_major_contiguous(&self) -> Result<(), Error>

Assert this tensor is compact column-major.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
t.assert_col_major_contiguous()?;
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::IntegerOverflow when compactness arithmetic overflows, or tenferro_tensor_core::ValidationError::InvalidArgument when the tensor is not compact column-major.

Source

pub fn as_slice<T>(&self) -> Result<&[T], Error>
where T: TensorScalar,

Try to borrow the host data as a typed slice.

Returns an error if the tensor dtype does not match T.

§Examples
use tenferro_tensor::{Tensor, TypedTensor};

let t = Tensor::from_typed(TypedTensor::from_vec_col_major(vec![3], vec![1.0, 2.0, 3.0]).unwrap());
assert_eq!(t.as_slice::<f64>().unwrap(), [1.0, 2.0, 3.0].as_slice());
assert!(t.as_slice::<f32>().is_err());
§Errors

Returns crate::Error::Validation with tenferro_tensor_core::ValidationError::DTypeMismatch when T does not match the tensor dtype, or crate::Error::RuntimeState when the matching tensor uses backend storage that has not been downloaded.

Source

pub fn as_typed<T>(&self) -> Option<&TypedTensor<T>>
where T: TensorScalar,

Borrow the typed tensor when the requested scalar matches this tensor’s dtype.

This is the accessor tag-based dispatch needs: it recovers the typed tensor — and with it the device buffer — from a value whose element type is only known at run time, so a caller can dispatch on Tensor::dtype instead of matching every variant. An externally defined scalar is not a typed tensor, so it returns None rather than guessing a representation.

§Examples
use tenferro_tensor::Tensor;

let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert!(tensor.as_typed::<f64>().is_some());
assert!(tensor.as_typed::<f32>().is_none());
assert_eq!(tensor.as_typed::<f64>().unwrap().shape(), &[2]);
Source

pub fn as_typed_mut<T>(&mut self) -> Option<&mut TypedTensor<T>>
where T: TensorScalar,

Mutably borrow the typed tensor when the requested scalar matches this tensor’s dtype.

This is the mutable half of Tensor::as_typed, for the tables whose arm calls a method that needs &mut, such as marking a freshly allocated output with its placement. An externally defined scalar is not a typed tensor, so it returns None for the same reason.

§Examples
use tenferro_tensor::Tensor;

let mut tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert!(tensor.as_typed_mut::<f64>().is_some());
assert!(tensor.as_typed_mut::<f32>().is_none());
Source

pub fn into_typed<T>(self) -> Result<TypedTensor<T>, ReinterpretError<Tensor>>
where T: TensorScalar,

Consume this tensor and return the owned typed tensor when the dtype matches.

This is the consuming counterpart of Tensor::as_typed, for the tables whose arm hands the typed tensor to a function that takes it by value — reusing its buffer rather than copying it.

§Examples
use tenferro_tensor::Tensor;

let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
assert!(tensor.into_typed::<f64>().is_ok());

let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f32, 2.0])?;
assert!(tensor.into_typed::<f64>().is_err());
§Errors

Returns ReinterpretError carrying the unchanged tensor when T is not this tensor’s dtype, with crate::Error::Validation and tenferro_tensor_core::ValidationError::DTypeMismatch as the cause. A matching tensor is handed over as it is, including one whose storage lives in a backend buffer.

Source

pub fn into_vec_col_major<T>( self, ) -> Result<(Vec<usize>, Vec<T>), ReinterpretError<Tensor>>
where T: TensorScalar,

Consume this tensor and return its owned column-major buffer when the dtype matches.

§Examples
use tenferro_tensor::Tensor;

let t = Tensor::from_vec_col_major(vec![1], vec![2.0_f64]).unwrap();
assert_eq!(t.into_vec_col_major::<f64>().unwrap().1, vec![2.0]);
§Errors

Returns ReinterpretError carrying the unchanged tensor when T does not match the tensor dtype or when the matching tensor uses backend storage that has not been downloaded.

Trait Implementations§

Source§

impl Debug for Tensor

Source§

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

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

impl From<TypedTensor<Complex<f32>>> for Tensor

Wrap a Complex32 TypedTensor into the corresponding Tensor variant.

§Examples

use num_complex::Complex32;
use tenferro_tensor::{Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(
    vec![1],
    vec![Complex32::new(1.0, 2.0)],
).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.shape(), &[1]);
Source§

fn from(t: TypedTensor<Complex<f32>>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<Complex<f64>>> for Tensor

Wrap a Complex64 TypedTensor into the corresponding Tensor variant.

§Examples

use num_complex::Complex64;
use tenferro_tensor::{Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(
    vec![1],
    vec![Complex64::new(1.0, 2.0)],
).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.shape(), &[1]);
Source§

fn from(t: TypedTensor<Complex<f64>>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<bool>> for Tensor

Wrap a bool TypedTensor into the corresponding Tensor variant.

§Examples

use tenferro_tensor::{DType, Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(vec![2], vec![true, false]).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.dtype(), DType::Bool);
assert_eq!(tensor.shape(), &[2]);
Source§

fn from(t: TypedTensor<bool>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<f32>> for Tensor

Wrap an f32 TypedTensor into the corresponding Tensor variant.

§Examples

use tenferro_tensor::{Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(vec![2], vec![1.0_f32, 2.0]).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.shape(), &[2]);
Source§

fn from(t: TypedTensor<f32>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<f64>> for Tensor

Wrap an f64 TypedTensor into the corresponding Tensor variant.

§Examples

use tenferro_tensor::{Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.shape(), &[2]);
Source§

fn from(t: TypedTensor<f64>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<i32>> for Tensor

Wrap an i32 TypedTensor into the corresponding Tensor variant.

§Examples

use tenferro_tensor::{DType, Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(vec![2], vec![1_i32, 2]).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.dtype(), DType::I32);
assert_eq!(tensor.shape(), &[2]);
Source§

fn from(t: TypedTensor<i32>) -> Tensor

Converts to this type from the input type.
Source§

impl From<TypedTensor<i64>> for Tensor

Wrap an i64 TypedTensor into the corresponding Tensor variant.

§Examples

use tenferro_tensor::{DType, Tensor, TypedTensor};

let typed = TypedTensor::from_vec_col_major(vec![2], vec![1_i64, 2]).unwrap();
let tensor: Tensor = typed.into();
assert_eq!(tensor.dtype(), DType::I64);
assert_eq!(tensor.shape(), &[2]);
Source§

fn from(t: TypedTensor<i64>) -> Tensor

Converts to this type from the input type.
Source§

impl TensorSessionOpsExt for Tensor

Source§

fn add(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise addition with NumPy-style broadcasting inside a session. Read more
Source§

fn mul(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise multiplication with NumPy-style broadcasting inside a session. Read more
Source§

fn exp(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise exponential inside a session. Read more
Source§

fn reduce_sum( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Sum over the selected axes inside a session. None reduces every axis and Some(&[]) keeps the input shape, as in the eager and traced reduction family. Read more
Source§

fn convert(&self, to: DType, session: &mut dyn BackendSession) -> Result<Tensor>

Convert to a different dtype using the checked conversion lattice inside a session. Read more
Source§

fn cast(&self, to: DType, session: &mut dyn BackendSession) -> Result<Tensor>

Cast to a different dtype using explicit lossy projection inside a session. Read more
Source§

fn sub(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise subtraction with NumPy-style broadcasting inside a session. Read more
Source§

fn div(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise division with NumPy-style broadcasting inside a session. Read more
Source§

fn rem(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise remainder with NumPy-style broadcasting inside a session. Read more
Source§

fn pow(&self, rhs: &Tensor, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise power with NumPy-style broadcasting inside a session. Read more
Source§

fn maximum( &self, rhs: &Tensor, session: &mut dyn BackendSession, ) -> Result<Tensor>

Elementwise maximum with NumPy-style broadcasting inside a session. Read more
Source§

fn minimum( &self, rhs: &Tensor, session: &mut dyn BackendSession, ) -> Result<Tensor>

Elementwise minimum with NumPy-style broadcasting inside a session. Read more
Source§

fn neg(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise negation inside a session. Read more
Source§

fn abs(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise absolute value inside a session. Read more
Source§

fn sign(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise sign inside a session. Read more
Source§

fn conj(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise complex conjugate inside a session. Read more
Source§

fn log(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise natural logarithm inside a session. Read more
Source§

fn expm1(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise exp(x) - 1 inside a session. Read more
Source§

fn log1p(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise log(1 + x) inside a session. Read more
Source§

fn erf(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise error function erf(x) inside a session, for real F32/F64. Read more
Source§

fn sin(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise sine inside a session. Read more
Source§

fn cos(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise cosine inside a session. Read more
Source§

fn tanh(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise hyperbolic tangent inside a session. Read more
Source§

fn sqrt(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise square root inside a session. Read more
Source§

fn rsqrt(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Elementwise reciprocal square root inside a session. Read more
Source§

fn compare( &self, rhs: &Tensor, dir: CompareDir, session: &mut dyn BackendSession, ) -> Result<Tensor>

Elementwise comparison with NumPy-style broadcasting inside a session. Read more
Source§

fn where_select( &self, on_true: &Tensor, on_false: &Tensor, session: &mut dyn BackendSession, ) -> Result<Tensor>

Select values from on_true or on_false using this tensor as condition inside a session. Read more
Source§

fn clamp( &self, lower: &Tensor, upper: &Tensor, session: &mut dyn BackendSession, ) -> Result<Tensor>

Clamp values elementwise between lower and upper bounds inside a session. Read more
Source§

fn matmul( &self, rhs: &Tensor, session: &mut dyn BackendSession, ) -> Result<Tensor>

Rank-2 matrix multiplication inside a session. Read more
Source§

fn reshape( &self, shape: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor>

Reshape without changing element order inside a session. Read more
Source§

fn transpose( &self, perm: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor>

Permute axes inside a session. Read more
Source§

fn gather( &self, indices: &Tensor, config: GatherConfig, session: &mut dyn BackendSession, ) -> Result<Tensor>

Gather slices of this tensor at indices inside a session (StableHLO gather). Read more
Source§

fn scatter( &self, indices: &Tensor, updates: &Tensor, config: ScatterConfig, session: &mut dyn BackendSession, ) -> Result<Tensor>

Scatter updates into a copy of this tensor at indices inside a session (StableHLO scatter). Read more
Source§

fn slice( &self, config: SliceConfig, session: &mut dyn BackendSession, ) -> Result<Tensor>

Slice this tensor with explicit start, limit and stride per axis inside a session. Read more
Source§

fn dynamic_slice( &self, starts: &Tensor, sizes: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor>

Slice this tensor at runtime starts (an integer tensor) with static sizes inside a session. Read more
Source§

fn pad( &self, config: PadConfig, session: &mut dyn BackendSession, ) -> Result<Tensor>

Pad this tensor with zeros (edge and interior padding per axis) inside a session. Read more
Source§

fn concatenate( inputs: &[&Tensor], axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Concatenate tensors along axis inside a session. Read more
Source§

fn reverse( &self, axes: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor>

Reverse the elements along axes inside a session. Read more
Source§

fn reduce_max( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Take the maximum over the selected axes inside a session. None reduces every axis and Some(&[]) keeps the input shape. Read more
Source§

fn reduce_min( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Take the minimum over the selected axes inside a session. None reduces every axis and Some(&[]) keeps the input shape. Read more
Source§

fn reduce_prod( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Multiply over the selected axes inside a session. None reduces every axis and Some(&[]) keeps the input shape. Read more
Source§

fn reduce_sum_squares( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Sum elementwise squares over the selected axes inside a session (f32/f64). None reduces every axis and Some(&[]) keeps the input shape. Read more
Source§

fn broadcast_in_dim( &self, shape: &[usize], dims: &[usize], session: &mut dyn BackendSession, ) -> Result<Tensor>

Broadcast this tensor into shape, mapping input axis i to output axis dims[i], inside a session. Read more
Source§

fn tril(&self, k: i64, session: &mut dyn BackendSession) -> Result<Tensor>

Keep the lower triangle (on and below diagonal k) of the trailing matrix axes inside a session. Read more
Source§

fn triu(&self, k: i64, session: &mut dyn BackendSession) -> Result<Tensor>

Keep the upper triangle (on and above diagonal k) of the trailing matrix axes inside a session. Read more
Source§

fn extract_diag( &self, axis_a: usize, axis_b: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Extract the diagonal along axis_a and axis_b inside a session. Read more
Source§

fn embed_diag( &self, axis_a: usize, axis_b: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Embed this tensor along the diagonal of axis_a and axis_b inside a session. Read more
Source§

fn dot_general( &self, rhs: &Tensor, config: DotGeneralConfig, session: &mut dyn BackendSession, ) -> Result<Tensor>

Contract this tensor with rhs inside a session (StableHLO dot_general). Read more
Source§

fn dot_general_with_conj( &self, rhs: &Tensor, config: DotGeneralConfig, lhs_conj: bool, rhs_conj: bool, session: &mut dyn BackendSession, ) -> Result<Tensor>

Contract with optional conjugation of either operand inside a session. Read more
Source§

fn scale_real( &self, factor: f64, session: &mut dyn BackendSession, ) -> Result<Tensor>

Multiply by a real scalar inside a session, with the eager scale_real dtype rules. Read more
Source§

fn scale_complex( &self, factor: Complex64, session: &mut dyn BackendSession, ) -> Result<Tensor>

Multiply a complex tensor by a complex scalar inside a session. Read more
Source§

fn sigmoid(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Logistic sigmoid 1 / (1 + exp(-x)) inside a session, overflow-free. Read more
Source§

fn silu(&self, session: &mut dyn BackendSession) -> Result<Tensor>

SiLU (swish) x * sigmoid(x) inside a session. Read more
Source§

fn softplus(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Softplus log(1 + exp(x)) inside a session, in the stable form max(x, 0) + log1p(exp(-|x|)). Read more
Source§

fn gelu(&self, session: &mut dyn BackendSession) -> Result<Tensor>

Exact GELU x/2 * (1 + erf(x / sqrt(2))) inside a session. Read more
Source§

fn gelu_tanh(&self, session: &mut dyn BackendSession) -> Result<Tensor>

GELU tanh approximation inside a session (PyTorch approximate="tanh"). Read more
Source§

fn reduce_mean( &self, axes: Option<&[usize]>, session: &mut dyn BackendSession, ) -> Result<Tensor>

Arithmetic mean over axes inside a session (None reduces every axis). Read more
Source§

fn softmax( &self, axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Max-subtracted softmax along axis inside a session. Read more
Source§

fn log_softmax( &self, axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Max-subtracted log-softmax along axis inside a session. Read more
Source§

fn masked_softmax( &self, mask: &Tensor, axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Softmax along axis over the entries where the Bool mask is true. Read more
Source§

fn masked_log_softmax( &self, mask: &Tensor, axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

Log-softmax along axis over the entries where the Bool mask is true. Read more
Source§

fn layer_norm( &self, axis: usize, weight: Option<&Tensor>, bias: Option<&Tensor>, eps: f64, session: &mut dyn BackendSession, ) -> Result<Tensor>

Layer normalization along axis with optional affine weight / bias, inside a session. Read more
Source§

fn rms_norm( &self, axis: usize, weight: Option<&Tensor>, bias: Option<&Tensor>, eps: f64, session: &mut dyn BackendSession, ) -> Result<Tensor>

RMS normalization along axis with optional affine weight / bias, inside a session. Read more
Source§

fn take_along_axis( &self, indices: &Tensor, axis: usize, session: &mut dyn BackendSession, ) -> Result<Tensor>

NumPy-style take_along_axis over gather, inside a session. Read more

Auto Trait Implementations§

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