pub struct Tensor { /* private fields */ }Expand description
Enhanced Tensor implementation with Candle backend.
Implementations§
Source§impl Tensor
Convenience functions for arithmetic operations.
impl Tensor
Convenience functions for arithmetic operations.
Source§impl Tensor
Additional matrix operations as methods on Tensor.
impl Tensor
Additional matrix operations as methods on Tensor.
Sourcepub fn trace(&self) -> Result<Tensor>
pub fn trace(&self) -> Result<Tensor>
Compute the trace (sum of diagonal elements) of a 2D tensor.
Sourcepub fn eye(size: usize, dtype: DataType, layout: TensorLayout) -> Result<Tensor>
pub fn eye(size: usize, dtype: DataType, layout: TensorLayout) -> Result<Tensor>
Create an identity matrix of given size.
Sourcepub fn inverse(&self) -> Result<Tensor>
pub fn inverse(&self) -> Result<Tensor>
Compute matrix inverse (for 2x2 matrices only in this implementation).
Sourcepub fn frobenius_norm(&self) -> Result<Tensor>
pub fn frobenius_norm(&self) -> Result<Tensor>
Compute the Frobenius norm of the tensor.
Sourcepub fn diag_embed(&self) -> Result<Tensor>
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.
impl Tensor
Additional reduction methods for convenience.
Sourcepub fn sum_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn sum_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Sum along a single dimension.
Sourcepub fn mean_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn mean_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Mean along a single dimension.
Sourcepub fn max_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn max_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Maximum along a single dimension.
Sourcepub fn min_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn min_dim(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Minimum along a single dimension.
Sourcepub fn argmax(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn argmax(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Find indices of maximum values along a dimension.
Sourcepub fn argmin(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
pub fn argmin(&self, dim: usize, keep_dim: bool) -> Result<Tensor>
Find indices of minimum values along a dimension.
Sourcepub fn count_nonzero(&self) -> Result<usize>
pub fn count_nonzero(&self) -> Result<usize>
Count non-zero elements.
Sourcepub fn count_nonzero_dim(&self, dim: usize) -> Result<Tensor>
pub fn count_nonzero_dim(&self, dim: usize) -> Result<Tensor>
Count elements along a dimension.
Sourcepub fn log_softmax(&self, dim: usize) -> Result<Tensor>
pub fn log_softmax(&self, dim: usize) -> Result<Tensor>
Log softmax operation along a dimension.
Source§impl Tensor
Additional shape manipulation methods.
impl Tensor
Additional shape manipulation methods.
Sourcepub fn chunk(&self, chunks: usize, dim: usize) -> Result<Vec<Tensor>>
pub fn chunk(&self, chunks: usize, dim: usize) -> Result<Vec<Tensor>>
Split the tensor into chunks along a specific dimension.
Sourcepub fn slice(&self, dim: usize, start: usize, end: usize) -> Result<Tensor>
pub fn slice(&self, dim: usize, start: usize, end: usize) -> Result<Tensor>
Slice the tensor along a specific dimension.
Sourcepub fn concat(tensors: &[&Tensor], dim: usize) -> Result<Tensor>
pub fn concat(tensors: &[&Tensor], dim: usize) -> Result<Tensor>
Concatenate tensors along a specific dimension.
Sourcepub fn repeat(&self, repeats: &[usize]) -> Result<Tensor>
pub fn repeat(&self, repeats: &[usize]) -> Result<Tensor>
Repeat the tensor along specified dimensions.
Source§impl Tensor
impl Tensor
Sourcepub fn from_data(
data: Vec<f32>,
shape: Vec<usize>,
dtype: DataType,
layout: TensorLayout,
) -> Result<Self>
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 datashape- Tensor dimensionsdtype- Data type specificationlayout- 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)?;Sourcepub fn zeros(
shape: Vec<usize>,
dtype: DataType,
layout: TensorLayout,
) -> Result<Self>
pub fn zeros( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>
Create a tensor filled with zeros.
§Arguments
shape- Tensor dimensionsdtype- Data type specificationlayout- Memory layout preference
Sourcepub fn ones(
shape: Vec<usize>,
dtype: DataType,
layout: TensorLayout,
) -> Result<Self>
pub fn ones( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>
Create a tensor filled with ones.
§Arguments
shape- Tensor dimensionsdtype- Data type specificationlayout- Memory layout preference
Sourcepub fn rand(
shape: Vec<usize>,
dtype: DataType,
layout: TensorLayout,
) -> Result<Self>
pub fn rand( shape: Vec<usize>, dtype: DataType, layout: TensorLayout, ) -> Result<Self>
Create a tensor with random values from a uniform distribution.
Sourcepub fn layout(&self) -> TensorLayout
pub fn layout(&self) -> TensorLayout
Get the memory layout of the tensor.
Sourcepub fn candle_tensor(&self) -> &CandleTensor
pub fn candle_tensor(&self) -> &CandleTensor
Get the underlying Candle tensor for advanced operations.
Sourcepub fn from_candle(
candle_tensor: CandleTensor,
dtype: DataType,
layout: TensorLayout,
) -> Self
pub fn from_candle( candle_tensor: CandleTensor, dtype: DataType, layout: TensorLayout, ) -> Self
Create a Tensor from a Candle tensor.
Sourcepub fn is_broadcastable_with(&self, other: &Tensor) -> bool
pub fn is_broadcastable_with(&self, other: &Tensor) -> bool
Check if tensor shapes are broadcastable.
Sourcepub fn broadcast_shape(shape1: &[usize], shape2: &[usize]) -> Result<Vec<usize>>
pub fn broadcast_shape(shape1: &[usize], shape2: &[usize]) -> Result<Vec<usize>>
Compute broadcast shape for two tensors.
Sourcepub fn conv2d(
&self,
weight: &Tensor,
bias: Option<&Tensor>,
strides: &[usize],
pads: &[usize],
dilations: &[usize],
groups: usize,
) -> Result<Tensor>
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).
Sourcepub fn max_pool2d(
&self,
kernel_shape: &[usize],
strides: &[usize],
pads: &[usize],
) -> Result<Tensor>
pub fn max_pool2d( &self, kernel_shape: &[usize], strides: &[usize], pads: &[usize], ) -> Result<Tensor>
Max pooling 2D operation.
Sourcepub fn avg_pool2d(
&self,
kernel_shape: &[usize],
strides: &[usize],
pads: &[usize],
) -> Result<Tensor>
pub fn avg_pool2d( &self, kernel_shape: &[usize], strides: &[usize], pads: &[usize], ) -> Result<Tensor>
Average pooling 2D operation.
Sourcepub fn batch_norm(
&self,
scale: &Tensor,
bias: &Tensor,
mean: &Tensor,
var: &Tensor,
epsilon: f32,
) -> Result<Tensor>
pub fn batch_norm( &self, scale: &Tensor, bias: &Tensor, mean: &Tensor, var: &Tensor, epsilon: f32, ) -> Result<Tensor>
Batch normalization operation.
Sourcepub fn stack(tensors: &[&Tensor], dim: usize) -> Result<Self>
pub fn stack(tensors: &[&Tensor], dim: usize) -> Result<Self>
Stack tensors along a new dimension.
§Arguments
tensors- Slice of tensors to stackdim- 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]);Sourcepub fn split(&self, num_chunks: usize, dim: usize) -> Result<Vec<Tensor>>
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 intodim- 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);Sourcepub fn gather(&self, indices: &Tensor, dim: usize) -> Result<Tensor>
pub fn gather(&self, indices: &Tensor, dim: usize) -> Result<Tensor>
Gather elements along an axis.
Sourcepub fn layer_norm(
&self,
scale: Option<&Tensor>,
bias: Option<&Tensor>,
epsilon: f32,
axis: i32,
) -> Result<Self>
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 stabilityaxis- 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 axisSourcepub fn attention(
&self,
key: &Tensor,
value: &Tensor,
num_heads: usize,
mask: Option<&Tensor>,
) -> Result<Self>
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 tensorvalue- Value tensornum_heads- Number of attention headsmask- 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)?;Sourcepub fn pow_tensor(&self, exponent: &Tensor) -> Result<Self>
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.
Sourcepub fn leaky_relu(&self, alpha: f32) -> Result<Self>
pub fn leaky_relu(&self, alpha: f32) -> Result<Self>
LeakyReLU activation: max(alpha * x, x)
Sourcepub fn elu(&self, alpha: f32) -> Result<Self>
pub fn elu(&self, alpha: f32) -> Result<Self>
ELU activation: x if x > 0 else alpha * (exp(x) - 1)
Sourcepub fn reduce_mean(&self, axes: &[usize], keepdims: bool) -> Result<Self>
pub fn reduce_mean(&self, axes: &[usize], keepdims: bool) -> Result<Self>
Reduce mean along axes
Sourcepub fn reduce_sum(&self, axes: &[usize], keepdims: bool) -> Result<Self>
pub fn reduce_sum(&self, axes: &[usize], keepdims: bool) -> Result<Self>
Reduce sum along axes
Sourcepub fn to_scalar_f32(&self) -> Result<f32>
pub fn to_scalar_f32(&self) -> Result<f32>
Convert tensor to a scalar f32 value
Trait Implementations§
Source§impl ArithmeticOps for Tensor
impl ArithmeticOps for Tensor
Source§impl From<Tensor> for Tensor
Convert legacy RonnTensor to new Tensor implementation.
impl From<Tensor> for Tensor
Convert legacy RonnTensor to new Tensor implementation.
Source§fn from(legacy: RonnTensor) -> Self
fn from(legacy: RonnTensor) -> Self
Source§impl MatrixOps for Tensor
impl MatrixOps for Tensor
Source§impl ReductionOps for Tensor
impl ReductionOps for Tensor
Source§fn sum_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
fn sum_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
Source§fn mean_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
fn mean_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
Source§fn max_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
fn max_dims(&self, dims: &[usize], keep_dim: bool) -> Result<Tensor>
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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