Skip to main content

TracedTensor

Struct TracedTensor 

Source
pub struct TracedTensor {
    pub id: TracedTensorId,
    pub rank: usize,
    pub dtype: DType,
    pub val: LocalValueId,
    /* private fields */
}

Fields§

§id: TracedTensorId§rank: usize§dtype: DType§val: LocalValueId

Implementations§

Source§

impl TracedTensor

Source

pub fn slice_axis(&self, axis: usize, range: Range<usize>) -> Result<Self>

Slice one axis with an exclusive-end range, keeping all other axes.

§Examples
use tenferro_runtime::TracedTensor;

let x = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
let y = x.slice_axis(0, 1..3).unwrap();
assert_eq!(y.try_concrete_shape(), Some(vec![2]));
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside the concrete rank, or InvalidArgument when range is outside the selected axis extent.

Source

pub fn slice_builder(&self) -> TracedSliceBuilder<'_>

Start a rank-preserving slicing builder for this tensor.

§Examples
use tenferro_runtime::TracedTensor;

let x = TracedTensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0]).unwrap();
let y = x.slice_builder().axis(0, 0..2).apply().unwrap();
assert_eq!(y.try_concrete_shape(), Some(vec![2]));
Source

pub fn take_axis(&self, axis: usize, indices: &[usize]) -> Result<Self>

Select entries from one axis using host-known indices.

§Examples
use tenferro_runtime::TracedTensor;

let x = TracedTensor::from_vec_col_major(vec![3], vec![10.0_f64, 20.0, 30.0]).unwrap();
let y = x.take_axis(0, &[2, 0]).unwrap();
assert_eq!(y.try_concrete_shape(), Some(vec![2]));
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside the concrete rank, or InvalidArgument when an index list cannot be applied to the selected axis.

Source

pub fn index_select(&self, axis: isize, positions: &[usize]) -> Result<Self>

Select entries from one axis using host-known positions.

§Examples
use tenferro_cpu::CpuBackend;
use tenferro_runtime::{GraphCompiler, Runtime, Tensor, TracedTensor};

let x = TracedTensor::from_tensor_concrete_shape(
    Tensor::from_vec_col_major(vec![3], vec![10.0_f64, 20.0, 30.0]).unwrap(),
)
.unwrap();
let y = x.index_select(-1, &[2, 0]).unwrap();
let mut compiler = GraphCompiler::new();
let program = compiler.compile(&y).unwrap();
let backend = CpuBackend::new();
let mut builder = Runtime::builder();
builder
    .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
    .unwrap();
let runtime = builder.build().unwrap();
let outputs = runtime.run_compiled(&program, &[]).unwrap();
let out = &outputs[0];

assert_eq!(
    out.as_slice::<f64>().unwrap(),
    &[30.0, 10.0],
);
§Errors

Returns Error::Validation with InvalidArgument when the tensor shape is not concrete, AxisOutOfBounds when axis is outside its rank, or InvalidArgument when a position is outside the selected axis extent.

Source

pub fn stack(tensors: &[&Self], dim: isize) -> Result<Self>

Stack tensors along a newly inserted axis.

§Examples
use tenferro_cpu::CpuBackend;
use tenferro_runtime::{GraphCompiler, Runtime, Tensor, TracedTensor};

let a = TracedTensor::from_tensor_concrete_shape(Tensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap()).unwrap();
let b = TracedTensor::from_tensor_concrete_shape(Tensor::from_vec_col_major(vec![], vec![2.0_f64]).unwrap()).unwrap();
let stacked = TracedTensor::stack(&[&a, &b], -1).unwrap();
let mut compiler = GraphCompiler::new();
let program = compiler.compile(&stacked).unwrap();
let backend = CpuBackend::new();
let mut builder = Runtime::builder();
builder
    .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
    .unwrap();
let runtime = builder.build().unwrap();
let outputs = runtime.run_compiled(&program, &[]).unwrap();
let out = &outputs[0];

assert_eq!(
    out.as_slice::<f64>().unwrap(),
    &[1.0, 2.0],
);
§Errors

Returns Error::Validation with InvalidArgument for an empty input list, ShapeMismatch for incompatible input shapes, or AxisOutOfBounds when dim is outside the output rank.

Source

pub fn concatenate(tensors: &[&Self], axis: usize) -> Result<Self>

Concatenate tensors along one existing axis.

§Errors

Returns Error::Validation with InvalidArgument for an empty input list, RankMismatch/ShapeMismatch for incompatible input shapes, or AxisOutOfBounds when axis is outside the input rank.

Source§

impl TracedTensor

Source

pub fn graph(&self) -> &Arc<Graph<StdTensorOp>>

Return the graph that owns this traced tensor’s current value.

§Examples
use tenferro_runtime::TracedTensor;

let x = TracedTensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
let _graph = x.graph();
Source

pub fn attached_data(&self) -> Option<&Arc<Tensor>>

Return the concrete tensor data attached to this traced value, if any.

Placeholder tensors created with input_concrete_shape or input_symbolic_shape have no attached data until execution bindings provide it.

§Examples
use tenferro_runtime::{DType, TracedTensor};

let concrete = TracedTensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();
assert!(concrete.attached_data().is_some());

let placeholder = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();
assert!(placeholder.attached_data().is_none());
Source

pub fn from_tensor_concrete_shape(tensor: Tensor) -> Result<Self>

Build a TracedTensor leaf from a concrete Tensor, keeping its shape as a concrete shape_hint.

This is the common constructor when you have concrete tensor data that you want to use both for graph building and for evaluation. The resulting tensor is treated as a concrete-shape leaf by downstream passes (binary einsum decomposition, build-time reshape folding, etc.).

§Examples
use tenferro_runtime::{Tensor, TracedTensor};

let a = TracedTensor::from_tensor_concrete_shape(
    Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(),
)
.unwrap();
assert_eq!(a.rank, 2);
assert!(a.is_concrete_shape());
§Errors

Returns Error::RuntimeStateSource when graph metadata registration cannot retain the concrete tensor’s shape or dtype.

Source

pub fn from_tensor_symbolic_shape(tensor: Tensor) -> Result<Self>

Build a TracedTensor leaf from a concrete Tensor but advertise a symbolic shape during graph construction.

The tensor data is still attached (so plain eval works without bindings), but graph passes see the leaf as shape-symbolic. This is useful for building a single traced program that should not bake in shape-specific optimizations.

§Examples
use tenferro_runtime::{Tensor, TracedTensor};

let t = TracedTensor::from_tensor_symbolic_shape(
    Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(),
)
.unwrap();
assert_eq!(t.rank, 2);
assert!(!t.is_concrete_shape());
§Errors

Returns Error::RuntimeStateSource when symbolic graph metadata registration is unavailable or its registry state is poisoned.

Source

pub fn input_concrete_shape(dtype: DType, shape: &[usize]) -> Result<Self>

Build a data-less placeholder leaf with a fixed (concrete) shape.

Must be passed as an input to crate::Runtime::run_compiled before evaluation. Use this when you know the exact shape of the input but want to build the graph once and feed different concrete tensors at execution time.

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let x = TracedTensor::input_concrete_shape(DType::F64, &[2, 3]).unwrap();
assert_eq!(x.rank, 2);
assert!(x.is_concrete_shape());
§Errors

Returns Error::RuntimeStateSource when graph metadata registration fails or the registry state is poisoned. dtype and shape are metadata values and are not revalidated by this constructor.

Source

pub fn input_symbolic_shape(dtype: DType, rank: usize) -> Result<Self>

Build a data-less placeholder leaf with the given rank but fully symbolic shape (every dim is a distinct SymDim::TensorAxis).

Must be passed as an input to crate::Runtime::run_compiled before evaluation. Use this to build shape-agnostic graphs.

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let x = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
assert_eq!(x.rank, 2);
assert!(!x.is_concrete_shape());
§Errors

Returns Error::RuntimeStateSource when graph metadata registration fails or the registry state is poisoned. rank is recorded as the symbolic placeholder rank and is not otherwise rejected here.

Source

pub fn from_vec_col_major<T: TensorScalar>( shape: impl IntoShapeVec, data: Vec<T>, ) -> Result<Self>

Build a concrete-shape TracedTensor leaf from column-major typed Vec<T> data.

The data must already be in tenferro’s physical column-major order.

§Examples
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(
    vec![2, 3],
    vec![1.0_f64, 4.0, 2.0, 5.0, 3.0, 6.0],
)?;
assert_eq!(a.rank, 2);
§Errors

Returns Error::TensorRuntime containing ValidationError::ShapeDataLengthMismatch when the shape product does not equal data.len(), or ValidationError::IntegerOverflow when the shape product cannot be represented by usize.

Source

pub fn dtype(&self) -> DType

Return the tensor element dtype recorded for this traced value.

Source

pub fn is_concrete_shape(&self) -> bool

Returns true iff every dim of this tensor’s shape_hint is a constant SymDim (i.e. the shape is fully known at graph-build time).

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
assert!(a.is_concrete_shape());
assert!(!b.is_concrete_shape());
Source

pub fn try_concrete_shape(&self) -> Option<Vec<usize>>

Return the fully-concrete shape of this tensor, if every dim of its shape-hint is a constant SymDim. Returns None if any dimension is symbolic.

This is the counterpart to Self::is_concrete_shape for callers that need to use the concrete shape (e.g. external composition wrappers building broadcast_in_dim payloads from known shapes).

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
assert_eq!(a.try_concrete_shape(), Some(vec![2, 3]));

let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
assert!(b.try_concrete_shape().is_none());
Source

pub fn concrete_shape(&self) -> Result<Vec<usize>>

Return the concrete tensor shape.

Returns an error when a shape hint is missing or any dimension is symbolic. Composite traced ops that require concrete sizes should propagate this error instead of panicking.

§Errors

Returns Error::Validation with InvalidArgument when this tensor has no shape hint or any dimension is symbolic.

Source

pub fn input_key(&self) -> Option<TensorInputKey>

If this TracedTensor is a leaf (single-node input graph), return its input key. Computed tensors return None.

Source

pub fn add(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise addition with NumPy-style broadcasting.

Prefer using the + operator when it reads naturally.

A longer expression such as a + b + c does not compose because the first + returns Result<TracedTensor, Error>, so the second + would receive a result rather than a tensor. Use ? at each step or the explicit fallible method chain shown below when the operation sequence is more important than notation:

§Examples
let y = x.add(&z);
let y2 = &x + &z;
let ab = (a + b)?;
let sum = (&ab + c)?;
let method_chain = a.add(b)?.add(c)?;
let _ = method_chain;

Tenferro prioritizes robust error handling over the conciseness of chained operator notation; the explicit fallible methods are the canonical form for longer sequences.

§Errors

Returns Error::Validation with ShapeMismatch when operand shapes cannot be broadcast, or Error::RuntimeStateSource when graph metadata registration fails.

§Deferred errors

If symbolic dimensions prevent shape comparison during graph construction, the same ShapeMismatch can be reported during compilation or execution, with the corresponding ErrorPhase.

Source

pub fn sub(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise subtraction with NumPy-style broadcasting.

Prefer using the - operator when it reads naturally.

§Errors

Returns Error::Validation with ShapeMismatch when operand shapes cannot be broadcast, or Error::RuntimeStateSource when graph metadata registration fails.

§Deferred errors

If symbolic dimensions prevent shape comparison during graph construction, the same ShapeMismatch can be reported during compilation or execution, with the corresponding ErrorPhase.

Source

pub fn mul(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise multiplication with NumPy-style broadcasting.

Prefer using the * operator when it reads naturally.

§Examples
let y = x.mul(&z);
let y2 = &x * &z;
§Errors

Returns Error::Validation with ShapeMismatch when operand shapes cannot be broadcast, or Error::RuntimeStateSource when graph metadata registration fails.

§Deferred errors

If symbolic ranks prevent shape comparison during graph construction, the same ShapeMismatch can be reported during compilation or execution, with the corresponding ErrorPhase.

Source

pub fn div(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise division with NumPy-style broadcasting.

Prefer using the / operator when it reads naturally.

§Examples
let y = x.div(&z);
let y2 = &x / &z;
§Errors

Returns Error::Validation with ShapeMismatch when operand shapes cannot be broadcast, or Error::RuntimeStateSource when graph metadata registration fails.

§Deferred errors

If symbolic ranks prevent shape comparison during graph construction, the same ShapeMismatch can be reported during compilation or execution, with the corresponding ErrorPhase. For integer inputs, a zero divisor is reported during execution as Error::TensorRuntime containing a tenferro_tensor::Error::Extension classified as tenferro_tensor::ErrorKind::NumericalFailure and retaining the typed backend source; floating-point and complex zero divisors follow their numeric semantics instead.

Source

pub fn rem(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise remainder with NumPy-style broadcasting.

Prefer using the % operator when it reads naturally.

§Errors

Returns Error::Validation with ShapeMismatch when operand shapes cannot be broadcast, Error::Unsupported at ErrorPhase::GraphBuild when either operand has a complex dtype, or Error::RuntimeStateSource when graph metadata registration fails.

§Deferred errors

If symbolic ranks prevent shape comparison during graph construction, the same ShapeMismatch can be reported during compilation or execution, with the corresponding ErrorPhase. For integer inputs, a zero divisor is reported during execution as Error::TensorRuntime containing a tenferro_tensor::Error::Extension classified as tenferro_tensor::ErrorKind::NumericalFailure and retaining the typed backend source; floating-point zero divisors follow their numeric semantics.

Source

pub fn compare( &self, other: &TracedTensor, dir: CompareDir, ) -> Result<TracedTensor>

Elementwise comparison with NumPy-style broadcasting.

§Errors

Returns Error::Validation with ShapeMismatch when the concrete operands cannot be broadcast, Error::Unsupported when ordered comparison rejects a complex dtype, or Error::RuntimeStateSource when result metadata cannot be registered.

§Deferred errors

With same-rank symbolic operands, shape compatibility is retained as a graph constraint. A concrete mismatch is reported later as Error::TensorRuntime containing a typed validation source, with the failure phase identifying compilation or execution.

Source

pub fn maximum(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise maximum with NumPy-style broadcasting.

§Errors

Returns Error::Validation with ShapeMismatch when the concrete operands cannot be broadcast, Error::Unsupported when ordered maximum rejects a complex dtype, or Error::RuntimeStateSource when result metadata cannot be registered.

§Deferred errors

With same-rank symbolic operands, the broadcast constraint may fail at compile or execution and is returned as Error::TensorRuntime with its typed validation source.

Source

pub fn minimum(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise minimum with NumPy-style broadcasting.

§Errors

Returns Error::Validation with ShapeMismatch when the concrete operands cannot be broadcast, Error::Unsupported when ordered minimum rejects a complex dtype, or Error::RuntimeStateSource when result metadata cannot be registered.

§Deferred errors

With same-rank symbolic operands, the broadcast constraint may fail at compile or execution and is returned as Error::TensorRuntime with its typed validation source.

Source

pub fn where_select( condition: &TracedTensor, on_true: &TracedTensor, on_false: &TracedTensor, ) -> Result<TracedTensor>

Select values from on_true or on_false using condition.

§Errors

Returns Error::Validation with InvalidArgument when an operand lacks concrete shape metadata, or ShapeMismatch when the concrete condition and branches cannot share a broadcast shape. Dtype promotion failures are returned as Error::TensorRuntime with the typed UnsupportedDTypeConversion source; metadata failures retain Error::RuntimeStateSource.

Source

pub fn select( condition: &TracedTensor, on_true: &TracedTensor, on_false: &TracedTensor, ) -> Result<TracedTensor>

Alias for Self::where_select.

§Errors

Returns the same concrete failures as Self::where_select: Error::Validation with InvalidArgument/ShapeMismatch for shape metadata or broadcasting, Error::TensorRuntime with UnsupportedDTypeConversion for failed promotion, and Error::RuntimeStateSource for metadata registration.

Source

pub fn clamp( &self, lower: &TracedTensor, upper: &TracedTensor, ) -> Result<TracedTensor>

Clamp values elementwise between lower and upper bounds.

§Errors

Returns Error::Validation with InvalidArgument when an operand lacks concrete shape metadata, ShapeMismatch when bounds cannot be broadcast with the input, Error::Unsupported for an ordered complex dtype, or Error::RuntimeStateSource when metadata cannot be registered.

Source

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

Elementwise negation.

Prefer using the unary - operator when it reads naturally.

§Examples
let y = x.neg().unwrap();
let y2 = (-&x).unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn conj(&self) -> Result<TracedTensor>

Elementwise complex conjugate.

§Examples
let y = x.conj().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

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

Elementwise absolute value.

Complex inputs return real magnitudes (C32 -> F32, C64 -> F64).

§Examples
let y = x.abs().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn sign(&self) -> Result<TracedTensor>

Elementwise sign.

§Examples
let y = x.sign().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn scale_real(&self, factor: f64) -> Result<TracedTensor>

Scale by a real scalar: y = factor * x.

§Examples
let y = x.scale_real(2.0)?;
§Errors

Returns Error::Validation with InvalidArgument when an integer or boolean factor is non-finite or out of range for the input dtype, or Error::RuntimeStateSource when output metadata registration fails.

Source

pub fn scale_complex(&self, factor: Complex64) -> Result<TracedTensor>

Scale by a complex scalar: y = factor * x.

Only complex tensors support complex scaling. For a real scalar factor that should preserve the input dtype, prefer scale_real.

§Examples
use num_complex::Complex64;
let y = x.scale_complex(Complex64::new(0.0, 1.0)).unwrap(); // multiply by i
§Errors

Returns Error::Validation with InvalidArgument when a complex factor is applied to a non-complex dtype, or Error::RuntimeStateSource when output metadata registration fails.

Source

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

Elementwise exponential.

§Examples
let y = x.exp().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

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

Elementwise natural logarithm.

§Examples
let y = x.log().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

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

Elementwise sine.

§Examples
let y = x.sin().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

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

Elementwise cosine.

§Examples
let y = x.cos().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn tanh(&self) -> Result<TracedTensor>

Elementwise hyperbolic tangent.

§Examples
let y = x.tanh().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

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

Elementwise square root.

§Examples
let y = x.sqrt().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn rsqrt(&self) -> Result<TracedTensor>

Elementwise reciprocal square root.

§Examples
let y = x.rsqrt().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn pow(&self, other: &TracedTensor) -> Result<TracedTensor>

Elementwise power with NumPy-style broadcasting.

§Examples
let y = base.pow(&exp);
§Errors

Returns Error::Validation with ShapeMismatch when the concrete operands cannot be broadcast, or Error::RuntimeStateSource when result metadata cannot be registered.

§Deferred errors

A symbolic broadcast mismatch or integer negative exponent is discovered at compile or execution and is returned as Error::TensorRuntime with a typed ShapeMismatch or NegativeIntegerExponent numerical source and the corresponding ErrorPhase.

Source

pub fn expm1(&self) -> Result<TracedTensor>

Elementwise exp(x) - 1.

§Examples
let y = x.expm1().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn log1p(&self) -> Result<TracedTensor>

Elementwise log(1 + x).

§Examples
let y = x.log1p().unwrap();
§Errors

Returns Error::RuntimeStateSource when the graph metadata registry is unavailable or poisoned while recording the unary result.

Source

pub fn convert(&self, to: DType) -> Result<TracedTensor>

Convert the tensor to a different dtype using checked conversion.

Use cast when a lossy dtype projection is intended.

§Examples
use tenferro_runtime::DType;

let y = x.convert(DType::C64)?;
§Errors

Returns tenferro_tensor::Error::UnsupportedDTypeConversion when the requested pair is outside tenferro’s checked dtype-promotion lattice, or Error::Validation when graph metadata rejects the conversion. Use cast for explicit lossy dtype projection.

Source

pub fn cast(&self, to: DType) -> Result<TracedTensor>

Cast the tensor to a different dtype using explicit dtype projection.

cast may truncate, narrow precision, project complex values to their real component, or use boolean truthiness where the backend supports the requested projection.

§Examples
use tenferro_runtime::DType;

let y = x.cast(DType::I32).unwrap();
§Errors

Returns Error::TensorRuntime containing UnsupportedDTypeConversion when the requested input-to-target projection is not supported, or Error::RuntimeStateSource when converted-output metadata cannot be registered.

Source

pub fn dot_general( &self, other: &TracedTensor, config: DotGeneralConfig, ) -> Result<TracedTensor>

Generalized tensor contraction.

§Examples
let y = a.dot_general(&b, config)?;
§Errors

Returns Error::Validation with RankMismatch, AxisOutOfBounds, DuplicateAxis, or AxisRoleConflict when dimension numbers are invalid for the operand ranks, and Error::RuntimeStateSource when output metadata cannot be registered.

§Deferred errors

Contracting or batch dimensions whose sizes are symbolic are checked when concrete inputs reach compilation or execution. A mismatch is returned as Error::TensorRuntime with a typed ShapeMismatch source and its corresponding ErrorPhase.

Source

pub fn matmul(&self, other: &TracedTensor) -> Result<TracedTensor>

Matrix multiplication for rank-2 tensors.

§Errors

Returns Error::Validation with RankMismatch when either operand is not rank 2, ShapeMismatch::ContractedDimensions when known matrix dimensions differ, or Error::RuntimeStateSource when output metadata cannot be registered.

§Deferred errors

If either contracted dimension is symbolic, the mismatch is discovered at compilation or execution and returned as Error::TensorRuntime with its typed ShapeMismatch source.

Source

pub fn reduce_sum(&self, axes: Option<&[usize]>) -> Result<TracedTensor>

Sum over the given axes.

§Examples
let total = x.reduce_sum(None)?;
let rows = x.reduce_sum(Some(&[1]))?;
let identity = x.reduce_sum(Some(&[]))?;
assert_eq!(total.rank, 0);
assert_eq!(rows.rank, 1);
assert_eq!(identity.rank, 2);
§Errors

Returns Error::Validation with AxisOutOfBounds when an axis is outside the input rank or DuplicateAxis when axes repeats an axis, or Error::RuntimeStateSource when output metadata cannot be registered.

Source

pub fn reduce_sum_squares(&self, axes: &[usize]) -> Result<TracedTensor>

Sum elementwise squares over the requested axes.

Each value is squared in its input dtype before reduction. The initial supported dtypes are f32 and f64; other dtypes return a typed unsupported error during execution. Passing an empty axis slice returns the elementwise square without reducing rank.

This operation is useful when the squared sum is needed directly. Use the linalg norm APIs when a square root or complex magnitude semantics are required.

§Errors

Returns a typed validation error for invalid axes or a typed runtime-state error while registering output metadata.

§Deferred errors

Unsupported dtypes and backend execution failures are reported when the compiled graph is executed.

Source

pub fn reduce_max(&self, axes: Option<&[usize]>) -> Result<TracedTensor>

Reduce by taking the maximum along the given axes.

Used by tropical (max-plus) compositions: a max-plus reduction over an axis is ReduceMax on that axis.

§Examples
let y = x.reduce_max(Some(&[0]))?;
§Errors

Returns Error::Validation with AxisOutOfBounds when an axis is outside the input rank or DuplicateAxis when axes repeats an axis, Error::Unsupported when a non-empty maximum reduction receives a complex dtype, or Error::RuntimeStateSource when output metadata cannot be registered.

Source

pub fn reduce_min(&self, axes: Option<&[usize]>) -> Result<TracedTensor>

Reduce by taking the minimum along the given axes.

Used by tropical (min-plus) compositions: a min-plus reduction over an axis is ReduceMin on that axis.

§Examples
let y = x.reduce_min(Some(&[0]))?;
§Errors

Returns Error::Validation with AxisOutOfBounds when an axis is outside the input rank or DuplicateAxis when axes repeats an axis, Error::Unsupported when a non-empty minimum reduction receives a complex dtype, or Error::RuntimeStateSource when output metadata cannot be registered.

Source

pub fn reduce_prod(&self, axes: Option<&[usize]>) -> Result<TracedTensor>

Reduce by taking the product along the given axes.

§Examples
let y = x.reduce_prod(Some(&[0]))?;
§Errors

Returns Error::Validation with AxisOutOfBounds when an axis is outside the input rank or DuplicateAxis when axes repeats an axis, or Error::RuntimeStateSource when output metadata cannot be registered.

Source

pub fn reshape(&self, shape: &[usize]) -> Result<TracedTensor>

Reshape without changing element order.

§Examples
let y = x.reshape(&[2, 2])?;
§Errors

Returns Error::Validation with ShapeMismatch::ReshapeElementCount when a concrete input has a different element count, or IntegerOverflow when the target shape product overflows usize.

Source

pub fn sym_size(&self, axis: usize) -> Result<SymDim>

Return a symbolic expression for the size of one axis, suitable as an InputDim-style reference when composing with TracedTensor::reshape_sym.

Semantics: if this tensor’s shape_hint has a symbolic (non-constant) entry for axis, that entry is returned verbatim. Otherwise — including when shape_hint[axis] is a concrete SymDim::Concrete(n) — a SymDim::tensor_axis(self.id, axis) reference is returned so the resulting graph remains shape-polymorphic if the same graph is later evaluated against a differently-shaped binding.

For a canonical “what is the size of this axis?” query that reports the concrete size when it is known, prefer Self::axis_sym_dim.

§Examples
let rows = x.sym_size(0)?;
let cols = x.sym_size(1)?;
let y = x.reshape_sym(&[rows * cols]).unwrap();
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside this tensor’s rank.

Source

pub fn axis_sym_dim(&self, axis: usize) -> Result<SymDim>

Return the canonical SymDim for axis — the concrete SymDim::Concrete(n) when the size is known, otherwise a symbolic expression identifying this tensor’s axis.

Unlike Self::sym_size, this method does not rewrite concrete axes into TensorAxis references. It is the accessor external composition wrappers should use when building mixed concrete/symbolic target shapes for operations like Self::broadcast_in_dim_sym.

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
// Concrete axis: reports the constant size.
assert_eq!(a.axis_sym_dim(0).unwrap().constant_value(), Some(2));

let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
// Fully symbolic leaf: reports a TensorAxis reference.
assert!(b.axis_sym_dim(0).unwrap().constant_value().is_none());
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside this tensor’s rank.

Source

pub fn sym_shape(&self) -> Option<&[SymDim]>

Return the full symbolic shape of this tensor when a shape_hint is present.

Returns None for fully-symbolic placeholders produced via Self::input_symbolic_shape (where shape_hint is intentionally absent). For those, build the shape axis-by-axis via Self::axis_sym_dim.

§Examples
use tenferro_tensor::DType;
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
assert!(a.sym_shape().is_some());
assert_eq!(a.sym_shape().unwrap().len(), 2);

let b = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
assert!(b.sym_shape().is_none());
Source

pub fn reshape_sym(&self, shape: &[SymDim]) -> Result<TracedTensor>

Reshape using symbolic dimensions derived from traced tensor axes.

§Examples
let rows = x.sym_size(0)?;
let cols = x.sym_size(1)?;
let y = x.reshape_sym(&[rows * cols]).unwrap();
§Errors

Returns Error::SymbolicShapeConversion when a supplied symbolic dimension cannot be mapped to this graph, or Error::RuntimeStateSource when result metadata cannot be registered.

§Deferred errors

Element-count compatibility for symbolic dimensions is checked when concrete inputs reach compilation or execution. A mismatch is returned as Error::TensorRuntime with a typed ShapeMismatch source.

Source

pub fn broadcast_in_dim( &self, shape: &[usize], dims: &[usize], ) -> Result<TracedTensor>

Broadcast into a larger shape with explicit dimension placement.

§Examples
let y = x.broadcast_in_dim(&[2, 3], &[1])?;
§Errors

Returns Error::Validation with RankMismatch when dims does not have one entry per input axis, AxisOutOfBounds or DuplicateAxis for an invalid output mapping, or InvalidArgument when known dimensions cannot broadcast. Error::RuntimeStateSource reports failure to register the result metadata.

Source

pub fn broadcast_in_dim_sym( &self, shape: &[SymDim], dims: &[usize], shape_refs: &[&TracedTensor], ) -> Result<TracedTensor>

Broadcast into a symbolic target shape with explicit dimension placement.

Unlike Self::broadcast_in_dim, each axis of shape is a SymDim, so the target shape can mix concrete sizes (via SymDim::from(n)) with symbolic references to this tensor’s axes (via Self::axis_sym_dim) or to axes of other traced tensors.

When shape contains a SymDim that references a traced tensor other than self, the referenced tensor(s) must be supplied in shape_refs. They are wired into the built op as auxiliary shape-reference inputs — the op does not read their data, only their runtime shape. shape_refs must be listed in the same order in which their tensor IDs first appear when walking shape after any references to self. Usually the simplest correct thing is to pass each unique non-self reference tensor once.

§Examples
use tenferro_runtime::TracedTensor;

let a = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
let b = TracedTensor::from_vec_col_major(vec![3, 4], vec![1.0_f64; 12]).unwrap();
let m = a.axis_sym_dim(0)?;
let k = a.axis_sym_dim(1)?;
let n = b.axis_sym_dim(1)?;
// Broadcast `a[m, k]` to `[m, k, n]`, placing `a`'s axes at 0, 1
// and taking `n` from `b` as an auxiliary shape reference.
let a_b = a.broadcast_in_dim_sym(&[m, k, n], &[0, 1], &[&b])?;
assert_eq!(a_b.rank, 3);
§Errors

Returns Error::Validation with RankMismatch, AxisOutOfBounds, DuplicateAxis, or InvalidArgument when the output mapping or shape references are invalid, Error::SymbolicShapeConversion for an unmappable symbolic dimension, or Error::RuntimeStateSource when metadata cannot be registered.

§Deferred errors

If a symbolic output dimension is smaller than a non-unit input axis, the concrete broadcast check is deferred to compilation or execution and is returned as Error::TensorRuntime with a typed validation source.

Source

pub fn slice(&self, config: SliceConfig) -> Result<TracedTensor>

Slice with explicit start, limit, and stride per axis.

§Errors

Returns Error::Validation with RankMismatch when the start/limit/ stride vectors do not match the input rank, InvalidSliceStep when a stride is zero, InvalidSliceBounds when a limit precedes its start, or Error::RuntimeStateSource when output metadata cannot be registered.

Source

pub fn pad(&self, config: PadConfig) -> Result<TracedTensor>

Pad with zeros using StableHLO-style edge and interior padding.

§Errors

Returns Error::Validation with RankMismatch when padding vectors do not match the input rank, InvalidArgument for negative interior padding, or IntegerOverflow when the padded extent exceeds usize. Error::RuntimeStateSource is returned when output metadata cannot be registered.

Source

pub fn reverse(&self, axes: &[usize]) -> Result<TracedTensor>

Reverse the order of elements along the requested axes.

§Errors

Returns Error::Validation with AxisOutOfBounds when an axis is outside the input rank or DuplicateAxis when axes repeats one, or Error::RuntimeStateSource when result metadata cannot be registered.

Source

pub fn gather( &self, indices: &TracedTensor, config: GatherConfig, ) -> Result<TracedTensor>

Gather slices from self using integer start indices.

§Errors

Returns Error::Validation with RankMismatch, AxisOutOfBounds, DuplicateAxis, or ShapeMismatch when indices or the gather configuration is incompatible with the input, and Error::RuntimeStateSource when output metadata cannot be registered.

§Deferred errors

Runtime index values are checked after binding. An out-of-range index is returned as Error::TensorRuntime with the backend’s typed validation source and ErrorPhase::Execution.

Source

pub fn scatter( &self, indices: &TracedTensor, updates: &TracedTensor, config: ScatterConfig, ) -> Result<TracedTensor>

Scatter updates into self using StableHLO scatter semantics.

§Errors

Returns Error::Validation with RankMismatch, AxisOutOfBounds, DuplicateAxis, or ShapeMismatch when indices, updates, or the scatter configuration is incompatible, Error::TensorRuntime with UnsupportedDTypeConversion when dtype promotion cannot be represented, or Error::RuntimeStateSource when output metadata cannot be registered.

§Deferred errors

Runtime index/update values are checked after binding. An invalid index or update shape is returned as Error::TensorRuntime with its typed validation source and ErrorPhase::Execution.

Source

pub fn dynamic_slice( &self, starts: &TracedTensor, sizes: &[usize], ) -> Result<TracedTensor>

Slice using runtime start indices.

§Errors

Returns Error::Validation with RankMismatch, AxisOutOfBounds, or InvalidArgument when starts or sizes has an incompatible rank or extent, and Error::RuntimeStateSource when output metadata cannot be registered.

§Deferred errors

Runtime start values are checked after binding. An out-of-range start is returned as Error::TensorRuntime with the backend’s typed validation source and ErrorPhase::Execution.

Source

pub fn tril(&self, k: i64) -> Result<TracedTensor>

Keep the lower triangle and zero the rest.

§Examples
let matrix = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4])?;
let lower = matrix.tril(0)?;
assert_eq!(lower.rank, 2);
§Errors

Returns Error::RuntimeStateSource when traced output metadata registration is unavailable or inconsistent with the graph.

Source

pub fn triu(&self, k: i64) -> Result<TracedTensor>

Keep the upper triangle and zero the rest.

§Examples
let matrix = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4])?;
let upper = matrix.triu(0)?;
assert_eq!(upper.rank, 2);
§Errors

Returns Error::RuntimeStateSource when traced output metadata registration is unavailable or inconsistent with the graph.

Source

pub fn transpose(&self, perm: &[usize]) -> Result<TracedTensor>

Permute tensor axes.

§Examples
let y = x.transpose(&[1, 0])?;
§Errors

Returns Error::Validation with InvalidPermutationLength, AxisOutOfBounds, or DuplicateAxis when perm is not a valid permutation of the tensor axes, or Error::RuntimeStateSource when output metadata registration fails.

Source

pub fn extract_diag(&self, axis_a: usize, axis_b: usize) -> Result<TracedTensor>

Extract the diagonal along two axes.

§Examples
let y = x.extract_diag(0, 1)?;
§Errors

Returns Error::Validation with AxisOutOfBounds when either axis is outside the input rank or InvalidArgument when axis_a == axis_b.

Source

pub fn embed_diag(&self, axis_a: usize, axis_b: usize) -> Result<TracedTensor>

Embed a vector or lower-rank tensor along a diagonal.

§Examples
let y = x.embed_diag(0, 1)?;
§Errors

Returns Error::Validation with AxisOutOfBounds when axis_a is outside the input rank or InvalidArgument when axis_b is not a valid insertion axis.

Source

pub fn shape_of(&self, axis: usize) -> Result<TracedTensor>

Return the runtime size of one axis as a scalar f64 tensor.

The result is metadata-derived and therefore has no gradient.

§Examples
use tenferro_cpu::CpuBackend;
use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};

let x = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
let cols = x.shape_of(1)?;
let mut compiler = GraphCompiler::new();
let program = compiler.compile(&cols).unwrap();
let backend = CpuBackend::new();
let mut builder = Runtime::builder();
builder
    .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
    .unwrap();
let runtime = builder.build().unwrap();
let outputs = runtime.run_compiled(&program, &[]).unwrap();
let out = &outputs[0];
assert_eq!(out.shape(), &[] as &[usize]);
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside the input rank, or Error::RuntimeStateSource when scalar output metadata cannot be registered.

Source

pub fn dynamic_truncate( &self, size: &TracedTensor, axis: usize, ) -> Result<TracedTensor>

Truncate this tensor along axis to the first size elements.

size is read at runtime from a scalar traced tensor. Values are rounded to the nearest integer, clamped to [0, self.shape[axis]], and the output keeps the same element dtype as the input.

§Examples
use tenferro_cpu::CpuBackend;
use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};

let x = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
let size = TracedTensor::from_vec_col_major(vec![], vec![2.0_f64]).unwrap();
let y = x.dynamic_truncate(&size, 0)?;
let mut compiler = GraphCompiler::new();
let program = compiler.compile(&y).unwrap();
let backend = CpuBackend::new();
let mut builder = Runtime::builder();
builder
    .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
    .unwrap();
let runtime = builder.build().unwrap();
let outputs = runtime.run_compiled(&program, &[]).unwrap();
let out = &outputs[0];
assert_eq!(out.shape(), &[2]);
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside the input rank or RankMismatch when size is not scalar.

§Deferred errors

At execution, non-f32/f64/i64 size dtypes return Error::TensorRuntime with Unsupported, non-finite size values return a typed InvalidArgument, and an empty scalar buffer returns a typed runtime-state source.

Source

pub fn pad_to_match( &self, reference: &TracedTensor, axis: usize, ) -> Result<TracedTensor>

Pad this tensor with zeros along axis to match reference.shape[axis].

If reference is smaller along that axis, this is a no-op.

§Examples
use tenferro_cpu::CpuBackend;
use tenferro_runtime::{GraphCompiler, Runtime, TracedTensor};

let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
let reference = TracedTensor::from_vec_col_major(vec![4], vec![0.0_f64, 0.0, 0.0, 0.0]).unwrap();
let y = x.pad_to_match(&reference, 0)?;
let mut compiler = GraphCompiler::new();
let program = compiler.compile(&y).unwrap();
let backend = CpuBackend::new();
let mut builder = Runtime::builder();
builder
    .register_engine(tenferro_cpu::runtime_engine_registration(&backend).unwrap())
    .unwrap();
let runtime = builder.build().unwrap();
let outputs = runtime.run_compiled(&program, &[]).unwrap();
let out = &outputs[0];
assert_eq!(out.shape(), &[4]);
§Errors

Returns Error::Validation with AxisOutOfBounds when axis is outside either tensor’s rank, or Error::RuntimeStateSource when output metadata cannot be registered.

Trait Implementations§

Source§

impl Add for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the + operator.
Source§

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

Performs the + operation. Read more
Source§

impl Clone for TracedTensor

Source§

fn clone(&self) -> TracedTensor

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 TracedTensor

Source§

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

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

impl Div for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the / operator.
Source§

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

Performs the / operation. Read more
Source§

impl Mul<&TracedTensor> for f64

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the * operator.
Source§

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

Performs the * operation. Read more
Source§

impl Mul<f64> for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: f64) -> Result<TracedTensor>

Performs the * operation. Read more
Source§

impl Mul for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the * operator.
Source§

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

Performs the * operation. Read more
Source§

impl Neg for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
Source§

impl Rem for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the % operator.
Source§

fn rem(self, rhs: &TracedTensor) -> Result<TracedTensor>

Performs the % operation. Read more
Source§

impl Sub for &TracedTensor

Source§

type Output = Result<TracedTensor, Error>

The resulting type after applying the - operator.
Source§

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

Performs the - operation. Read more

Auto Trait Implementations§

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> 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
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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.
§

impl<T> MaybeSend for T
where T: Send,

§

impl<T> MaybeSendSync for T
where T: Send + Sync,

§

impl<T> MaybeSync for T
where T: Sync,