Skip to main content

Matrix

Struct Matrix 

Source
pub struct Matrix { /* private fields */ }
Expand description

Device-visible numeric storage with explicit shape and dtype semantics.

Arithmetic operators delegate to crate::matrix and return Result<Matrix>: use let sum = (&left + &right)?;. They preserve validation, allocation, and recording failures without panicking. Multiplication is elementwise; use crate::matrix::matmul for matrix multiplication.

Implementations§

Source§

impl Matrix

Source

pub fn new_from_slice<T: Element>( shape: impl Into<Vec<usize>>, values: &[T], ) -> Result<Self>

Create a dense matrix from an admitted Rust scalar slice.

The element type selects the matrix dtype exactly; this function performs no numeric conversion.

§Errors

Returns an error when the shape overflows, its element count differs from values, or storage allocation/upload fails.

This variant uploads on this thread’s default runtime. An runtime initialization failure is returned before the upload starts.

Source

pub fn new_from_slice_on<T: Element>( runtime: &Runtime, shape: impl Into<Vec<usize>>, values: &[T], ) -> Result<Self>

Create a dense matrix on a particular runtime.

This is the new_from_slice contract evaluated on runtime instead of this thread’s default runtime.

§Errors

Returns the same errors as new_from_slice.

Source

pub fn new_from_slice_on_same_runtime<T: Element>( &self, shape: impl Into<Vec<usize>>, values: &[T], ) -> Result<Self>

Create a dense matrix on the runtime that owns self.

The element type selects the matrix dtype exactly; this function performs no numeric conversion.

§Errors

Returns an error when the shape overflows, its element count differs from values, or storage allocation/upload fails.

Source

pub fn same_runtime(&self, other: &Matrix) -> bool

Return whether other is owned by the same runtime as self.

Source

pub fn new_from_f32( shape: impl Into<Vec<usize>>, values: &[f32], ) -> Result<Self>

Create an FP32 matrix and initialize its device-visible storage.

§Errors

Returns an error when the shape overflows, its element count differs from values, or storage allocation/upload fails.

This variant uploads on this thread’s default runtime. An runtime initialization failure is returned before the upload starts.

Source

pub fn new_from_f32_on( runtime: &Runtime, shape: impl Into<Vec<usize>>, values: &[f32], ) -> Result<Self>

Create an FP32 matrix and initialize its device-visible storage on a particular runtime.

This is the new_from_f32 contract evaluated on runtime instead of this thread’s default runtime.

§Errors

Returns an error when the shape overflows, its element count differs from values, or storage allocation/upload fails.

Source

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

Return the matrix shape.

Source

pub const fn dtype(&self) -> DType

Return the matrix scalar representation.

Source

pub const fn num_elements(&self) -> usize

Return the number of logical dense elements.

Source

pub fn flatten(&self) -> Result<Self>

Return a zero-copy one-dimensional view over all elements.

Equivalent to self.reshape([self.num_elements()]).

§Errors

Returns an error when the element count overflows or storage allocation fails.

Source

pub fn unsqueeze(&self, dim: usize) -> Result<Self>

Return a zero-copy view with a new size-one axis inserted at dim.

dim must be in 0..=self.shape().len(). Negative indices are not supported; use self.shape().len() to append at the end.

§Errors

Returns an error when dim is out of range.

Source

pub fn squeeze(&self, dim: usize) -> Result<Self>

Return a zero-copy view with one size-one axis removed.

dim must be in 0..self.shape().len() and the selected axis must have extent one. Negative indices are not supported.

§Errors

Returns an error when dim is out of range or the selected axis is not size one.

Source

pub fn read_f32(&self) -> Result<Vec<f32>>

Read all FP32 values back to host memory.

§Errors

This is an explicit host-observation boundary: it submits the pending eager batch when this matrix is still recorded, then waits for the exact GPU event that produced it before mapping its storage. Returns an error when this is not an FP32 matrix or when submission, completion, mapping, or cache invalidation fails.

Source

pub fn try_read_f32(&self) -> Result<Vec<f32>>

Attempt to read all FP32 values without waiting for pending GPU work.

§Errors

Returns an error when this is not an FP32 matrix, crate::ErrorKind::NotReady when GPU production is pending, or an error when mapping or cache invalidation fails.

Source

pub fn read<T: Element>(&self) -> Result<Vec<T>>

Read all values into their exact admitted Rust scalar representation.

§Errors

Returns an error before submission or waiting when T does not match this matrix’s dtype. Otherwise this submits its pending eager batch when needed, waits for the exact producing event, and returns an error when submission, completion, mapping, or cache invalidation fails.

Source

pub fn try_read<T: Element>(&self) -> Result<Vec<T>>

Attempt typed readback without waiting for pending GPU work.

§Errors

Returns an error when T does not match this matrix’s dtype, crate::ErrorKind::NotReady when production is pending, or an error when mapping or cache invalidation fails.

Source

pub fn value_id(&self) -> u64

Stable identity of this value for plan-validity comparisons.

Two matrices constructed independently never share an id; views and clones of one allocation do. Compiled-plan owners (OA-CC-20) compare identities to reject replaying a captured plan against different storage.

Source§

impl Matrix

Source

pub fn add(&self, right: &Matrix) -> Result<Self>

Add two matrices elementwise using multidirectional broadcasting.

Delegates to crate::matrix::add.

Source

pub fn bias_add(&self, right: &Matrix) -> Result<Self>

Add a bias matrix to another matrix elementwise using multidirectional broadcasting.

Delegates to crate::matrix::bias_add.

Source

pub fn sub(&self, right: &Matrix) -> Result<Self>

Subtract two FP32 matrices elementwise using multidirectional broadcasting.

Delegates to crate::matrix::sub.

Source

pub fn mul(&self, right: &Matrix) -> Result<Self>

Multiply two FP32 matrices elementwise.

Delegates to crate::matrix::mul.

Source

pub fn div(&self, right: &Matrix) -> Result<Self>

Divide two FP32 matrices elementwise using multidirectional broadcasting.

Delegates to crate::matrix::div.

Source

pub fn scale(&self, scalar: f32) -> Result<Self>

Multiply every FP32 matrix element by a scalar.

Delegates to crate::matrix::scale.

Source

pub fn neg(&self) -> Result<Self>

Negate every FP32 matrix element.

Delegates to crate::matrix::neg.

Source

pub fn abs(&self) -> Result<Self>

Take the absolute value of every FP32 matrix element.

Delegates to crate::matrix::abs.

Source

pub fn log(&self) -> Result<Self>

Take the natural logarithm of every FP32 matrix element.

Delegates to crate::matrix::log.

Source

pub fn sqrt(&self) -> Result<Self>

Take the square root of every FP32 matrix element.

Delegates to crate::matrix::sqrt.

Source

pub fn pow(&self, exponent: f32) -> Result<Self>

Raise every FP32 matrix element to a scalar exponent.

Delegates to crate::matrix::pow.

Source

pub fn add_scalar(&self, scalar: f32) -> Result<Self>

Add a scalar to every FP32 matrix element.

Delegates to crate::matrix::add_scalar.

Source

pub fn sub_scalar(&self, scalar: f32) -> Result<Self>

Subtract a scalar from every FP32 matrix element.

Delegates to crate::matrix::sub_scalar.

Source

pub fn div_scalar(&self, scalar: f32) -> Result<Self>

Divide every FP32 matrix element by a scalar.

Delegates to crate::matrix::div_scalar.

Source

pub fn exp(&self) -> Result<Self>

Take the exponential of every FP32 matrix element.

Delegates to crate::matrix::exp.

Source

pub fn sin(&self) -> Result<Self>

Take the sine of every FP32 matrix element.

Delegates to crate::matrix::sin.

Source

pub fn cos(&self) -> Result<Self>

Take the cosine of every FP32 matrix element.

Delegates to crate::matrix::cos.

Source

pub fn reciprocal(&self) -> Result<Self>

Take the reciprocal of every FP32 matrix element.

Delegates to crate::matrix::reciprocal.

Source

pub fn clamp_max(&self, max: f32) -> Result<Self>

Cap every FP32 matrix element at an upper bound.

Delegates to crate::matrix::clamp_max.

Source

pub fn clamp_min(&self, min: f32) -> Result<Self>

Raise every FP32 matrix element to a lower bound.

Delegates to crate::matrix::clamp_min.

Source

pub fn copy(&self) -> Result<Self>

Deep-copy a dense matrix into independent device storage.

Delegates to crate::matrix::copy.

Source

pub fn matmul(&self, right: &Matrix) -> Result<Self>

Multiply A by the transpose of B using the OA weight-layout convention.

Delegates to crate::matrix::matmul.

Source

pub fn softmax(&self, dim: i32) -> Result<Self>

Delegates to crate::matrix::softmax.

Source

pub fn log_softmax(&self, dim: i32) -> Result<Self>

Source

pub fn sum(&self, dim: i32) -> Result<Self>

Delegates to crate::matrix::sum.

Source

pub fn mean(&self, dim: i32) -> Result<Self>

Delegates to crate::matrix::mean.

Source

pub fn max(&self, dim: i32) -> Result<Self>

Delegates to crate::matrix::max.

Source

pub fn argmax(&self, dim: i32) -> Result<i64>

Delegates to crate::matrix::argmax.

Source

pub fn categorical_accuracy_count(&self, labels: &Matrix) -> Result<Self>

Source

pub fn masked_categorical_accuracy_count( &self, labels: &Matrix, mask: &Matrix, ) -> Result<Self>

Source

pub fn philox_uniform(&self, low: f32, high: f32, seed: u64) -> Result<Self>

Source

pub fn philox_normal(&self, mean: f32, stddev: f32, seed: u64) -> Result<Self>

Source

pub fn dropout(&self, probability: f32, seed: u64) -> Result<Self>

Delegates to crate::matrix::dropout.

Source

pub fn sample_logits( &self, temperature: f32, top_k: i32, top_p: f32, seed: u64, ) -> Result<Self>

Source

pub fn top_k(&self, k: i32, dim: i32) -> Result<TopKResult>

Delegates to crate::matrix::top_k.

Source

pub fn top_k_mask(&self, num_experts: usize) -> Result<Self>

Source

pub fn moe_expert_plan(&self, num_experts: usize) -> Result<MoeExpertPlan>

Source

pub fn moe_routing_bias_update( &self, bias: &Matrix, experts_per_token: usize, gamma: f32, ) -> Result<()>

Source

pub fn slice(&self, dim: i32, start: i64, end: i64) -> Result<Self>

Delegates to crate::matrix::slice.

Source

pub fn pad(&self, pads: &[usize], mode: PadMode, fill: f32) -> Result<Self>

Delegates to crate::matrix::pad.

Source

pub fn repeat_interleave(&self, repeats: usize, dim: i32) -> Result<Self>

Source

pub fn gather(&self, indices: &Matrix) -> Result<Self>

Delegates to crate::matrix::gather.

Source

pub fn gather_last_dim(&self, indices: &Matrix) -> Result<Self>

Source

pub fn transpose(&self, dim0: i32, dim1: i32) -> Result<Self>

Source

pub fn equal(&self, value: f32) -> Result<Self>

Delegates to crate::matrix::equal.

Source

pub fn causal_mask(&self) -> Result<Self>

Source

pub fn greater_equal(&self, value: f32) -> Result<Self>

Source

pub fn split(&self, sizes: &[i64], dim: i32) -> Result<Vec<Matrix>>

Delegates to crate::matrix::split.

Source

pub fn compact_rows(&self, mask: &Matrix) -> Result<CompactRowsResult>

Source

pub fn scatter_rows( &self, source: &Matrix, row_map: &Matrix, count: &Matrix, ) -> Result<Self>

Source

pub fn scatter_rows_indirect( &self, source: &Matrix, plan: &CompactRowsResult, ) -> Result<Self>

Source

pub fn cast_f32_i32(&self) -> Result<Self>

Source

pub fn cast_i32_f32(&self) -> Result<Self>

Source

pub fn reshape(&self, shape: impl Into<Vec<usize>>) -> Result<Self>

Delegates to crate::matrix::reshape.

Trait Implementations§

Source§

impl Add for &Matrix

&mat_a + &mat_b — elementwise add with broadcasting.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: &Matrix) -> Result<Matrix>

Performs the + operation. Read more
Source§

impl Add<&Matrix> for f32

scalar + &mat — add a scalar to every element (left-hand scalar form).

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: &Matrix) -> Result<Matrix>

Performs the + operation. Read more
Source§

impl Add<f32> for &Matrix

&mat + scalar — add a scalar to every element.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: f32) -> Result<Matrix>

Performs the + operation. Read more
Source§

impl Clone for Matrix

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 Div for &Matrix

&mat_a / &mat_b — elementwise divide with broadcasting.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: &Matrix) -> Result<Matrix>

Performs the / operation. Read more
Source§

impl Div<f32> for &Matrix

&mat / scalar — divide every element by a scalar.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: f32) -> Result<Matrix>

Performs the / operation. Read more
Source§

impl Mul for &Matrix

&mat_a * &mat_b — elementwise multiply (not matmul).

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: &Matrix) -> Result<Matrix>

Performs the * operation. Read more
Source§

impl Mul<&Matrix> for f32

scalar * &mat — scale every element (left-hand scalar form).

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: &Matrix) -> Result<Matrix>

Performs the * operation. Read more
Source§

impl Mul<f32> for &Matrix

&mat * scalar — scale every element.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: f32) -> Result<Matrix>

Performs the * operation. Read more
Source§

impl Neg for &Matrix

-&mat — elementwise negate.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Result<Matrix>

Performs the unary - operation. Read more
Source§

impl Neg for Matrix

-mat — elementwise negate of an owned matrix (avoids a & at call sites where the value is already a temporary, e.g. -(&a * &b)?).

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Result<Matrix>

Performs the unary - operation. Read more
Source§

impl Sub for &Matrix

&mat_a - &mat_b — elementwise subtract with broadcasting.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: &Matrix) -> Result<Matrix>

Performs the - operation. Read more
Source§

impl Sub<f32> for &Matrix

&mat - scalar — subtract a scalar from every element.

Source§

type Output = Result<Matrix, Error>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: f32) -> Result<Matrix>

Performs the - operation. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Matrix

§

impl !Send for Matrix

§

impl !Sync for Matrix

§

impl !UnwindSafe for Matrix

§

impl Forget for Matrix

§

impl Freeze for Matrix
where *const RcInner<RefCell<RuntimeState>> is !null: Freeze, PhantomData<RcInner<RefCell<RuntimeState>>>: Freeze, *const RcInner<StorageInner> is !null: Freeze, PhantomData<RcInner<StorageInner>>: Freeze, *const u8 is !null: Freeze, PhantomData<usize>: Freeze, *const RcInner<MatrixSemantic> is !null: Freeze, PhantomData<RcInner<MatrixSemantic>>: Freeze, PhantomData<Rc<()>>: Freeze,

§

impl Move for Matrix

§

impl Unpin for Matrix
where Rc<RefCell<RuntimeState>>: Unpin, Rc<StorageInner>: Unpin, *const u8 is !null: Unpin, Rc<MatrixSemantic>: Unpin, Rc<()>: Unpin,

§

impl UnsafeUnpin for Matrix
where *const RcInner<RefCell<RuntimeState>> is !null: UnsafeUnpin, PhantomData<RcInner<RefCell<RuntimeState>>>: UnsafeUnpin, *const RcInner<StorageInner> is !null: UnsafeUnpin, PhantomData<RcInner<StorageInner>>: UnsafeUnpin, *const u8 is !null: UnsafeUnpin, PhantomData<usize>: UnsafeUnpin, *const RcInner<MatrixSemantic> is !null: UnsafeUnpin, PhantomData<RcInner<MatrixSemantic>>: UnsafeUnpin, PhantomData<Rc<()>>: UnsafeUnpin,

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<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

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<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

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.