Skip to main content

Tensor

Struct Tensor 

Source
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 0 yields numel == 0, even when other extents would overflow if multiplied without checked arithmetic (for example [usize::MAX, 0, 2]).
  • Constructors and Deserialize reject shapes whose element count or row-major stride product is not representable in usize (see checked_numel and try_compute_strides).
  • Self::mean on a zero-element tensor is 0.0 / 0.0, which is NaN.

Implementations§

Source§

impl Tensor

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn try_ones(shape: &[usize]) -> Result<Self>

Fallible Tensor::ones.

Source

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.

Source

pub fn try_full(shape: &[usize], val: f32) -> Result<Self>

Fallible Tensor::full.

Source

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.

Source

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.

Source

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.

Source

pub fn data(&self) -> &[f32]

Source

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

Source

pub fn shape(&self) -> &[usize]

Source

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.

Source

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.

Source

pub fn numel(&self) -> usize

Source

pub fn ndim(&self) -> usize

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn try_add(&self, other: &Tensor) -> Result<Self>

Fallible element-wise addition.

Source

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.

Source

pub fn try_sub(&self, other: &Tensor) -> Result<Self>

Fallible element-wise subtraction.

Source

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.

Source

pub fn try_mul(&self, other: &Tensor) -> Result<Self>

Fallible element-wise multiplication.

Source

pub fn scale(&self, s: f32) -> Self

Source

pub fn add_scalar(&self, s: f32) -> Self

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · 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<'de> Deserialize<'de> for Tensor

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Tensor

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StageTensor for Tensor

Source§

fn meta(&self) -> TensorMeta

Report this tensor’s shape and dtype.

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> 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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

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