pub struct Tensor { /* private fields */ }Expand description
A tensor: shared storage viewed through a layout.
Cloning a tensor is cheap — it clones the layout and bumps the storage
refcount, never the data. View operations (reshape, permute,
narrow, …) produce new tensors over the same storage whenever the
layout arithmetic allows it.
Implementations§
Source§impl Tensor
impl Tensor
Sourcepub fn scalar_on(like: &Tensor, value: f32) -> Result<Tensor>
pub fn scalar_on(like: &Tensor, value: f32) -> Result<Tensor>
A scalar constant on the same device as like (plumbing for VJPs
and scalar operator overloads).
Sourcepub fn gt_mask(&self, rhs: &Tensor) -> Result<Tensor>
pub fn gt_mask(&self, rhs: &Tensor) -> Result<Tensor>
Elementwise a > b as a 0.0/1.0 mask. Not differentiable.
Sourcepub fn eq_mask(&self, rhs: &Tensor) -> Result<Tensor>
pub fn eq_mask(&self, rhs: &Tensor) -> Result<Tensor>
Elementwise a == b as a 0.0/1.0 mask. Not differentiable.
Sourcepub fn add_scalar(&self, s: f32) -> Result<Tensor>
pub fn add_scalar(&self, s: f32) -> Result<Tensor>
Add a scalar, broadcasting.
Sourcepub fn mul_scalar(&self, s: f32) -> Result<Tensor>
pub fn mul_scalar(&self, s: f32) -> Result<Tensor>
Multiply by a scalar, broadcasting.
Sourcepub fn matmul(&self, rhs: &Tensor) -> Result<Tensor>
pub fn matmul(&self, rhs: &Tensor) -> Result<Tensor>
Matrix product with NumPy/PyTorch batch semantics.
Operands are rank 2 ([m, k]) or rank 3 ([b, m, k]); a rank-2
operand behaves as batch 1, and batch dimensions broadcast (1
against b). The result is rank 2 only when both operands are.
[2, 2, 3] x [1, 3, 2] is [2, 2, 2]; [m, k] x [b, k, n] is
[b, m, n]. See plan_matmul for
the exact contract every backend implements.
Sourcepub fn sum(&self, axes: &[usize]) -> Result<Tensor>
pub fn sum(&self, axes: &[usize]) -> Result<Tensor>
Sum over axes (empty means all), removing them from the shape.
Sourcepub fn sum_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
pub fn sum_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
Sum over axes with explicit keepdim.
Sourcepub fn max_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
pub fn max_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
Maximum over axes with explicit keepdim.
Sourcepub fn mean(&self, axes: &[usize]) -> Result<Tensor>
pub fn mean(&self, axes: &[usize]) -> Result<Tensor>
Mean over axes (empty means all) — composite, so its gradient
flows through sum and scalar multiply.
Sourcepub fn mean_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
pub fn mean_keepdim(&self, axes: &[usize], keepdim: bool) -> Result<Tensor>
Mean over axes with explicit keepdim.
Sourcepub fn argmax(&self, dim: usize, keepdim: bool) -> Result<Tensor>
pub fn argmax(&self, dim: usize, keepdim: bool) -> Result<Tensor>
Index of the maximum along dim, as an I64 tensor. Not
differentiable.
Sourcepub fn softmax(&self, dim: usize) -> Result<Tensor>
pub fn softmax(&self, dim: usize) -> Result<Tensor>
Numerically stable softmax along dim — composite.
Sourcepub fn log_softmax(&self, dim: usize) -> Result<Tensor>
pub fn log_softmax(&self, dim: usize) -> Result<Tensor>
Numerically stable log-softmax along dim — composite.
Sourcepub fn index_select(&self, dim: usize, indices: &Tensor) -> Result<Tensor>
pub fn index_select(&self, dim: usize, indices: &Tensor) -> Result<Tensor>
Rows of self along dim selected by indices (I64).
Source§impl Tensor
impl Tensor
Sourcepub fn from_storage(storage: Arc<Storage>, layout: Layout) -> Result<Self>
pub fn from_storage(storage: Arc<Storage>, layout: Layout) -> Result<Self>
A tensor over existing storage with an explicit layout.
Errors when the layout addresses elements outside the storage.
Sourcepub fn from_vec_f32(data: Vec<f32>, shape: impl Into<Shape>) -> Result<Self>
pub fn from_vec_f32(data: Vec<f32>, shape: impl Into<Shape>) -> Result<Self>
A contiguous CPU tensor holding data with shape shape.
Errors when data.len() does not equal shape.numel().
Sourcepub fn from_slice(data: &[f32], shape: impl Into<Shape>) -> Result<Self>
pub fn from_slice(data: &[f32], shape: impl Into<Shape>) -> Result<Self>
A contiguous CPU tensor copying data with shape shape.
Sourcepub fn from_vec_i64(data: Vec<i64>, shape: impl Into<Shape>) -> Result<Self>
pub fn from_vec_i64(data: Vec<i64>, shape: impl Into<Shape>) -> Result<Self>
A contiguous CPU I64 tensor holding data (indices, targets).
Sourcepub fn randn(shape: impl Into<Shape>) -> Self
pub fn randn(shape: impl Into<Shape>) -> Self
Standard-normal random CPU tensor, seeded from the OS.
Sourcepub fn randn_with_seed(shape: impl Into<Shape>, seed: u64) -> Self
pub fn randn_with_seed(shape: impl Into<Shape>, seed: u64) -> Self
Standard-normal random CPU tensor with a fixed seed, for reproducible tests and examples.
Sourcepub fn get_f32(&self, index: &[usize]) -> Result<f32>
pub fn get_f32(&self, index: &[usize]) -> Result<f32>
The element at a logical index, as f32.
Errors on rank mismatch, out-of-bounds, non-float dtype, or non-CPU storage.
Sourcepub fn to_vec_f32(&self) -> Result<Vec<f32>>
pub fn to_vec_f32(&self) -> Result<Vec<f32>>
Every element in logical (row-major) order, as f32, from CPU
storage.
Sourcepub fn to_vec_i64(&self) -> Result<Vec<i64>>
pub fn to_vec_i64(&self) -> Result<Vec<i64>>
Every element in logical (row-major) order, as i64.
Sourcepub fn reshape(&self, shape: impl Into<Shape>) -> Result<Self>
pub fn reshape(&self, shape: impl Into<Shape>) -> Result<Self>
A view (or copy, when this view is not contiguous) with the same elements in a new shape.
Sourcepub fn permute(&self, perm: &[usize]) -> Result<Self>
pub fn permute(&self, perm: &[usize]) -> Result<Self>
A view with dimensions reordered by perm (a permutation of
0..ndim).
Sourcepub fn transpose(&self, d0: usize, d1: usize) -> Result<Self>
pub fn transpose(&self, d0: usize, d1: usize) -> Result<Self>
A view with dimensions d0 and d1 swapped.
Sourcepub fn narrow(&self, dim: usize, start: usize, len: usize) -> Result<Self>
pub fn narrow(&self, dim: usize, start: usize, len: usize) -> Result<Self>
A view of len elements of dimension dim starting at start.
Sourcepub fn slice(&self, dim: usize, range: Range<usize>) -> Result<Self>
pub fn slice(&self, dim: usize, range: Range<usize>) -> Result<Self>
A view of range along dim — sugar over Tensor::narrow.
Sourcepub fn broadcast_to(&self, shape: impl Into<Shape>) -> Result<Self>
pub fn broadcast_to(&self, shape: impl Into<Shape>) -> Result<Self>
A zero-copy broadcast view to shape (stride 0 on expanded axes).
Sourcepub fn broadcast_view(&self, shape: &Shape) -> Result<Self>
pub fn broadcast_view(&self, shape: &Shape) -> Result<Self>
A broadcast view that records nothing on the tape — backend
plumbing; prefer Tensor::broadcast_to in user code.
Sourcepub fn unsqueeze(&self, dim: usize) -> Result<Self>
pub fn unsqueeze(&self, dim: usize) -> Result<Self>
A view with a new size-1 dimension inserted at dim.
Sourcepub fn contiguous(&self) -> Result<Self>
pub fn contiguous(&self) -> Result<Self>
This tensor’s elements, in logical order, in fresh contiguous storage on the same device. A no-op clone when already contiguous.
Sourcepub fn contiguous_untracked(&self) -> Result<Self>
pub fn contiguous_untracked(&self) -> Result<Self>
The contiguous copy without autograd recording — backend plumbing;
prefer Tensor::contiguous in user code.
Sourcepub fn requires_grad_(self, requires: bool) -> Self
pub fn requires_grad_(self, requires: bool) -> Self
Mark (or unmark) this tensor as a gradient-accumulating leaf, in place, returning it for chaining.
Sourcepub fn requires_grad(&self) -> bool
pub fn requires_grad(&self) -> bool
Whether gradients accumulate on this tensor during backward
— true for leaves marked with requires_grad_.
This answers a narrower question than PyTorch’s requires_grad:
a tensor computed from such a leaf is on the tape but does not
accumulate a gradient of its own, so it reports false here. Ask
is_tracked for “is this on the graph at all”.
Sourcepub fn is_tracked(&self) -> bool
pub fn is_tracked(&self) -> bool
Whether this tensor participates in the autograd tape at all —
true for a leaf that requires grad and for anything computed from
one while recording was enabled; false for constants and for
everything produced under no_grad.
This is the predicate that observes no_grad:
use oxmera_tensor::tensor::Tensor;
use oxmera_tensor::autograd::no_grad;
let a = Tensor::from_slice(&[1.0, 2.0], [2]).unwrap().requires_grad_(true);
assert!(a.mul_scalar(3.0).unwrap().is_tracked());
assert!(!no_grad(|| a.mul_scalar(3.0).unwrap()).is_tracked());Sourcepub fn grad(&self) -> Option<Tensor>
pub fn grad(&self) -> Option<Tensor>
The accumulated gradient, if a backward pass has produced one.
Sourcepub fn backward(&self) -> Result<()>
pub fn backward(&self) -> Result<()>
Propagate gradients from this scalar through the recorded tape.
Errors when the tensor is not a scalar; use
Tensor::backward_with to seed a non-scalar output.
Sourcepub fn backward_with(&self, seed: Tensor) -> Result<()>
pub fn backward_with(&self, seed: Tensor) -> Result<()>
Propagate gradients seeding this tensor’s gradient with seed.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Tensor
impl !UnwindSafe for Tensor
impl Freeze for Tensor
impl Send for Tensor
impl Sync for Tensor
impl Unpin for Tensor
impl UnsafeUnpin 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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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