Skip to main content

Tensor

Struct Tensor 

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

Enhanced Tensor implementation with Candle backend.

Implementations§

Source§

impl Tensor

Convenience functions for arithmetic operations.

Source

pub fn clamp(&self, min: f32, max: f32) -> Result<Tensor>

Clamp tensor values between min and max.

Source

pub fn relu(&self) -> Result<Tensor>

Apply ReLU activation function.

Source

pub fn sigmoid(&self) -> Result<Tensor>

Apply Sigmoid activation function.

Source

pub fn tanh(&self) -> Result<Tensor>

Apply Tanh activation function.

Source

pub fn gelu(&self) -> Result<Tensor>

Apply GELU activation function.

Source§

impl Tensor

Additional matrix operations as methods on Tensor.

Source

pub fn trace(&self) -> Result<Tensor>

Compute the trace (sum of diagonal elements) of a 2D tensor.

Source

pub fn diagonal(&self) -> Result<Tensor>

Get the diagonal elements of a 2D tensor.

Source

pub fn eye(size: usize, dtype: DataType, layout: TensorLayout) -> Result<Tensor>

Create an identity matrix of given size.

Source

pub fn det(&self) -> Result<Tensor>

Compute the determinant of a 2D square tensor.

Source

pub fn inverse(&self) -> Result<Tensor>

Compute matrix inverse (for 2x2 matrices only in this implementation).

Source

pub fn frobenius_norm(&self) -> Result<Tensor>

Compute the Frobenius norm of the tensor.

Source

pub fn diag_embed(&self) -> Result<Tensor>

Create a tensor with ones on the diagonal and zeros elsewhere.

Source§

impl Tensor

Additional reduction methods for convenience.

Source

pub fn sum_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Sum along a single dimension.

Source

pub fn mean_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Mean along a single dimension.

Source

pub fn max_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Maximum along a single dimension.

Source

pub fn min_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Minimum along a single dimension.

Source

pub fn argmax(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Find indices of maximum values along a dimension.

Source

pub fn argmin(&self, dim: usize, keep_dim: bool) -> Result<Tensor>

Find indices of minimum values along a dimension.

Source

pub fn count_nonzero(&self) -> Result<usize>

Count non-zero elements.

Source

pub fn count_nonzero_dim(&self, dim: usize) -> Result<Tensor>

Count elements along a dimension.

Source

pub fn cumsum(&self, dim: usize) -> Result<Tensor>

Cumulative sum along a dimension.

Source

pub fn cumprod(&self, dim: usize) -> Result<Tensor>

Cumulative product along a dimension.

Source

pub fn softmax(&self, dim: usize) -> Result<Tensor>

Softmax operation along a dimension.

Source

pub fn log_softmax(&self, dim: usize) -> Result<Tensor>

Log softmax operation along a dimension.

Source§

impl Tensor

Additional shape manipulation methods.

Source

pub fn chunk(&self, chunks: usize, dim: usize) -> Result<Vec<Tensor>>

Split the tensor into chunks along a specific dimension.

Source

pub fn slice(&self, dim: usize, start: usize, end: usize) -> Result<Tensor>

Slice the tensor along a specific dimension.

Source

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

Concatenate tensors along a specific dimension.

Source

pub fn repeat(&self, repeats: &[usize]) -> Result<Tensor>

Repeat the tensor along specified dimensions.

Source

pub fn tile(&self, multiples: &[usize]) -> Result<Tensor>

Tile the tensor with the given multiples.

Source

pub fn pad_zeros(&self, padding: &[(usize, usize)]) -> Result<Tensor>

Pad the tensor with zeros.

Source§

impl Tensor

Source

pub fn from_data( data: Vec<f32>, shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>

Create a new tensor from raw data.

§Arguments
  • data - Raw tensor data
  • shape - Tensor dimensions
  • dtype - Data type specification
  • layout - Memory layout preference
§Example
use ronn_core::tensor::Tensor;
use ronn_core::types::{DataType, TensorLayout};

let data = vec![1.0, 2.0, 3.0, 4.0];
let tensor = Tensor::from_data(data, vec![2, 2], DataType::F32, TensorLayout::RowMajor)?;
Source

pub fn zeros( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>

Create a tensor filled with zeros.

§Arguments
  • shape - Tensor dimensions
  • dtype - Data type specification
  • layout - Memory layout preference
Source

pub fn ones( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>

Create a tensor filled with ones.

§Arguments
  • shape - Tensor dimensions
  • dtype - Data type specification
  • layout - Memory layout preference
Source

pub fn rand( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>

Create a tensor with random values from a uniform distribution.

Source

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

Get the shape of the tensor.

Source

pub fn dtype(&self) -> DataType

Get the data type of the tensor.

Source

pub fn layout(&self) -> TensorLayout

Get the memory layout of the tensor.

Source

pub fn ndim(&self) -> usize

Get the number of dimensions.

Source

pub fn numel(&self) -> usize

Get the total number of elements.

Source

pub fn device(&self) -> &Device

Get the device where the tensor is stored.

Source

pub fn to_cpu(&self) -> Result<Self>

Convert tensor to CPU device.

Source

pub fn to_vec(&self) -> Result<Vec<f32>>

Extract data as a vector of f32 values.

Source

pub fn candle_tensor(&self) -> &CandleTensor

Get the underlying Candle tensor for advanced operations.

Source

pub fn from_candle( candle_tensor: CandleTensor, dtype: DataType, layout: TensorLayout, ) -> Self

Create a Tensor from a Candle tensor.

Source

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

Check if tensor shapes are broadcastable.

Source

pub fn broadcast_shape(shape1: &[usize], shape2: &[usize]) -> Result<Vec<usize>>

Compute broadcast shape for two tensors.

Source

pub fn conv2d( &self, weight: &Tensor, bias: Option<&Tensor>, strides: &[usize], pads: &[usize], dilations: &[usize], groups: usize, ) -> Result<Tensor>

Convolution 2D operation (placeholder - uses Candle’s conv2d).

Source

pub fn max_pool2d( &self, kernel_shape: &[usize], strides: &[usize], pads: &[usize], ) -> Result<Tensor>

Max pooling 2D operation.

Source

pub fn avg_pool2d( &self, kernel_shape: &[usize], strides: &[usize], pads: &[usize], ) -> Result<Tensor>

Average pooling 2D operation.

Source

pub fn batch_norm( &self, scale: &Tensor, bias: &Tensor, mean: &Tensor, var: &Tensor, epsilon: f32, ) -> Result<Tensor>

Batch normalization operation.

Source

pub fn rank(&self) -> usize

Get rank (number of dimensions).

Source

pub fn to_vec1<T: WithDType>(&self) -> Result<Vec<T>>

Convert to 1D vector (alias for to_vec).

Source

pub fn stack(tensors: &[&Tensor], dim: usize) -> Result<Self>

Stack tensors along a new dimension.

§Arguments
  • tensors - Slice of tensors to stack
  • dim - Dimension along which to stack
§Example
use ronn_core::tensor::Tensor;
use ronn_core::types::{DataType, TensorLayout};

let t1 = Tensor::from_data(vec![1.0, 2.0], vec![2], DataType::F32, TensorLayout::RowMajor)?;
let t2 = Tensor::from_data(vec![3.0, 4.0], vec![2], DataType::F32, TensorLayout::RowMajor)?;
let stacked = Tensor::stack(&[&t1, &t2], 0)?;
assert_eq!(stacked.shape(), vec![2, 2]);
Source

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

Split tensor into chunks along an axis.

§Arguments
  • num_chunks - Number of chunks to split into
  • dim - Dimension along which to split
§Example
use ronn_core::tensor::Tensor;
use ronn_core::types::{DataType, TensorLayout};

let t = Tensor::from_data(
    vec![1.0, 2.0, 3.0, 4.0],
    vec![2, 2],
    DataType::F32,
    TensorLayout::RowMajor
)?;
let chunks = t.split(2, 0)?;
assert_eq!(chunks.len(), 2);
Source

pub fn gather(&self, indices: &Tensor, dim: usize) -> Result<Tensor>

Gather elements along an axis.

Source

pub fn transpose(&self, perm: &[usize]) -> Result<Tensor>

Transpose with specific permutation.

Source

pub fn layer_norm( &self, scale: Option<&Tensor>, bias: Option<&Tensor>, epsilon: f32, axis: i32, ) -> Result<Self>

Layer normalization (critical for transformers).

Normalizes the input across the specified axis.

§Arguments
  • scale - Optional scale parameter (gamma)
  • bias - Optional bias parameter (beta)
  • epsilon - Small constant for numerical stability
  • axis - Axis to normalize over (default: -1 for last dimension)
§Example
use ronn_core::tensor::Tensor;
use ronn_core::types::{DataType, TensorLayout};

let input = Tensor::from_data(
    vec![1.0, 2.0, 3.0, 4.0],
    vec![2, 2],
    DataType::F32,
    TensorLayout::RowMajor
)?;
let normalized = input.layer_norm(None, None, 1e-5, 1)?;  // Use positive axis
Source

pub fn attention( &self, key: &Tensor, value: &Tensor, num_heads: usize, mask: Option<&Tensor>, ) -> Result<Self>

Multi-head attention mechanism (critical for transformers).

Computes scaled dot-product attention: softmax(Q·K^T / sqrt(d_k))·V

§Arguments
  • key - Key tensor
  • value - Value tensor
  • num_heads - Number of attention heads
  • mask - Optional attention mask
§Example
use ronn_core::tensor::Tensor;
use ronn_core::types::{DataType, TensorLayout};

let query = Tensor::from_data(
    vec![1.0; 64],
    vec![1, 8, 8],  // (batch, seq_len, d_model)
    DataType::F32,
    TensorLayout::RowMajor
)?;
let key = query.clone();
let value = query.clone();

let output = query.attention(&key, &value, 2, None)?;
Source

pub fn clip(&self, min: f32, max: f32) -> Result<Self>

Clip values to a range [min, max]

Source

pub fn pow_tensor(&self, exponent: &Tensor) -> Result<Self>

Element-wise power operation with tensor exponent. For scalar exponents, use the ArithmeticOps::pow trait method instead.

Source

pub fn sqrt(&self) -> Result<Self>

Element-wise square root

Source

pub fn exp(&self) -> Result<Self>

Element-wise exponential (e^x)

Source

pub fn log(&self) -> Result<Self>

Element-wise natural logarithm

Source

pub fn neg(&self) -> Result<Self>

Element-wise negation

Source

pub fn abs(&self) -> Result<Self>

Element-wise absolute value

Source

pub fn leaky_relu(&self, alpha: f32) -> Result<Self>

LeakyReLU activation: max(alpha * x, x)

Source

pub fn elu(&self, alpha: f32) -> Result<Self>

ELU activation: x if x > 0 else alpha * (exp(x) - 1)

Source

pub fn swish(&self) -> Result<Self>

Swish/SiLU activation: x * sigmoid(x)

Source

pub fn squeeze(&self, axes: Option<Vec<usize>>) -> Result<Self>

Remove dimensions of size 1

Source

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

Add dimensions of size 1

Source

pub fn reduce_mean(&self, axes: &[usize], keepdims: bool) -> Result<Self>

Reduce mean along axes

Source

pub fn reduce_sum(&self, axes: &[usize], keepdims: bool) -> Result<Self>

Reduce sum along axes

Source

pub fn cast(&self, to: DataType) -> Result<Self>

Cast tensor to a different data type

Source

pub fn to_scalar_f32(&self) -> Result<f32>

Convert tensor to a scalar f32 value

Trait Implementations§

Source§

impl ArithmeticOps for Tensor

Source§

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

Element-wise addition with broadcasting.
Source§

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

Element-wise subtraction with broadcasting.
Source§

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

Element-wise multiplication with broadcasting.
Source§

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

Element-wise division with broadcasting.
Source§

fn add_scalar(&self, scalar: f32) -> Result<Tensor>

Add a scalar to all elements.
Source§

fn sub_scalar(&self, scalar: f32) -> Result<Tensor>

Subtract a scalar from all elements.
Source§

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

Multiply all elements by a scalar.
Source§

fn div_scalar(&self, scalar: f32) -> Result<Tensor>

Divide all elements by a scalar.
Source§

fn neg(&self) -> Result<Tensor>

Element-wise negation.
Source§

fn abs(&self) -> Result<Tensor>

Element-wise absolute value.
Source§

fn pow(&self, exponent: f32) -> Result<Tensor>

Element-wise power operation.
Source§

fn sqrt(&self) -> Result<Tensor>

Element-wise square root.
Source§

fn exp(&self) -> Result<Tensor>

Element-wise exponential.
Source§

fn log(&self) -> Result<Tensor>

Element-wise natural logarithm.
Source§

impl Clone for Tensor

Source§

fn clone(&self) -> Tensor

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

Source§

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

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

impl From<Tensor> for Tensor

Convert legacy RonnTensor to new Tensor implementation.

Source§

fn from(legacy: RonnTensor) -> Self

Converts to this type from the input type.
Source§

impl From<Tensor> for Tensor

Convert new Tensor to legacy RonnTensor for compatibility.

Source§

fn from(tensor: Tensor) -> Self

Converts to this type from the input type.
Source§

impl MatrixOps for Tensor

Source§

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

Matrix multiplication.
Source§

fn transpose(&self) -> Result<Tensor>

Transpose the tensor (swap last two dimensions).
Source§

fn transpose_dims(&self, dim1: usize, dim2: usize) -> Result<Tensor>

Transpose with specific dimension indices.
Source§

fn batch_matmul(&self, other: &Tensor) -> Result<Tensor>

Batch matrix multiplication.
Source§

impl ReductionOps for Tensor

Source§

fn sum_all(&self) -> Result<Tensor>

Sum all elements in the tensor.
Source§

fn sum_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>

Sum along specified dimensions.
Source§

fn mean_all(&self) -> Result<Tensor>

Mean of all elements in the tensor.
Source§

fn mean_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>

Mean along specified dimensions.
Source§

fn max_all(&self) -> Result<Tensor>

Maximum value in the tensor.
Source§

fn max_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>

Maximum along specified dimensions.
Source§

fn min_all(&self) -> Result<Tensor>

Minimum value in the tensor.
Source§

fn min_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>

Minimum along specified dimensions.
Source§

fn prod_all(&self) -> Result<Tensor>

Product of all elements.
Source§

fn std_all(&self) -> Result<Tensor>

Standard deviation of all elements.
Source§

fn var_all(&self) -> Result<Tensor>

Variance of all elements.
Source§

fn norm(&self) -> Result<Tensor>

L2 norm (Euclidean norm) of the tensor.
Source§

fn norm_p(&self, p: f32) -> Result<Tensor>

Lp norm of the tensor.
Source§

impl ShapeOps for Tensor

Source§

fn reshape(&self, new_shape: &[usize]) -> Result<Tensor>

Reshape the tensor to a new shape.
Source§

fn flatten(&self) -> Result<Tensor>

Flatten the tensor to 1D.
Source§

fn flatten_from(&self, start_dim: usize) -> Result<Tensor>

Flatten starting from a specific dimension.
Source§

fn squeeze(&self) -> Result<Tensor>

Remove dimensions of size 1.
Source§

fn squeeze_dim(&self, dim: usize) -> Result<Tensor>

Remove a specific dimension of size 1.
Source§

fn unsqueeze(&self, dim: usize) -> Result<Tensor>

Add a dimension of size 1.
Source§

fn permute(&self, dims: &[usize]) -> Result<Tensor>

Permute the dimensions of the tensor.
Source§

fn expand(&self, new_shape: &[usize]) -> Result<Tensor>

Expand the tensor to a new shape (broadcasting).
Source§

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

View the tensor with a new shape (no data copy).

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§

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

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> ErasedDestructor for T
where T: 'static,