pub type Tensor = TensorBase<Storage>;Expand description
Type alias for owned tensors with Storage backend.
This is the most common tensor type for owned data that manages its own memory allocation and cleanup.
Aliased Type§
pub struct Tensor { /* private fields */ }Implementations§
Source§impl Tensor
impl Tensor
Sourcepub fn from_scalar<T: TensorElement>(value: T) -> Result<Self>
pub fn from_scalar<T: TensorElement>(value: T) -> Result<Self>
Creates a scalar (0-dimensional) tensor from a single value.
§Parameters
value- The scalar value to store in the tensor
§Returns
A Result<Tensor> containing:
Ok(Tensor): A scalar tensor with empty dimensions[]Err: If tensor creation fails
§Examples
use slsl::Tensor;
let scalar = Tensor::from_scalar(42.0f32)?;
assert_eq!(scalar.dims(), []);
assert_eq!(scalar.to_scalar::<f32>()?, 42.0);
let int_scalar = Tensor::from_scalar(10i32)?;
assert_eq!(int_scalar.to_scalar::<i32>()?, 10);Sourcepub fn from_vec<T: TensorElement, S: Into<Shape>>(
data: Vec<T>,
shape: S,
) -> Result<Self>
pub fn from_vec<T: TensorElement, S: Into<Shape>>( data: Vec<T>, shape: S, ) -> Result<Self>
Creates a tensor from a vector with the specified shape.
Takes ownership of the vector data and reshapes it according to the given dimensions. The total number of elements in the vector must match the product of all dimensions.
§Parameters
data- Vector containing the tensor elementsshape- The desired shape/dimensions for the tensor
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor with the specified shapeErr: If the data length doesn’t match the expected shape size
§Examples
use slsl::Tensor;
// Create 2D tensor
let data = vec![1, 2, 3, 4, 5, 6];
let tensor = Tensor::from_vec(data, [2, 3])?;
assert_eq!(tensor.dims(), [2, 3]);
// Create 1D tensor
let data = vec![1.0, 2.0, 3.0];
let tensor = Tensor::from_vec(data, [3])?;
assert_eq!(tensor.dims(), [3]);§Panics
Returns an error if data.len() doesn’t equal the product of shape dimensions.
Sourcepub fn from_slice<T: TensorElement, S: Into<Shape>>(
data: &[T],
shape: S,
) -> Result<Self>
pub fn from_slice<T: TensorElement, S: Into<Shape>>( data: &[T], shape: S, ) -> Result<Self>
Creates a tensor from a slice with the specified shape.
Copies data from the slice and creates a tensor with the given dimensions. The slice length must match the product of all shape dimensions.
§Parameters
data- Slice containing the tensor elementsshape- The desired shape/dimensions for the tensor
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor with the specified shape containing copied dataErr: If the slice length doesn’t match the expected shape size
§Examples
use slsl::Tensor;
let data = [1, 2, 3, 4];
let tensor = Tensor::from_slice(&data, [2, 2])?;
assert_eq!(tensor.dims(), [2, 2]);
assert_eq!(tensor.at::<i32>([0, 1]), 2);
let data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let tensor = Tensor::from_slice(&data, [3, 2])?;
assert_eq!(tensor.dims(), [3, 2]);Sourcepub fn full<T: TensorElement>(shape: impl Into<Shape>, value: T) -> Result<Self>
pub fn full<T: TensorElement>(shape: impl Into<Shape>, value: T) -> Result<Self>
Creates a tensor filled with a specific value.
All elements in the tensor will be set to the provided value.
§Parameters
shape- The shape/dimensions of the tensor to createvalue- The value to fill all tensor elements with
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor filled with the specified valueErr: If tensor creation fails
§Examples
use slsl::Tensor;
let tensor = Tensor::full([2, 3], 7.5f32)?;
assert_eq!(tensor.dims(), [2, 3]);
assert_eq!(tensor.at::<f32>([0, 0]), 7.5);
assert_eq!(tensor.at::<f32>([1, 2]), 7.5);
let tensor = Tensor::full([4], -1i32)?;
assert_eq!(tensor.to_vec::<i32>()?, vec![-1, -1, -1, -1]);Sourcepub fn ones<T: TensorElement>(shape: impl Into<Shape>) -> Result<Self>
pub fn ones<T: TensorElement>(shape: impl Into<Shape>) -> Result<Self>
Creates a tensor filled with ones.
All elements in the tensor will be set to the numeric value 1 for the specified type.
§Parameters
shape- The shape/dimensions of the tensor to create
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor filled with onesErr: If tensor creation fails
§Examples
use slsl::Tensor;
let tensor = Tensor::ones::<f32>([2, 2])?;
assert_eq!(tensor.dims(), [2, 2]);
assert_eq!(tensor.to_flat_vec::<f32>()?, vec![1.0, 1.0, 1.0, 1.0]);
let tensor = Tensor::ones::<i32>([3])?;
assert_eq!(tensor.to_vec::<i32>()?, vec![1, 1, 1]);Sourcepub fn zeros<T: TensorElement>(shape: impl Into<Shape>) -> Result<Self>
pub fn zeros<T: TensorElement>(shape: impl Into<Shape>) -> Result<Self>
Creates a tensor filled with zeros.
All elements in the tensor will be set to the numeric value 0 for the specified type. This operation is optimized for performance.
§Parameters
shape- The shape/dimensions of the tensor to create
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor filled with zerosErr: If tensor creation fails
§Examples
use slsl::Tensor;
let tensor = Tensor::zeros::<f64>([3, 2])?;
assert_eq!(tensor.dims(), [3, 2]);
assert_eq!(tensor.to_flat_vec::<f64>()?, vec![0.0; 6]);
let tensor = Tensor::zeros::<i32>([4])?;
assert_eq!(tensor.to_vec::<i32>()?, vec![0, 0, 0, 0]);Sourcepub fn ones_like<T: TensorElement>(tensor: &Self) -> Result<Self>
pub fn ones_like<T: TensorElement>(tensor: &Self) -> Result<Self>
Creates a tensor filled with ones, with the same shape as the input tensor.
This is a convenience function that creates a new tensor with the same dimensions as the reference tensor, but filled with ones of the specified type.
§Parameters
tensor- The reference tensor whose shape will be copied
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor with the same shape as input, filled with onesErr: If tensor creation fails
§Examples
use slsl::Tensor;
let original = Tensor::zeros::<f32>([2, 3])?;
let ones_tensor = Tensor::ones_like::<f32>(&original)?;
assert_eq!(ones_tensor.dims(), [2, 3]);
assert_eq!(ones_tensor.to_flat_vec::<f32>()?, vec![1.0; 6]);Sourcepub fn zeros_like<T: TensorElement>(tensor: &Self) -> Result<Self>
pub fn zeros_like<T: TensorElement>(tensor: &Self) -> Result<Self>
Creates a tensor filled with zeros, with the same shape as the input tensor.
This is a convenience function that creates a new tensor with the same dimensions as the reference tensor, but filled with zeros of the specified type.
§Parameters
tensor- The reference tensor whose shape will be copied
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor with the same shape as input, filled with zerosErr: If tensor creation fails
§Examples
use slsl::Tensor;
let original = Tensor::ones::<f32>([2, 2])?;
let zeros_tensor = Tensor::zeros_like::<f32>(&original)?;
assert_eq!(zeros_tensor.dims(), [2, 2]);
assert_eq!(zeros_tensor.to_flat_vec::<f32>()?, vec![0.0; 4]);Sourcepub fn eye<T: TensorElement>(n: usize) -> Result<Self>
pub fn eye<T: TensorElement>(n: usize) -> Result<Self>
Creates an identity matrix of size n × n.
An identity matrix has ones on the main diagonal and zeros elsewhere. This function creates a 2D square tensor with these properties.
§Parameters
n- The size of the square matrix (both width and height)
§Returns
A Result<Tensor> containing:
Ok(Tensor): A 2D tensor of shape[n, n]representing the identity matrixErr: If tensor creation fails
§Examples
use slsl::Tensor;
let eye = Tensor::eye::<f32>(3)?;
assert_eq!(eye.dims(), [3, 3]);
assert_eq!(eye.at::<f32>([0, 0]), 1.0); // Diagonal elements
assert_eq!(eye.at::<f32>([1, 1]), 1.0);
assert_eq!(eye.at::<f32>([2, 2]), 1.0);
assert_eq!(eye.at::<f32>([0, 1]), 0.0); // Off-diagonal elements
assert_eq!(eye.at::<f32>([1, 0]), 0.0);Sourcepub fn arange<T: TensorElement + PartialOrd + Add<Output = T> + AsPrimitive<f32>>(
start: T,
end: T,
step: T,
) -> Result<Self>
pub fn arange<T: TensorElement + PartialOrd + Add<Output = T> + AsPrimitive<f32>>( start: T, end: T, step: T, ) -> Result<Self>
Creates a 1D tensor with values from start to end (exclusive) with a given step.
Generates a sequence of values starting from start, incrementing by step,
and stopping before end. Similar to Python’s range() function.
§Parameters
start- The starting value (inclusive)end- The ending value (exclusive)step- The increment between consecutive values
§Returns
A Result<Tensor> containing:
Ok(Tensor): A 1D tensor containing the generated sequenceErr: If step is zero, or if boolean type is used
§Examples
use slsl::Tensor;
// Basic usage
let tensor = Tensor::arange(0, 5, 1)?;
assert_eq!(tensor.to_vec::<i32>()?, vec![0, 1, 2, 3, 4]);
// With step > 1
let tensor = Tensor::arange(0.0, 2.0, 0.5)?;
assert_eq!(tensor.to_vec::<f64>()?, vec![0.0, 0.5, 1.0, 1.5]);
// Negative step
let tensor = Tensor::arange(5, 0, -1)?;
assert_eq!(tensor.to_vec::<i32>()?, vec![5, 4, 3, 2, 1]);§Panics
Returns an error if:
stepis zero- The tensor type is boolean
Sourcepub fn linspace<T>(start: T, end: T, n: usize) -> Result<Self>
pub fn linspace<T>(start: T, end: T, n: usize) -> Result<Self>
Creates a 1D tensor with n evenly spaced values from start to end (inclusive).
Generates n values linearly spaced between start and end, including both endpoints.
Similar to NumPy’s linspace() function.
§Parameters
start- The starting value (inclusive)end- The ending value (inclusive)n- The number of values to generate
§Returns
A Result<Tensor> containing:
Ok(Tensor): A 1D tensor withnevenly spaced valuesErr: Ifnis zero or if boolean type is used
§Examples
use slsl::Tensor;
// 5 values from 0 to 10
let tensor = Tensor::linspace(0.0f32, 10.0f32, 5)?;
assert_eq!(tensor.to_vec::<f32>()?, vec![0.0, 2.5, 5.0, 7.5, 10.0]);
// Single value
let tensor = Tensor::linspace(5.0f32, 10.0f32, 1)?;
assert_eq!(tensor.to_vec::<f32>()?, vec![5.0]);
// Negative range
let tensor = Tensor::linspace(-1.0f32, 1.0f32, 3)?;
assert_eq!(tensor.to_vec::<f32>()?, vec![-1.0, 0.0, 1.0]);§Panics
Returns an error if:
nis zero- The tensor type is boolean
Sourcepub fn rand<T: TensorElement + SampleUniform>(
low: T,
high: T,
shape: impl Into<Shape>,
) -> Result<Self>
pub fn rand<T: TensorElement + SampleUniform>( low: T, high: T, shape: impl Into<Shape>, ) -> Result<Self>
Creates a tensor with random values from a uniform distribution in the range [low, high).
Generates random values uniformly distributed between low (inclusive) and high (exclusive).
The random number generator is automatically seeded.
§Parameters
low- The lower bound (inclusive)high- The upper bound (exclusive)shape- The shape/dimensions of the tensor to create
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor filled with random values from the uniform distributionErr: If the distribution parameters are invalid or tensor creation fails
§Examples
use slsl::Tensor;
// Random floats between 0.0 and 1.0
let tensor = Tensor::rand(0.0f32, 1.0f32, [2, 3])?;
assert_eq!(tensor.dims(), [2, 3]);
// Random integers between 1 and 10
let tensor = Tensor::rand(1i32, 10i32, [5])?;
assert_eq!(tensor.dims(), [5]);
// All values should be in range [1, 10)
for &val in tensor.to_vec::<i32>()?.iter() {
assert!(val >= 1 && val < 10);
}§Notes
- Uses a fast random number generator (SmallRng)
- Values are uniformly distributed in the specified range
- The upper bound is exclusive (values will be less than
high)
Sourcepub fn randn<T: TensorElement + From<f32>>(
shape: impl Into<Shape>,
) -> Result<Self>
pub fn randn<T: TensorElement + From<f32>>( shape: impl Into<Shape>, ) -> Result<Self>
Creates a tensor with random values from a standard normal distribution N(0,1).
Generates random values from a normal (Gaussian) distribution with mean 0 and standard deviation 1. This is commonly used for neural network weight initialization.
§Parameters
shape- The shape/dimensions of the tensor to create
§Returns
A Result<Tensor> containing:
Ok(Tensor): A tensor filled with normally distributed random valuesErr: If tensor creation fails
§Examples
use slsl::Tensor;
let tensor = Tensor::randn::<f32>([2, 3])?;
assert_eq!(tensor.dims(), [2, 3]);
// Values should be roughly centered around 0
let values = tensor.to_flat_vec::<f32>()?;
let mean: f32 = values.iter().sum::<f32>() / values.len() as f32;
assert!(mean.abs() < 1.0); // Should be close to 0 for large samples§Notes
- Uses a standard normal distribution (mean=0, std=1)
- Commonly used for initializing neural network weights
- Values follow the bell curve distribution
Sourcepub fn triu<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
pub fn triu<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
Extracts the upper triangular part of a matrix (k-th diagonal and above).
Creates a new tensor containing only the upper triangular elements of the input matrix. Elements below the k-th diagonal are set to zero.
§Parameters
matrix- The input 2D tensor (must be 2-dimensional)k- Diagonal offset:k = 0: Main diagonal and abovek > 0: Above the main diagonalk < 0: Below the main diagonal
§Returns
A Result<Tensor> containing:
Ok(Tensor): A new tensor with the upper triangular partErr: If the input is not a 2D matrix
§Examples
use slsl::Tensor;
let matrix = Tensor::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3])?;
// Main diagonal and above (k=0)
let upper = Tensor::triu::<i32>(&matrix, 0)?;
// Result: [[1, 2, 3],
// [0, 5, 6],
// [0, 0, 9]]
// Above main diagonal (k=1)
let upper = Tensor::triu::<i32>(&matrix, 1)?;
// Result: [[0, 2, 3],
// [0, 0, 6],
// [0, 0, 0]]§Panics
Returns an error if the input tensor is not 2-dimensional.
Sourcepub fn tril<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
pub fn tril<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
Extracts the lower triangular part of a matrix (k-th diagonal and below).
Creates a new tensor containing only the lower triangular elements of the input matrix. Elements above the k-th diagonal are set to zero.
§Parameters
matrix- The input 2D tensor (must be 2-dimensional)k- Diagonal offset:k = 0: Main diagonal and belowk > 0: Above the main diagonalk < 0: Below the main diagonal
§Returns
A Result<Tensor> containing:
Ok(Tensor): A new tensor with the lower triangular partErr: If the input is not a 2D matrix
§Examples
use slsl::Tensor;
let matrix = Tensor::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3])?;
// Main diagonal and below (k=0)
let lower = Tensor::tril::<i32>(&matrix, 0)?;
// Result: [[1, 0, 0],
// [4, 5, 0],
// [7, 8, 9]]
// Below main diagonal (k=-1)
let lower = Tensor::tril::<i32>(&matrix, -1)?;
// Result: [[0, 0, 0],
// [4, 0, 0],
// [7, 8, 0]]§Panics
Returns an error if the input tensor is not 2-dimensional.
Sourcepub fn diag<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
pub fn diag<T: TensorElement>(matrix: &Tensor, k: i32) -> Result<Self>
Extracts diagonal elements from a matrix.
Returns a 1D tensor containing the elements from the specified diagonal of the input matrix. The k-th diagonal can be the main diagonal (k=0), above it (k>0), or below it (k<0).
§Parameters
matrix- The input 2D tensor (must be 2-dimensional)k- Diagonal offset:k = 0: Main diagonalk > 0: k-th diagonal above the main diagonalk < 0: k-th diagonal below the main diagonal
§Returns
A Result<Tensor> containing:
Ok(Tensor): A 1D tensor with the diagonal elementsErr: If the input is not a 2D matrix
§Examples
use slsl::Tensor;
let matrix = Tensor::from_vec(vec![1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3])?;
// Main diagonal (k=0)
let diag = Tensor::diag::<i32>(&matrix, 0)?;
assert_eq!(diag.to_vec::<i32>()?, vec![1, 5, 9]);
// First super-diagonal (k=1)
let diag = Tensor::diag::<i32>(&matrix, 1)?;
assert_eq!(diag.to_vec::<i32>()?, vec![2, 6]);
// First sub-diagonal (k=-1)
let diag = Tensor::diag::<i32>(&matrix, -1)?;
assert_eq!(diag.to_vec::<i32>()?, vec![4, 8]);§Notes
- For non-square matrices, the diagonal length is determined by the matrix dimensions
- If the requested diagonal is out of bounds, an empty tensor is returned
§Panics
Returns an error if the input tensor is not 2-dimensional.
Source§impl Tensor
impl Tensor
Sourcepub fn view(&self) -> TensorView<'_>
pub fn view(&self) -> TensorView<'_>
Creates a view of this tensor without copying data.
A tensor view provides a lightweight way to access tensor data without taking ownership. The view borrows from the original tensor’s storage.
§Returns
A TensorView that references the same data as this tensor.
§Examples
use slsl::Tensor;
let tensor = Tensor::zeros::<f32>([2, 3])?;
let view = tensor.view();
assert_eq!(view.shape(), tensor.shape());
assert_eq!(view.dtype(), tensor.dtype());Source§impl Tensor
impl Tensor
Sourcepub fn slice<S: IntoSliceElem + Copy>(&self, specs: S) -> TensorView<'_>
pub fn slice<S: IntoSliceElem + Copy>(&self, specs: S) -> TensorView<'_>
Creates a slice view of this tensor with optimized performance.
This method provides efficient tensor slicing with fast paths for common patterns. Creates a zero-copy view without memory allocation.
§Parameters
specs- The slice specification (index, range with s! macro, tuple, etc.)
§Returns
A TensorView representing the sliced portion of the tensor.
§Examples
use slsl::{s, Tensor};
let tensor = Tensor::zeros::<f32>([4, 6])?;
// Single index
let row = tensor.slice(1);
assert_eq!(row.shape().as_slice(), &[6]);
// Range slice using s! macro
let rows = tensor.slice(s![1..3]);
assert_eq!(rows.shape().as_slice(), &[2]);pub fn compute_slice( shape: &Shape, strides: &Stride, slice: SliceSpecs, ) -> (Shape, Stride, usize)
Trait Implementations§
Source§impl<T: TensorElement> From<&[T]> for Tensor
impl<T: TensorElement> From<&[T]> for Tensor
Source§fn from(value: &[T]) -> Self
fn from(value: &[T]) -> Self
Creates a 1D tensor from a slice.
The tensor will have the same length as the slice and contain copies of all elements.
§Examples
use slsl::Tensor;
let data = [1, 2, 3, 4];
let tensor: Tensor = (&data[..]).into();
assert_eq!(tensor.dims(), [4]);
assert_eq!(tensor.to_vec::<i32>().unwrap(), vec![1, 2, 3, 4]);Source§impl<T: TensorElement> From<&Vec<T>> for Tensor
impl<T: TensorElement> From<&Vec<T>> for Tensor
Source§fn from(value: &Vec<T>) -> Self
fn from(value: &Vec<T>) -> Self
Creates a 1D tensor from a vector reference.
The tensor will have the same length as the vector and contain copies of all elements.
§Examples
use slsl::Tensor;
let data = vec![1.0, 2.0, 3.0];
let tensor: Tensor = (&data).into();
assert_eq!(tensor.dims(), [3]);
assert_eq!(tensor.to_vec::<f64>().unwrap(), vec![1.0, 2.0, 3.0]);Source§impl<T: TensorElement, const N: usize> From<[T; N]> for Tensor
impl<T: TensorElement, const N: usize> From<[T; N]> for Tensor
Source§fn from(value: [T; N]) -> Self
fn from(value: [T; N]) -> Self
Creates a 1D tensor from a fixed-size array.
Since TensorElement implements Copy, the array is efficiently copied.
The tensor will have length N and contain all array elements.
§Examples
use slsl::Tensor;
let data = [1, 2, 3, 4, 5];
let tensor: Tensor = data.into();
assert_eq!(tensor.dims(), [5]);
assert_eq!(tensor.to_vec::<i32>().unwrap(), vec![1, 2, 3, 4, 5]);
// Original array is still available (Copy semantics)
println!("{:?}", data);Source§impl<T: TensorElement> From<T> for Tensor
impl<T: TensorElement> From<T> for Tensor
Source§fn from(value: T) -> Self
fn from(value: T) -> Self
Creates a tensor from a scalar value.
This conversion creates a 0-dimensional (scalar) tensor containing the given value.
§Examples
use slsl::Tensor;
let tensor: Tensor = 42.0f32.into();
assert_eq!(tensor.dims(), []);
assert_eq!(tensor.to_scalar::<f32>().unwrap(), 42.0);Source§impl<T: TensorElement> From<Vec<T>> for Tensor
impl<T: TensorElement> From<Vec<T>> for Tensor
Source§fn from(value: Vec<T>) -> Self
fn from(value: Vec<T>) -> Self
Creates a 1D tensor from a vector by taking ownership.
This is an efficient conversion that takes ownership of the vector’s data without copying.
§Examples
use slsl::Tensor;
let data = vec![1.0f32, 2.0, 3.0, 4.0];
let tensor: Tensor = data.into();
assert_eq!(tensor.dims(), [4]);
assert_eq!(tensor.to_vec::<f32>().unwrap(), vec![1.0, 2.0, 3.0, 4.0]);