Tensor

Struct Tensor 

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

A tensor with optional gradient tracking for automatic differentiation.

§Design

The tensor stores:

  • data: The actual numerical values (backed by aprender’s Vector)
  • shape: Dimensions of the tensor
  • grad: Accumulated gradient (populated after backward())
  • requires_grad: Whether this tensor participates in gradient computation
  • grad_fn: The operation that created this tensor (for backprop)
  • id: Unique identifier for graph tracking

§Thread Safety

Tensors use Arc internally for shared ownership of gradient functions, making them safe to share across threads for inference (but not training).

Implementations§

Source§

impl Tensor

Source

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

Element-wise addition: z = self + other

Source

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

Element-wise subtraction: z = self - other

Source

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

Element-wise multiplication: z = self * other

Source

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

Element-wise division: z = self / other

Source

pub fn neg(&self) -> Tensor

Element-wise negation: z = -self

Source

pub fn mul_scalar(&self, scalar: f32) -> Tensor

Scalar multiplication: z = self * scalar

Source§

impl Tensor

Source

pub fn exp(&self) -> Tensor

Element-wise exponential: z = exp(self)

Source

pub fn log(&self) -> Tensor

Element-wise natural logarithm: z = log(self)

Source

pub fn pow(&self, n: f32) -> Tensor

Element-wise power: z = self^n

Source

pub fn sqrt(&self) -> Tensor

Element-wise square root: z = sqrt(self)

Source§

impl Tensor

Source

pub fn sum(&self) -> Tensor

Sum all elements: z = sum(self)

Source

pub fn mean(&self) -> Tensor

Mean of all elements: z = mean(self)

Source§

impl Tensor

Source

pub fn relu(&self) -> Tensor

ReLU activation: z = max(0, self)

Source

pub fn sigmoid(&self) -> Tensor

Sigmoid activation: z = 1 / (1 + exp(-self))

Source

pub fn tanh_(&self) -> Tensor

Tanh activation

Source

pub fn leaky_relu(&self, negative_slope: f32) -> Tensor

Leaky ReLU activation: z = max(negative_slope * x, x)

§Arguments
  • negative_slope - Controls the angle of the negative slope (default: 0.01)
Source

pub fn gelu(&self) -> Tensor

GELU (Gaussian Error Linear Unit) activation.

Uses the tanh approximation: GELU(x) ≈ 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x³)))

Source

pub fn softmax(&self) -> Tensor

Softmax activation over the last dimension of a 2D tensor.

softmax(x)_i = exp(x_i) / Σ_j exp(x_j)

Uses numerically stable computation with max subtraction.

Source§

impl Tensor

Source

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

Matrix multiplication: z = self @ other

Currently supports 2D tensors only. Batched matmul (3D+ tensors) can be added by iterating over batch dimensions and calling 2D matmul.

Source

pub fn transpose(&self) -> Tensor

Transpose a 2D tensor.

§Example
let a = Tensor::new(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
let a_t = a.transpose();
// a_t = [[1, 3], [2, 4]]
Source

pub fn broadcast_add(&self, other: &Tensor) -> Tensor

Broadcast addition: z = matrix + vector (broadcasts over rows).

The vector is broadcast to match the matrix’s second dimension. This is useful for adding biases in neural networks.

§Shape
  • self: [N, M] (2D matrix)
  • other: [M] (1D vector)
  • output: [N, M]
§Example
let matrix = Tensor::new(&[1.0, 2.0, 3.0, 4.0], &[2, 2]);
let bias = Tensor::new(&[10.0, 20.0], &[2]);
let result = matrix.broadcast_add(&bias);
// result = [[11, 22], [13, 24]]
Source

pub fn view(&self, new_shape: &[usize]) -> Tensor

Reshape tensor to a new shape (view).

The total number of elements must remain the same.

§Example
let a = Tensor::new(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
let b = a.view(&[3, 2]);
// b = [[1, 2], [3, 4], [5, 6]]
Source§

impl Tensor

Source

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

Create a new tensor from a slice with the given shape.

By default, gradient tracking is disabled.

§Panics

Panics if the data length doesn’t match the product of shape dimensions.

Source

pub fn from_slice(data: &[f32]) -> Self

Create a tensor from a 1D slice (vector).

Source

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

Create a tensor filled with zeros.

Source

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

Create a tensor filled with ones.

Source

pub fn zeros_like(other: &Tensor) -> Self

Create a tensor with the same shape as another, filled with zeros.

Source

pub fn ones_like(other: &Tensor) -> Self

Create a tensor with the same shape as another, filled with ones.

Source

pub fn requires_grad(self) -> Self

Enable gradient tracking for this tensor.

Returns self for method chaining.

Source

pub fn requires_grad_(&mut self, requires: bool) -> &mut Self

Enable or disable gradient tracking (in-place).

Source

pub fn requires_grad_enabled(&self) -> bool

Check if this tensor requires gradient computation.

Source

pub fn is_leaf(&self) -> bool

Check if this is a leaf tensor (not created by an operation).

Source

pub fn id(&self) -> TensorId

Get the tensor’s unique identifier.

Source

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

Get the shape of the tensor.

Source

pub fn numel(&self) -> usize

Get the total number of elements.

Source

pub fn ndim(&self) -> usize

Get the number of dimensions.

Source

pub fn data(&self) -> &[f32]

Get a reference to the underlying data.

Source

pub fn data_mut(&mut self) -> &mut [f32]

Get a mutable reference to the underlying data.

§Warning

Modifying data directly may invalidate gradients.

Source

pub fn grad(&self) -> Option<&Tensor>

Get the gradient tensor (if computed).

Source

pub fn zero_grad_(&mut self)

Zero out the gradient.

Source

pub fn clear_grad(&mut self)

Clear the gradient (alias for zero_grad_).

Source

pub fn detach(&self) -> Tensor

Detach tensor from computation graph.

Returns a new tensor with the same data but no gradient tracking.

Source

pub fn item(&self) -> f32

Get a scalar value (for 0-d or 1-element tensors).

§Panics

Panics if the tensor has more than one element.

Source

pub fn backward(&self)

Compute gradients via backpropagation.

This implements the reverse-mode automatic differentiation algorithm described in Rumelhart et al. (1986).

§Panics

Panics if called on a tensor with more than one element (use backward_with_grad for non-scalar outputs).

Source

pub fn backward_with_grad(&self, grad_output: Tensor)

Compute gradients with a specified output gradient.

§Arguments
  • grad_output - Gradient of the loss with respect to this tensor

Trait Implementations§

Source§

impl Clone for Tensor

Source§

fn clone(&self) -> Tensor

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 Debug for Tensor

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Tensor

§

impl !RefUnwindSafe for Tensor

§

impl Send for Tensor

§

impl Sync for Tensor

§

impl Unpin for Tensor

§

impl !UnwindSafe for Tensor

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.

§

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