Skip to main content

Tensor

Struct Tensor 

Source
pub struct Tensor {
    pub shape: Vec<usize>,
    pub data: Vec<f64>,
}
Expand description

N-dimensional tensor with row-major (C-contiguous) data.

Fields§

§shape: Vec<usize>

Tensor shape in row-major order.

§data: Vec<f64>

Flat row-major data buffer.

Implementations§

Source§

impl Tensor

Source

pub fn new(shape: &[usize], data: &[f64]) -> MathResult<Self>

Create a tensor from shape + data. Validates numel matches.

Source

pub fn from_vec(shape: &[usize], data: Vec<f64>) -> MathResult<Self>

Create from shape + owned data.

Source

pub fn zeros(shape: &[usize]) -> Self

Zero-filled tensor.

Source

pub fn ones(shape: &[usize]) -> Self

One-filled tensor.

Source

pub fn full(shape: &[usize], val: f64) -> Self

Fill with a constant value.

Source

pub fn scalar(val: f64) -> Self

0-dimensional scalar.

Source

pub fn arange(start: f64, stop: f64, step: f64) -> MathResult<Self>

1-D range: [start, stop) with step. Negative steps are supported.

Source

pub fn linspace(start: f64, end: f64, n: usize) -> Self

1-D linspace.

Source

pub fn randn(shape: &[usize]) -> Self

Pseudo-random normal via xorshift64. Uses persistent thread-local state so successive calls produce different values.

Source

pub fn randn_seeded(shape: &[usize], seed: u64) -> Self

Pseudo-random normal with explicit seed. Uses a local RNG state so it does not interfere with the shared thread-local state used by [randn].

Source

pub fn ndim(&self) -> usize

Number of dimensions.

Source

pub fn numel(&self) -> usize

Total number of elements.

Source

pub fn is_scalar(&self) -> bool

True if 0-dimensional.

Source

pub fn strides(&self) -> Vec<usize>

Compute strides from shape (row-major).

Source

pub fn index_to_flat(&self, coords: &[usize]) -> MathResult<usize>

Multi-index to flat offset.

Source

pub fn flat_to_index(&self, flat: usize) -> MathResult<Vec<usize>>

Flat offset to multi-index.

Source

pub fn get(&self, coords: &[usize]) -> MathResult<f64>

Get element at multi-index.

Source

pub fn get_flat(&self, idx: usize) -> f64

Get element at flat index.

Source

pub fn set(&mut self, coords: &[usize], val: f64) -> MathResult<()>

Set element at multi-index.

Source

pub fn set_flat(&mut self, idx: usize, val: f64)

Set element at flat index.

Source

pub fn as_slice(&self) -> &[f64]

Borrow data as slice.

Source

pub fn to_vec(self) -> Vec<f64>

Consume into Vec.

Source

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

Reshape (numel must match).

Source

pub fn flatten(&self) -> Self

Flatten to 1-D.

Source

pub fn transpose(&self) -> MathResult<Self>

2-D transpose.

Source

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

General axis permutation.

Source

pub fn squeeze(&self, axis: Option<usize>) -> Self

Remove size-1 dimensions (or a specific axis).

Source

pub fn unsqueeze(&self, axis: usize) -> MathResult<Self>

Add a size-1 dimension at axis.

Source

pub fn broadcast_to(&self, target_shape: &[usize]) -> MathResult<Self>

Expand to a target shape (broadcast semantics, clones data).

Source

pub fn add(&self, other: &Tensor) -> MathResult<Tensor>

Element-wise add with broadcasting.

Source

pub fn sub(&self, other: &Tensor) -> MathResult<Tensor>

Element-wise sub.

Source

pub fn mul(&self, other: &Tensor) -> MathResult<Tensor>

Element-wise mul.

Source

pub fn div(&self, other: &Tensor) -> MathResult<Tensor>

Element-wise div (safe: returns NaN for zero denominators instead of corrupting sign).

Source

pub fn add_scalar(&self, s: f64) -> Tensor

Add a scalar to every element.

Source

pub fn sub_scalar(&self, s: f64) -> Tensor

Subtract a scalar from every element.

Source

pub fn mul_scalar(&self, s: f64) -> Tensor

Multiply every element by a scalar.

Source

pub fn div_scalar(&self, s: f64) -> Tensor

Divide every element by a scalar (returns NaN for zero denominator).

Source

pub fn neg(&self) -> Tensor

Negate every element.

Source

pub fn abs(&self) -> Tensor

Absolute value of every element.

Source

pub fn sqrt(&self) -> Tensor

Square root of every element.

Source

pub fn exp(&self) -> Tensor

Exponential of every element.

Source

pub fn ln(&self) -> Tensor

Natural logarithm of every element.

Source

pub fn powf(&self, e: f64) -> Tensor

Raise every element to a floating-point exponent.

Source

pub fn clip(&self, lo: f64, hi: f64) -> Tensor

Clip values to [lo, hi].

Source

pub fn sum(&self) -> f64

Sum all elements.

Source

pub fn sum_axis(&self, axis: usize) -> MathResult<Tensor>

Sum along axis (removes that axis).

Source

pub fn mean(&self) -> f64

Mean of all elements.

Source

pub fn mean_axis(&self, axis: usize) -> MathResult<Tensor>

Mean along axis.

Source

pub fn max(&self) -> f64

Max of all elements.

Source

pub fn max_axis(&self, axis: usize) -> MathResult<Tensor>

Max along axis.

Source

pub fn min(&self) -> f64

Min of all elements.

Source

pub fn min_axis(&self, axis: usize) -> MathResult<Tensor>

Min along axis.

Source

pub fn argmax_axis(&self, axis: usize) -> MathResult<Tensor>

Argmax along axis (returns flat index per slice).

Source

pub fn argmin_axis(&self, axis: usize) -> MathResult<Tensor>

Argmin along axis.

Source

pub fn matmul(&self, other: &Tensor) -> MathResult<Tensor>

Matrix multiply: 2-D @ 2-D or batched 3-D @ 3-D.

Source

pub fn layer_norm(&self, eps: f64) -> Tensor

Layer normalization (over last dimension).

Source

pub fn batch_norm(&self, eps: f64) -> MathResult<Tensor>

Batch normalization (over first dimension).

For 2-D tensors [N, features], normalizes each feature across the batch. For 4-D tensors [N, C, H, W], normalizes per channel across N, H, W (standard image batch norm behavior).

Source

pub fn rms_norm(&self, eps: f64) -> Tensor

RMS normalization: x / sqrt(mean(x²) + eps) along last dim.

Source

pub fn where_tensor( condition: &Tensor, a: &Tensor, b: &Tensor, ) -> MathResult<Tensor>

Element-wise where: condition ? a : b.

Source

pub fn gather(&self, axis: usize, indices: &Tensor) -> MathResult<Tensor>

Gather along axis: selects from self using indices. indices has same shape as output, values are indices along axis.

§Errors

Returns MathError::OutOfRange if any index is outside [0, axis_size).

Source

pub fn scatter_add( &self, axis: usize, indices: &Tensor, src: &Tensor, ) -> MathResult<Tensor>

Scatter add: adds src into a zero tensor at positions given by indices.

§Errors

Returns MathError::OutOfRange if any index is outside [0, axis_size).

Source

pub fn topk(&self, k: usize, axis: usize) -> MathResult<(Tensor, Tensor)>

Top-k along axis: returns (values, indices) tensors.

Source

pub fn concat(tensors: &[Tensor], axis: usize) -> MathResult<Tensor>

Concatenate tensors along an axis.

Source

pub fn split(&self, num_chunks: usize, axis: usize) -> MathResult<Vec<Tensor>>

Split into chunks along axis. Last chunk absorbs any remainder.

Source

pub fn dot(&self, other: &Tensor) -> MathResult<f64>

Dot product (flattened). Errors if the tensors have different sizes.

Source

pub fn cross(&self, other: &Tensor) -> MathResult<Tensor>

Cross product (3-vectors only).

Source

pub fn clamp(&self, lo: f64, hi: f64) -> Tensor

Clamp (alias for clip).

Source

pub fn var(&self) -> f64

Variance of all elements.

Source

pub fn var_axis(&self, axis: usize) -> MathResult<Tensor>

Variance along axis.

Source

pub fn std_axis(&self, axis: usize) -> MathResult<Tensor>

Standard deviation along axis.

Source

pub fn sort(&self, axis: usize) -> MathResult<(Tensor, Tensor)>

Sort along axis (ascending), returns (sorted_values, original_indices).

Source

pub fn unique(&self) -> Vec<f64>

Unique elements (sorted, deduplicated). Exact equality only — near-but-not-equal values are kept.

Source

pub fn count_nonzero(&self) -> usize

Count non-zero elements.

Source

pub fn any(&self) -> bool

Any (true if any element > 0).

Source

pub fn all(&self) -> bool

All (true if all elements > 0).

Trait Implementations§

Source§

impl Clone for Tensor

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Tensor

Source§

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

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

impl Display for Tensor

Source§

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

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

impl PartialEq for Tensor

Source§

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

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

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

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Tensor

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> 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> 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> ToString for T
where T: Display + ?Sized,

Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.