pub struct Tensor { /* private fields */ }Expand description
Row-major dense tensor — a CPU-only reference backend.
Stores f32 data in a single contiguous, row-major Vec<f32> addressed as
data[i * ncols + j] (and the rank-n generalization). This layout is the
one and only invariant: there are no strided views, no broadcasting outside
the documented ops::batched_matmul case, and no device or dtype
dispatch. External ML frameworks own general tensor abstractions; this crate
deliberately stays a small, honest reference kernel.
Tensor does not carry a strides field. Because every element is
contiguous and row-major, strides are fully determined by Self::shape
and can be recomputed on demand with Tensor::row_major_strides; storing
them would only invite the illusion of stride-aware kernels that do not
exist.
§Layout and copies
Self::reshape and Self::transpose both return owned tensors backed
by fresh buffers — they are copies, never aliasing views. Self::data_mut
hands out the raw contiguous storage; callers must preserve the row-major
element count for Self::shape (mutating length or reordering across rows
breaks the contiguity invariant).
§Construction
Prefer Tensor::try_from_vec, which validates the element count and
row-major stride arithmetic with checked multiplication before storing
data. Tensor::from_vec and the other panic-style constructors remain
as pre-1.0 compatibility wrappers; migrate new call sites to try_from_vec.
§Serialization
JSON is a versioned fixture format for this CPU reference backend, not a
universal tensor interchange format. Version 1 carries schema_version,
data, and shape; unknown fields, including legacy strides, are rejected.
Non-finite values cannot be serialized to JSON. Deserialization checks the
shape and row-major stride arithmetic through Self::try_from_vec. Use
crate::reference_json::from_slice_with_limit for untrusted input.
§Rank-0 scalars vs zero-sized axes
shape == []is a rank-0 scalar with exactly one element (numel == 1).- Any axis equal to
0yieldsnumel == 0, even when other extents would overflow if multiplied without checked arithmetic (for example[usize::MAX, 0, 2]). - Constructors and
Deserializereject shapes whose element count or row-major stride product is not representable inusize(seechecked_numelandtry_compute_strides). Self::meanon a zero-element tensor is0.0 / 0.0, which isNaN.
Implementations§
Source§impl Tensor
impl Tensor
Sourcepub fn from_vec(data: Vec<f32>, shape: &[usize]) -> Self
pub fn from_vec(data: Vec<f32>, shape: &[usize]) -> Self
Constructs a tensor from a contiguous row-major buffer and shape.
§Panics
Panics if the shape product or stride arithmetic overflows usize, or
if data.len() does not equal the number of elements implied by
shape.
Prefer Tensor::try_from_vec in new code. This wrapper is retained
for pre-1.0 source compatibility and will remain until a separate
SemVer decision removes panic-on-invalid-shape constructors.
Sourcepub fn try_from_vec(data: Vec<f32>, shape: &[usize]) -> Result<Self>
pub fn try_from_vec(data: Vec<f32>, shape: &[usize]) -> Result<Self>
Fallible constructor: proves numel and row-major strides are
representable before taking ownership of data.
Strides are not stored; the check exists only to reject shapes whose
row-major stride arithmetic would overflow usize, matching the
contiguity guarantees callers of Self::data rely on. Does not
allocate a new data buffer, so overflowing shapes fail without
attempting a giant allocation.
Sourcepub fn zeros(shape: &[usize]) -> Self
pub fn zeros(shape: &[usize]) -> Self
Fills a tensor with zeros.
§Panics
Panics if the shape product or stride arithmetic overflows usize.
Prefer Tensor::try_zeros in new code.
Sourcepub fn try_zeros(shape: &[usize]) -> Result<Self>
pub fn try_zeros(shape: &[usize]) -> Result<Self>
Fallible Tensor::zeros.
Returns CortexError::SizeOverflow when the element count or strides
are not representable and CortexError::AllocationFailed when the
allocator refuses the reservation, instead of aborting through
handle_alloc_error. The same holds for try_ones, try_full,
try_randn*, and the ops that allocate a fresh output buffer from a
shape (try_matmul, try_batched_matmul, try_layer_norm,
try_rms_norm, try_embedding, try_causal_mask). Ops that copy an
existing tensor (try_transpose, try_softmax_last, elementwise and
activation methods) still allocate infallibly; see
the crate-private try_reserve_f32 helper for that limitation and for
the overcommit caveat.
Sourcepub fn ones(shape: &[usize]) -> Self
pub fn ones(shape: &[usize]) -> Self
Fills a tensor with ones.
§Panics
Panics if the shape product or stride arithmetic overflows usize.
See Tensor::from_vec for the pre-1.0 compatibility policy.
Prefer Tensor::try_ones in new code.
Sourcepub fn try_ones(shape: &[usize]) -> Result<Self>
pub fn try_ones(shape: &[usize]) -> Result<Self>
Fallible Tensor::ones.
Sourcepub fn full(shape: &[usize], val: f32) -> Self
pub fn full(shape: &[usize], val: f32) -> Self
Fills a tensor with val.
§Panics
Panics if the shape product or stride arithmetic overflows usize.
See Tensor::from_vec for the pre-1.0 compatibility policy.
Prefer Tensor::try_full in new code.
Sourcepub fn randn(shape: &[usize], mean: f32, std: f32) -> Self
pub fn randn(shape: &[usize], mean: f32, std: f32) -> Self
Fills a tensor with i.i.d. normal samples.
§Panics
Panics if the shape product or stride arithmetic overflows usize,
if mean is not finite, if std is not finite or is negative, or if
a sample overflows f32. Prefer Tensor::try_randn in new code.
See Tensor::from_vec for the pre-1.0 compatibility policy.
Sourcepub fn try_randn(shape: &[usize], mean: f32, std: f32) -> Result<Self>
pub fn try_randn(shape: &[usize], mean: f32, std: f32) -> Result<Self>
Fallible Tensor::randn: fails on shape/stride overflow before
allocating, and with CortexError::InvalidConfig unless mean is
finite and std is finite and non-negative. Draws from the thread
RNG; use Tensor::try_randn_with_rng for reproducible values.
Sourcepub fn try_randn_with_rng<R: Rng + ?Sized>(
shape: &[usize],
mean: f32,
std: f32,
rng: &mut R,
) -> Result<Self>
pub fn try_randn_with_rng<R: Rng + ?Sized>( shape: &[usize], mean: f32, std: f32, rng: &mut R, ) -> Result<Self>
Like Tensor::try_randn but draws from the caller’s RNG, so a
seeded RNG reproduces the same tensor.
pub fn data(&self) -> &[f32]
Sourcepub fn data_mut(&mut self) -> &mut [f32]
pub fn data_mut(&mut self) -> &mut [f32]
Mutable access to the raw contiguous, row-major storage.
The slice length equals Self::numel and is addressed as
data[i * ncols + j]. Callers may overwrite values in place but must
not rely on any layout other than contiguous row-major, and must not
assume the length can change: Self::shape is unaffected by writes
here, so reinterpreting the buffer under a different shape requires
Self::reshape (which copies).
pub fn shape(&self) -> &[usize]
Sourcepub fn row_major_strides(&self) -> Vec<usize>
pub fn row_major_strides(&self) -> Vec<usize>
Recomputes the row-major strides implied by Self::shape.
Strides are not stored: this tensor is always contiguous row-major, so
they are a pure function of the shape. The last stride is 1 and each
earlier stride is the product of the following extents. Returns an empty
vector for a scalar (rank-0) shape.
§Panics
Panics only if the stride product overflows usize, which cannot happen
for a tensor built through the crate’s constructors (they reject such
shapes up front). Use Self::try_row_major_strides to recover instead
of panicking on a hand-corrupted shape.
Sourcepub fn try_row_major_strides(&self) -> Result<Vec<usize>>
pub fn try_row_major_strides(&self) -> Result<Vec<usize>>
Fallible Self::row_major_strides: returns
CortexError::SizeOverflow if the row-major stride product is not
representable in usize.
pub fn numel(&self) -> usize
pub fn ndim(&self) -> usize
Sourcepub fn reshape(&self, new_shape: &[usize]) -> Self
pub fn reshape(&self, new_shape: &[usize]) -> Self
Reshapes to new_shape, which must imply the same element count.
This copies. The returned tensor owns a fresh Vec<f32> cloned from
self; it does not alias self’s storage. Because the layout is always
contiguous row-major, the reinterpretation is a no-op on the element
order — only the shape metadata changes. To avoid the clone entirely,
reinterpret in place with Self::reshape_in_place.
§Panics
Panics if the element count changes or the new shape overflows.
Prefer Tensor::try_reshape in new code.
Sourcepub fn try_reshape(&self, new_shape: &[usize]) -> Result<Self>
pub fn try_reshape(&self, new_shape: &[usize]) -> Result<Self>
Fallible reshape (copying): new_shape must imply exactly
self.numel() elements and have representable row-major strides.
See Self::reshape: the result is a copy, not a view.
Sourcepub fn reshape_in_place(&mut self, new_shape: &[usize]) -> Result<()>
pub fn reshape_in_place(&mut self, new_shape: &[usize]) -> Result<()>
Reinterprets self under new_shape in place, without copying.
Because the storage is already contiguous row-major, a reshape only
rewrites the shape metadata. This variant mutates self and reuses the
existing buffer instead of cloning, which Self::reshape cannot do
behind &self. new_shape must imply exactly self.numel() elements
and have representable row-major strides.
On error the shape is validated before any mutation, so self is
left completely unchanged and remains usable: returns
CortexError::ShapeMismatch on an element-count change and
CortexError::SizeOverflow on stride overflow.
Sourcepub fn transpose(&self) -> Self
pub fn transpose(&self) -> Self
Transposes a 2-D tensor: [rows, cols] → [cols, rows].
This materializes a new tensor: the returned buffer is a fresh,
contiguous row-major reordering of the elements, not a stride-swapped
view over self’s storage.
§Panics
Panics if self is not rank-2. Prefer Tensor::try_transpose.
Sourcepub fn try_transpose(&self) -> Result<Self>
pub fn try_transpose(&self) -> Result<Self>
Fallible transpose (materializing): returns CortexError::RankMismatch
unless self is rank-2. See Self::transpose: the result is a copy,
not a view.
Sourcepub fn add(&self, other: &Tensor) -> Self
pub fn add(&self, other: &Tensor) -> Self
Element-wise addition. Both tensors must have identical shapes.
§Panics
Panics on shape mismatch. Prefer Tensor::try_add in new code.
Sourcepub fn sub(&self, other: &Tensor) -> Self
pub fn sub(&self, other: &Tensor) -> Self
Element-wise subtraction. Both tensors must have identical shapes.
§Panics
Panics on shape mismatch. Prefer Tensor::try_sub in new code.
Sourcepub fn mul(&self, other: &Tensor) -> Self
pub fn mul(&self, other: &Tensor) -> Self
Element-wise multiplication. Both tensors must have identical shapes.
§Panics
Panics on shape mismatch. Prefer Tensor::try_mul in new code.
pub fn scale(&self, s: f32) -> Self
pub fn add_scalar(&self, s: f32) -> Self
Sourcepub fn relu(&self) -> Self
pub fn relu(&self) -> Self
Rectified linear unit, max(x, 0) with NaN propagation.
f32::max is not used because it discards NaN. NaN inputs stay NaN,
+Inf stays +Inf, and every non-positive input (including -0.0
and -Inf) is written as canonical +0.0.
Sourcepub fn gelu(&self) -> Self
pub fn gelu(&self) -> Self
Tanh-approximate GELU: x * 0.5 * (1 + tanh(sqrt(2/π) * (x + 0.044715 x³))).
+Inf gives +Inf and -Inf gives 0 (the limits), instead of the
NaN that -Inf * 0 would produce. NaN propagates.
Sourcepub fn silu(&self) -> Self
pub fn silu(&self) -> Self
SiLU / swish: x / (1 + exp(-x)).
+Inf gives +Inf and -Inf gives 0 (the limits), instead of the
NaN that -Inf / Inf would produce. NaN propagates.
Sourcepub fn fast_sigmoid(&self) -> Self
pub fn fast_sigmoid(&self) -> Self
Fast sigmoid surrogate gradient (from soma-engine’s E-prop): x / (1 + |x|).
±Inf gives ±1 (the limits), instead of the NaN that Inf / Inf
would produce. NaN propagates.
Sourcepub fn sum(&self) -> f32
pub fn sum(&self) -> f32
Sum of all elements, accumulated in compensated f64 and cast back to f32.
Sequential Neumaier (Kahan-Babuška) f64 accumulation keeps every
f32 input exact, avoids the f32 running-sum stall at 2^24 and
spurious intermediate overflow ([MAX, MAX, -MAX] sums to MAX), and
keeps a small term that plain f64 would cancel away between two large
ones ([MAX, 1e20, -MAX] sums to 1e20). The final cast follows
IEEE rounding: a true sum outside the f32 range becomes ±Inf. NaN
inputs propagate and +Inf + -Inf is NaN. An empty tensor sums to 0.
Sourcepub fn mean(&self) -> f32
pub fn mean(&self) -> f32
Arithmetic mean over all elements: the compensated f64 total divided
by numel() in f64, then cast once to f32 (not sum() / numel()).
Returns NaN when numel() == 0 (zero-sized axis or empty buffer).
Sourcepub fn max_val(&self) -> f32
pub fn max_val(&self) -> f32
Largest element.
NaN policy: any NaN (either sign) makes the result NaN; f32::max is
not used because it silently discards NaN. Otherwise this is the
ordinary maximum, so data()[argmax()] == max_val() for NaN-free
input and both report NaN when a positive NaN is present. (A negative
NaN sorts below -Inf in argmax’s total order but
still yields NaN here.) An empty tensor returns -Inf, the identity of
max.
Sourcepub fn argmax(&self) -> usize
pub fn argmax(&self) -> usize
Index of the largest element.
NaN policy: elements are ordered with f32::total_cmp (IEEE 754
totalOrder), which never yields None, so this function cannot
panic on NaN inputs. A positive NaN sorts above +Inf and therefore
wins; a negative NaN sorts below -Inf. Returns 0 for an empty
tensor. Callers that need NaN rejection should screen inputs with
f32::is_nan first.
Sourcepub fn softmax_last(&self) -> Self
pub fn softmax_last(&self) -> Self
Softmax along the last axis (0-D, 1-D, or each row of a 2-D tensor).
See finite for the NaN / ±Inf / all-masked policy.
§Panics
Panics if the rank is greater than 2. Prefer
Self::try_softmax_last in new code.
Sourcepub fn try_softmax_last(&self) -> Result<Self>
pub fn try_softmax_last(&self) -> Result<Self>
Fallible softmax along the last axis.
Returns CortexError::RankMismatch with expected: 2 when
ndim > 2, matching the other rank-checked ops.
Sourcepub fn row(&self, idx: usize) -> Self
pub fn row(&self, idx: usize) -> Self
Copies row idx of a 2-D tensor into a 1-D tensor.
§Panics
Panics if self is not rank-2 or idx is out of bounds. Prefer
Tensor::try_row in new code.
Sourcepub fn try_row(&self, idx: usize) -> Result<Self>
pub fn try_row(&self, idx: usize) -> Result<Self>
Fallible row access: returns CortexError::RankMismatch unless
self is rank-2 and CortexError::IndexOutOfBounds when
idx >= shape[0].
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Tensor
impl<'de> Deserialize<'de> for Tensor
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Source§impl StageTensor for Tensor
impl StageTensor for Tensor
Source§fn meta(&self) -> TensorMeta
fn meta(&self) -> TensorMeta
Auto Trait Implementations§
impl Forget for Tensor
impl Freeze for Tensor
impl Move for Tensor
impl RefUnwindSafe for Tensor
impl Send for Tensor
impl Sync for Tensor
impl Unpin for Tensor
impl UnsafeUnpin 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
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,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
impl<T> ErasedDestructor for Twhere
T: 'static,
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