Skip to main content

Tensor

Struct Tensor 

Source
pub struct Tensor<T: Copy + Default + DType, const N: usize, const R: usize> { /* private fields */ }
Expand description

Owned, fixed-capacity tensor stored inline.

  • T — scalar element type (Copy + Default + DType).
  • N — maximum element capacity (compile-time).
  • R — tensor rank / number of dimensions (compile-time).

len tracks live elements (≤ N). Shape is [usize; R] with all dimensions active. Rank-0 scalars use R = 0.

Byte size is computed, not stored — one multiply is cheaper than 8 bytes of struct overhead on a constrained MCU.

§Examples

// TF Lite Micro person detection input.
let img = Tensor::<u8, 9216, 4>::nhwc(1, 96, 96, 1, &pixels);

// Classifier output.
let out = Tensor::<i8, 3, 2>::nc(1, 3, &scores);

// Flat feature vector.
let v = Tensor::<f32, 128, 1>::from_slice(&features);

// Destructure shape for processing.
let [batch, height, width, channels] = *img.shape();
let pixel = img.at([0, 10, 20, 0]);

Implementations§

Source§

impl<T: Copy + Default + DType, const N: usize, const R: usize> Tensor<T, N, R>

Source

pub fn from_shape(shape: [usize; R], data: &[T]) -> Self

Create from a shape and data slice.

§Panics
  • If data.len() > N.
  • In debug: if the product of shape != data.len().
Source

pub fn filled(shape: [usize; R], value: T) -> Self

Create filled with value.

§Panics

If the shape product exceeds N.

Source

pub fn zeros(shape: [usize; R]) -> Self

Create zeroed with the given shape.

Source

pub fn data_type(&self) -> DataType

The DataType of the scalar elements.

Source

pub fn len(&self) -> usize

Number of live elements.

Source

pub fn is_empty(&self) -> bool

Whether the tensor has zero live elements.

Source

pub const fn capacity(&self) -> usize

Compile-time element capacity.

Source

pub const fn rank(&self) -> usize

Rank (compile-time constant).

Source

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

Active shape dimensions.

Source

pub fn as_slice(&self) -> &[T]

Borrow the live data.

Source

pub fn as_mut_slice(&mut self) -> &mut [T]

Mutably borrow the live data.

Source

pub fn byte_len(&self) -> usize

Total bytes of live data (computed, not stored).

Source

pub fn reshape(&mut self, new_shape: [usize; R])

Reshape in place (metadata only).

§Panics

In debug: if the shape product != self.len.

Source

pub fn is_compatible(&self) -> bool

Validate that the shape product matches the element count.

Source

pub fn at(&self, index: [usize; R]) -> T

Read element by multi-dimensional index.

§Panics

If the flat index is out of bounds.

Source

pub fn set(&mut self, index: [usize; R], value: T)

Write element by multi-dimensional index.

§Panics

If the flat index is out of bounds.

Source§

impl<T: Copy + Default + DType, const N: usize> Tensor<T, N, 0>

Source

pub fn scalar(value: T) -> Self

Create a rank-0 scalar.

Source

pub fn value(&self) -> T

Read the scalar value.

Source§

impl<T: Copy + Default + DType, const N: usize> Tensor<T, N, 1>

Source

pub fn from_slice(data: &[T]) -> Self

Create from a data slice (shape inferred as [data.len()]).

Source§

impl<T: Copy + Default + DType, const N: usize> Tensor<T, N, 2>

Source

pub fn nc(batch: usize, classes: usize, data: &[T]) -> Self

[batch, classes] — classifier output (TF Lite Micro softmax, etc.).

Source

pub fn matrix(rows: usize, cols: usize, data: &[T]) -> Self

[rows, cols] — 2-D matrix.

Source§

impl<T: Copy + Default + DType, const N: usize> Tensor<T, N, 3>

Source

pub fn sequence( batch: usize, time_steps: usize, features: usize, data: &[T], ) -> Self

[batch, time_steps, features] — sequence / spectrogram (keyword spotting, audio models).

Source

pub fn hwc(height: usize, width: usize, channels: usize, data: &[T]) -> Self

[height, width, channels] — single image, no batch dim (common in resource-constrained pipelines).

Source§

impl<T: Copy + Default + DType, const N: usize> Tensor<T, N, 4>

Source

pub fn nhwc( batch: usize, height: usize, width: usize, channels: usize, data: &[T], ) -> Self

[batch, height, width, channels] — TF Lite / TF Lite Micro standard.

Source

pub fn nchw( batch: usize, channels: usize, height: usize, width: usize, data: &[T], ) -> Self

[batch, channels, height, width] — PyTorch / tract default.

Trait Implementations§

Source§

impl<T: Clone + Copy + Default + DType, const N: usize, const R: usize> Clone for Tensor<T, N, R>

Source§

fn clone(&self) -> Tensor<T, N, R>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl ComputeBackend<Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>, Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>> for TestTensorBackend

Source§

type Model = TestTensorModel

Concrete model type (no trait objects).
Source§

type Error = InferenceError

Backend-specific error.
Source§

type ModelDescriptor<'d> = ()

Backend-chosen borrowed descriptor used to load a model. Read more
Source§

fn capabilities(&self) -> BackendCapabilities

Capability report.
Source§

fn load_model<'d>( &self, _desc: Self::ModelDescriptor<'d>, ) -> Result<Self::Model, Self::Error>

Load a model from a descriptor.
Source§

impl ComputeModel<Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>, Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>> for TestTensorModel

Source§

fn init(&mut self) -> Result<(), InferenceError>

Prepare internal state (allocate work buffers, compile kernels, etc.).
Source§

fn infer_one( &mut self, inp: &TestTensor, out: &mut TestTensor, ) -> Result<(), InferenceError>

Single-item inference (1×1).
Source§

fn infer_batch( &mut self, inputs: Batch<'_, TestTensor>, outputs: &mut [TestTensor], ) -> Result<(), InferenceError>

Optional: batched inference. Default loops infer_one.
Source§

fn drain(&mut self) -> Result<(), InferenceError>

Ensure outstanding device work is complete (if any).
Source§

fn reset(&mut self) -> Result<(), InferenceError>

Reset internal state to a known baseline (drop caches, etc.).
Source§

fn metadata(&self) -> ModelMetadata

Return model metadata (I/O placement preferences, limits).
Source§

impl<T: Copy + Default + DType + Debug, const N: usize, const R: usize> Debug for Tensor<T, N, R>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Copy + Default + DType, const N: usize, const R: usize> Default for Tensor<T, N, R>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<T: Copy + Default + DType + PartialEq, const N: usize, const R: usize> PartialEq for Tensor<T, N, R>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: Copy + Default + DType, const N: usize, const R: usize> Payload for Tensor<T, N, R>

Source§

fn buffer_descriptor(&self) -> BufferDescriptor

Return a descriptor containing the byte size of this payload.
Source§

impl Sink<Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>, 1> for TestSinkNodeTensor

Source§

type Error = Infallible

Sink-specific error type for open() or consume().
Source§

fn open(&mut self) -> Result<(), Self::Error>

Prepare the sink for consumption (open file/device, connect network, etc.). Read more
Source§

fn consume(&mut self, msg: &Message<TestTensor>) -> Result<(), Self::Error>

Consume a single message pulled from port. Read more
Source§

fn input_acceptance(&self) -> [PlacementAcceptance; 1]

Input placement acceptances for zero-copy compatibility.
Source§

fn capabilities(&self) -> NodeCapabilities

Describe sink capabilities (device streams, degrade tiers, etc.).
Source§

fn policy(&self) -> NodePolicy

Provide the node policy bundle (batching/budget/deadlines).
Source§

fn select_input(&mut self, occ: &[EdgeOccupancy; IN]) -> Option<usize>

Optional: choose which input to read this step based on occupancies. Read more
Source§

impl<Clock, const BACKLOG_CAP: usize> Source<Tensor<u32, TEST_TENSOR_ELEMENT_COUNT, 2>, 1> for TestCounterSourceTensor<Clock, BACKLOG_CAP>
where Clock: PlatformClock,

Source§

fn peek_ingress_creation_tick(&self, item_index: usize) -> Option<u64>

Peek the creation tick of the item_index’th ingress item (0 = oldest). Non-blocking and non-destructive. Returns None if metadata is not available (no backlog) or item_index is out of range.

Source§

type Error = Infallible

Source-specific error type for open().
Source§

fn open(&mut self) -> Result<(), Self::Error>

Prepare the source for production (e.g., open device, init driver). Read more
Source§

fn try_produce(&mut self) -> Option<(usize, Message<TestTensor>)>

Attempt to produce exactly one (port, message) pair. Read more
Source§

fn ingress_occupancy(&self) -> EdgeOccupancy

Report ingress pressure (items/bytes before the source). Read more
Source§

fn output_acceptance(&self) -> [PlacementAcceptance; 1]

Return output placement acceptances for zero-copy compatibility.
Source§

fn capabilities(&self) -> NodeCapabilities

Describe source capabilities (device streams, degrade tiers, etc.).
Source§

fn policy(&self) -> NodePolicy

Provide the node policy bundle (batching/budget/deadlines).
Source§

fn ingress_policy(&self) -> EdgePolicy

Provude the ingress edge policy for this source node.
Source§

fn into_sourcenode(self, policy: NodePolicy) -> SourceNode<Self, OutP, OUT>
where Self: Sized,

Convenience: wrap this source in a SourceNode with the provided policy. Read more
Source§

impl<T: Copy + Copy + Default + DType, const N: usize, const R: usize> Copy for Tensor<T, N, R>

Source§

impl<T: Copy + Default + DType + Eq, const N: usize, const R: usize> Eq for Tensor<T, N, R>

Auto Trait Implementations§

§

impl<T, const N: usize, const R: usize> Freeze for Tensor<T, N, R>
where T: Freeze,

§

impl<T, const N: usize, const R: usize> RefUnwindSafe for Tensor<T, N, R>
where T: RefUnwindSafe,

§

impl<T, const N: usize, const R: usize> Send for Tensor<T, N, R>
where T: Send,

§

impl<T, const N: usize, const R: usize> Sync for Tensor<T, N, R>
where T: Sync,

§

impl<T, const N: usize, const R: usize> Unpin for Tensor<T, N, R>
where T: Unpin,

§

impl<T, const N: usize, const R: usize> UnsafeUnpin for Tensor<T, N, R>
where T: UnsafeUnpin,

§

impl<T, const N: usize, const R: usize> UnwindSafe for Tensor<T, N, R>
where T: UnwindSafe,

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

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.