Skip to main content

EagerSession

Struct EagerSession 

Source
pub struct EagerSession<'a> { /* private fields */ }
Expand description

An eager runtime and its borrowed backend session for one execution boundary.

Obtain this only through EagerRuntime::with_eager_session. It rejects tensors from another eager runtime even if both runtimes use the same backend type, and it cannot escape the boundary closure.

§Examples

use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.neg(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-3.0]);

The borrowed session cannot escape its execution boundary:

ⓘ
use tenferro_ad::EagerRuntime;
let ctx = EagerRuntime::new().unwrap();
let escaped = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session).unwrap();
let _ = escaped;

Implementations§

Source§

impl<'a> EagerSession<'a>

Source

pub fn sigmoid(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Logistic sigmoid 1 / (1 + exp(-x)), overflow-free.

Evaluated as 1 / (1 + e) for x > 0 and e / (1 + e) otherwise, with e = exp(-|x|); the derivative is finite everywhere (sigmoid'(0) = 1/4). Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![-700.0_f64, 0.0, 1000.0])?)?;
    s.sigmoid(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[1], 0.5);
assert!(y[0] > 0.0 && y[0] < 1e-300);
assert_eq!(y[2], 1.0);
§Errors

Returns a typed UnsupportedDType error for complex, integer, or Bool input, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn silu(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

SiLU (swish) x * sigmoid(x).

Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![-1.0_f64, 0.0, 1.0])?)?;
    s.silu(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[1], 0.0);
assert!((y[2] - 1.0 / (1.0 + (-1.0_f64).exp())).abs() < 1e-15);
§Errors

Returns a typed UnsupportedDType error for complex, integer, or Bool input, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn softplus(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Softplus log(1 + exp(x)) in the stable form max(x, 0) + log1p(exp(-|x|)).

Never overflows; softplus'(0) = 1/2 and softplus''(0) = 1/4. Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![-1000.0_f64, 0.0, 1000.0])?)?;
    s.softplus(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[0], 0.0);
assert!((y[1] - 2.0_f64.ln()).abs() < 1e-15);
assert_eq!(y[2], 1000.0);
§Errors

Returns a typed UnsupportedDType error for complex, integer, or Bool input, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn gelu(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Exact GELU x/2 * (1 + erf(x / sqrt(2))) (PyTorch approximate="none").

Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![-1.0_f64, 0.0, 1.0])?)?;
    s.gelu(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[1], 0.0);
assert!((y[2] - 0.841_344_746_068_542_9).abs() < 1e-15);
§Errors

Returns a typed UnsupportedDType error for complex, integer, or Bool input, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn gelu_tanh(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

GELU tanh approximation (PyTorch approximate="tanh").

x/2 * (1 + tanh(sqrt(2/pi) * (x + 0.044715 x^3))); real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![-1.0_f64, 0.0, 1.0])?)?;
    s.gelu_tanh(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[1], 0.0);
assert!((y[2] - 0.841_191_990_608_276_8).abs() < 1e-12);
§Errors

Returns a typed UnsupportedDType error for complex, integer, or Bool input, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn reduce_mean( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Arithmetic mean over axes (None reduces every axis).

Float and complex dtypes. The sum is divided by the element count; a mean over zero elements is NaN, and Some(&[]) is the identity.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    s.reduce_mean(&x, Some(&[1]))
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0, 3.0]);
§Errors

Returns a typed UnsupportedDType error for integer or Bool input, an AxisOutOfBounds / DuplicateAxis validation error for invalid axes, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn softmax( &mut self, input: &EagerTensor, axis: isize, ) -> Result<EagerTensor, Error>

Max-subtracted softmax along axis.

A slice that is entirely -inf returns zeros with a finite gradient instead of NaN; a participating NaN or +inf makes its slice NaN; a zero-length axis returns an empty result. Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![0.0_f64, f64::NEG_INFINITY])?)?;
    s.softmax(&x, 0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0, 0.0]);
§Errors

Returns a typed UnsupportedDType error for non-real input, an AxisOutOfBounds validation error for an invalid axis, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn log_softmax( &mut self, input: &EagerTensor, axis: isize, ) -> Result<EagerTensor, Error>

Max-subtracted log-softmax along axis.

A slice that is entirely -inf returns -inf with a finite gradient instead of NaN. Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 1.0])?)?;
    s.log_softmax(&x, 0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-std::f64::consts::LN_2; 2]);
§Errors

Returns a typed UnsupportedDType error for non-real input, an AxisOutOfBounds validation error for an invalid axis, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn masked_softmax( &mut self, input: &EagerTensor, mask: &EagerTensor, axis: isize, ) -> Result<EagerTensor, Error>

Softmax along axis over the entries where the Bool mask is true.

mask broadcasts to the input shape. Masked-out entries get probability 0 and a zero gradient whatever their value; a slice with no unmasked entry returns zeros with a zero gradient.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 1.0, f64::NAN])?)?;
    let mask = s.constant_from_host(Tensor::from_vec_col_major(vec![3], vec![true, true, false])?)?;
    s.masked_softmax(&x, &mask, 0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.5, 0.5, 0.0]);
§Errors

Returns a typed UnsupportedDType error for non-real input, a DTypeMismatch validation error for a non-Bool mask, ShapeMismatch for a mask that does not broadcast to the input, AxisOutOfBounds for an invalid axis, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn masked_log_softmax( &mut self, input: &EagerTensor, mask: &EagerTensor, axis: isize, ) -> Result<EagerTensor, Error>

Log-softmax along axis over the entries where the Bool mask is true.

Masked-out entries are -inf with a zero gradient; a slice with no unmasked entry is all -inf with a zero gradient.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0])?)?;
    let mask = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![true, false])?)?;
    s.masked_log_softmax(&x, &mask, 0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0, f64::NEG_INFINITY]);
§Errors

Returns a typed UnsupportedDType error for non-real input, a DTypeMismatch validation error for a non-Bool mask, ShapeMismatch for a mask that does not broadcast to the input, AxisOutOfBounds for an invalid axis, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn layer_norm( &mut self, input: &EagerTensor, axis: isize, weight: Option<&EagerTensor>, bias: Option<&EagerTensor>, eps: f64, ) -> Result<EagerTensor, Error>

Layer normalization along axis with optional affine weight / bias.

(x - mean) / sqrt(var + eps) * weight + bias with the biased variance of the centered values; weight and bias are rank-1 of length shape[axis]. A zero-variance slice normalizes to 0 (then bias) with a finite gradient when eps > 0. Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 3.0])?)?;
    s.layer_norm(&x, 0, None, None, 0.0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-1.0, 1.0]);
§Errors

Returns a typed UnsupportedDType error for non-real input, an AxisOutOfBounds validation error for an invalid axis, InvalidArgument for a negative or non-finite eps, DTypeMismatch / ShapeMismatch for a weight or bias that is not a same-dtype vector of the axis length, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn rms_norm( &mut self, input: &EagerTensor, axis: isize, weight: Option<&EagerTensor>, bias: Option<&EagerTensor>, eps: f64, ) -> Result<EagerTensor, Error>

RMS normalization along axis with optional affine weight / bias.

x / sqrt(mean(x^2) + eps) * weight + bias; weight and bias are rank-1 of length shape[axis]. An all-zero slice normalizes to 0 (then bias) with a finite gradient when eps > 0. Real F32/F64 only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2], vec![0.0_f64, 0.0])?)?;
    s.rms_norm(&x, 0, None, None, 1e-6)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0, 0.0]);
§Errors

Returns a typed UnsupportedDType error for non-real input, an AxisOutOfBounds validation error for an invalid axis, InvalidArgument for a negative or non-finite eps, DTypeMismatch / ShapeMismatch for a weight or bias that is not a same-dtype vector of the axis length, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source

pub fn take_along_axis( &mut self, input: &EagerTensor, indices: &EagerTensor, axis: isize, ) -> Result<EagerTensor, Error>

NumPy-style take_along_axis over gather.

out[.., i, ..] = input[.., indices[.., i, ..], ..] along axis. indices (I32/I64) has the input’s rank; every other dimension is either the input’s extent (batch-varying indices) or 1 (the whole extent is taken). Indices must be in bounds. The gradient flows to input only.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
// Per-batch row gather: out[i, j, b] = x[idx[i, b], j, b].
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from_host(Tensor::from_vec_col_major(vec![2, 2, 2], (0..8).map(f64::from).collect::<Vec<_>>())?)?;
    let idx = s.constant_from_host(Tensor::from_vec_col_major(vec![2, 1, 2], vec![1_i64, 0, 0, 0])?)?;
    s.take_along_axis(&x, &idx, 0)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0, 0.0, 3.0, 2.0, 4.0, 4.0, 6.0, 6.0]);
§Errors

Returns a RankMismatch / ShapeMismatch validation error for incompatible index shapes, AxisOutOfBounds for an invalid axis, InvalidArgument when taking from a zero-length axis, a typed UnsupportedDType error for a non-integer index dtype, Error::ContextMismatch for a tensor from another runtime, or a backend error.

Source§

impl EagerSession<'_>

Source

pub fn neg(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Negate an eager tensor inside the caller’s execution boundary.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.neg(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-4.0]);
§Errors

Returns Error::ContextMismatch for a tensor from another runtime, or a typed eager/backend error from the selected operation.

Source

pub fn exp(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise exponential inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.exp(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed unsupported/backend error for the input dtype.

Source

pub fn abs(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise absolute value inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![-2.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.abs(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed unsupported/backend error for the input dtype.

Source

pub fn conj(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise conjugate inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.conj(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed unsupported/backend error for the input dtype.

Source

pub fn sign(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise sign on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![-2.0_f64])?)?;
    s.sign(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-1.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn log(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise natural logarithm on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?)?;
    s.log(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn sqrt(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise square root on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?)?;
    s.sqrt(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn rsqrt(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise reciprocal square root on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?)?;
    s.rsqrt(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.5]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn sin(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise sine on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
    s.sin(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn cos(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise cosine on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
    s.cos(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn tanh(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the elementwise hyperbolic tangent on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
    s.tanh(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn expm1(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute exp(x) - 1 elementwise on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
    s.expm1(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn log1p(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute log(1 + x) elementwise on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?)?;
    s.log1p(&x)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns a typed foreign-runtime, unsupported-dtype, or backend error.

Source

pub fn erf(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Compute the error function erf(x) elementwise on this borrowed session.

Defined for real F32/F64 tensors; erf(+-0) = +-0, erf(+-inf) = +-1, and NaN stays NaN. The derivative is 2/sqrt(pi) * exp(-x^2).

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![0.0_f64, 1.0])?)?;
    s.erf(&x)
})?;
let y = y.value()?;
let y = y.as_slice::<f64>()?;
assert_eq!(y[0], 0.0);
assert!((y[1] - 0.842_700_792_949_714_9).abs() < 1.0e-15);
§Errors

Returns a typed foreign-runtime error, a typed unsupported-dtype error for complex, integer, or Bool input, or a backend error.

Source

pub fn convert( &mut self, input: &EagerTensor, to: DType, ) -> Result<EagerTensor, Error>

Convert a tensor under the checked dtype-promotion lattice. Use Self::cast for intentional lossy projection.

§Examples
use tenferro_ad::{DType, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let converted = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let x = session.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    session.convert(&x, DType::C64)
})?;
assert_eq!(converted.dtype(), DType::C64);
§Errors

Returns Error::ContextMismatch for a foreign runtime or a typed unsupported dtype conversion/backend error.

Source

pub fn cast( &mut self, input: &EagerTensor, to: DType, ) -> Result<EagerTensor, Error>

Cast a tensor to a dtype, permitting explicitly lossy projections.

§Examples
use tenferro_ad::{DType, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let casted = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let x = session.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.8_f64])?)?;
    session.cast(&x, DType::I32)
})?;
assert_eq!(casted.value()?.as_slice::<i32>()?, &[2]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed unsupported projection/backend error.

Source

pub fn transpose( &mut self, input: &EagerTensor, perm: &[isize], ) -> Result<EagerTensor, Error>

Permute the axes of an eager tensor while preserving independent ownership.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let copied = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let x = session.constant_from(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    let y = session.transpose(&x, &[1, 0])?;
    session.duplicate_value(&y)
})?;
assert_eq!(copied.as_slice::<f64>()?, &[1.0, 3.0, 2.0, 4.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed axis/backend error for an invalid permutation or copy.

Source

pub fn reshape( &mut self, input: &EagerTensor, shape: impl IntoShapeVec, ) -> Result<EagerTensor, Error>

Reshape an eager tensor while retaining a separate result owner.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.reshape(&x, [1, 2]))?;
assert_eq!(y.shape(), &[1, 2]);
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0, 2.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed validation/backend error when the target shape is incompatible.

Source

pub fn slice( &mut self, input: &EagerTensor, config: SliceConfig, ) -> Result<EagerTensor, Error>

Slice an eager tensor with explicit start, limit, and stride per axis.

§Examples
use tenferro_ad::{EagerRuntime, SliceConfig, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let x = session.constant_from(Tensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    session.slice(&x, SliceConfig { starts: vec![1], limits: vec![3], strides: vec![1] })
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0, 3.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed axis/stride/backend error for an invalid slice or copy.

Source

pub fn broadcast_in_dim( &mut self, input: &EagerTensor, shape: &[usize], dims: &[usize], ) -> Result<EagerTensor, Error>

Broadcast an eager tensor into a larger shape on this session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
let copy = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let y = session.broadcast_in_dim(&x, &[2, 2], &[0])?;
    session.duplicate_value(&y)
})?;
assert_eq!(copy.as_slice::<f64>()?, &[1.0, 2.0, 1.0, 2.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed validation/backend error for an invalid broadcast mapping.

Source

pub fn tril( &mut self, input: &EagerTensor, k: i64, ) -> Result<EagerTensor, Error>

Keep the lower triangle of a matrix on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let lower = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let matrix = s.constant_from(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    s.tril(&matrix, 0)
})?;
assert_eq!(lower.value()?.as_slice::<f64>()?, &[1.0, 2.0, 0.0, 4.0]);
§Errors

Returns a typed foreign-runtime, rank, unsupported-dtype, or backend error.

Source

pub fn triu( &mut self, input: &EagerTensor, k: i64, ) -> Result<EagerTensor, Error>

Keep the upper triangle of a matrix on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let upper = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let matrix = s.constant_from(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    s.triu(&matrix, 0)
})?;
assert_eq!(upper.value()?.as_slice::<f64>()?, &[1.0, 0.0, 3.0, 4.0]);
§Errors

Returns a typed foreign-runtime, rank, unsupported-dtype, or backend error.

Source

pub fn pad( &mut self, input: &EagerTensor, config: PadConfig, ) -> Result<EagerTensor, Error>

Pad an eager tensor with zeros on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, PadConfig, Tensor};
let ctx = EagerRuntime::new()?;
let padded = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    s.pad(&x, PadConfig {
        edge_padding_low: vec![1],
        edge_padding_high: vec![1],
        interior_padding: vec![1],
    })
})?;
assert_eq!(padded.value()?.as_slice::<f64>()?, &[0.0, 1.0, 0.0, 2.0, 0.0]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, a validation error with ValidationError::InvalidArgument for a padding configuration whose length or extents do not match the input rank, or Error::TensorRuntime for a typed backend failure.

Source

pub fn reverse( &mut self, input: &EagerTensor, axes: &[isize], ) -> Result<EagerTensor, Error>

Reverse the elements along selected axes on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let reversed = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0])?)?;
    s.reverse(&x, &[0])
})?;
assert_eq!(reversed.value()?.as_slice::<f64>()?, &[3.0, 2.0, 1.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, or backend error.

Source

pub fn dynamic_slice( &mut self, input: &EagerTensor, starts: &EagerTensor, sizes: &[usize], ) -> Result<EagerTensor, Error>

Slice an eager tensor using runtime start indices in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let selected = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    let starts = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![1_i64])?)?;
    s.dynamic_slice(&x, &starts, &[2])
})?;
assert_eq!(selected.value()?.as_slice::<f64>()?, &[2.0, 3.0]);
§Errors

Returns a typed foreign-runtime, invalid-index or slice-shape, or backend error.

Source

pub fn gather( &mut self, input: &EagerTensor, indices: &EagerTensor, config: GatherConfig, ) -> Result<EagerTensor, Error>

Gather elements of an eager tensor in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, GatherConfig, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![3], vec![10.0_f64, 20.0, 30.0])?)?;
    let indices = s.constant_from(Tensor::from_vec_col_major(vec![2, 1], vec![2_i64, 0])?)?;
    s.gather(&x, &indices, GatherConfig {
        offset_dims: vec![], collapsed_slice_dims: vec![0],
        start_index_map: vec![0], index_vector_dim: 1,
        slice_sizes: vec![1],
    })
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[30.0, 10.0]);
§Errors

Returns a typed foreign-runtime, invalid-index/configuration, or backend error.

Source

pub fn concatenate( &mut self, inputs: &[&EagerTensor], axis: isize, ) -> Result<EagerTensor, Error>

Concatenate eager tensors along one axis in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let a = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?)?;
    let b = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    s.concatenate(&[&a, &b], 0)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[1.0, 2.0]);
§Errors

Returns a typed empty-input, foreign-runtime, invalid-axis/shape, or backend error.

Source

pub fn scatter( &mut self, input: &EagerTensor, indices: &EagerTensor, updates: &EagerTensor, config: ScatterConfig, ) -> Result<EagerTensor, Error>

Scatter updates into an eager tensor within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, ScatterConfig, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let input = s.constant_from(Tensor::from_vec_col_major(vec![4], vec![0.0_f64; 4])?)?;
    let indices = s.constant_from(Tensor::from_vec_col_major(vec![2, 1], vec![1_i64, 3])?)?;
    let updates = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![5.0_f64, 7.0])?)?;
    s.scatter(&input, &indices, &updates, ScatterConfig {
        update_window_dims: vec![],
        inserted_window_dims: vec![0],
        scatter_dims_to_operand_dims: vec![0],
        index_vector_dim: 1,
    })
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[0.0, 5.0, 0.0, 7.0]);
§Errors

Returns a typed foreign-runtime, invalid-index/configuration, or backend error.

Source

pub fn extract_diag( &mut self, input: &EagerTensor, axis_a: isize, axis_b: isize, ) -> Result<EagerTensor, Error>

Extract a diagonal along two axes in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let diagonal = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let matrix = s.constant_from(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    s.extract_diag(&matrix, 0, 1)
})?;
assert_eq!(diagonal.value()?.as_slice::<f64>()?, &[1.0, 4.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, or backend error.

Source

pub fn embed_diag( &mut self, input: &EagerTensor, axis_a: isize, axis_b: isize, ) -> Result<EagerTensor, Error>

Embed the input along a diagonal in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let matrix = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let diagonal = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    s.embed_diag(&diagonal, 0, 1)
})?;
assert_eq!(matrix.value()?.as_slice::<f64>()?, &[1.0, 0.0, 0.0, 2.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, or backend error.

Source

pub fn reduce_sum( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Reduce an eager tensor over selected axes within this borrowed session. None reduces all axes, while Some(&[]) retains the input shape.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
let sum = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.reduce_sum(&x, None))?;
assert_eq!(sum.value()?.as_slice::<f64>()?, &[3.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed validation/backend error for invalid axes or unsupported dtypes.

Source

pub fn reduce_sum_squares( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Sum elementwise squares over the selected axes in this borrowed session. Only f32 and f64 are supported. None reduces every axis, like the rest of the reduction family; Some(&[]) squares each value.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let (sum, all) = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let input = s.constant_from(Tensor::from_vec_col_major([2], vec![3.0_f64, 4.0])?)?;
    Ok::<_, tenferro_ad::Error>((
        s.reduce_sum_squares(&input, Some(&[0]))?,
        s.reduce_sum_squares(&input, None)?,
    ))
})?;
assert_eq!(sum.value()?.as_slice::<f64>()?, &[25.0]);
assert_eq!(all.value()?.as_slice::<f64>()?, &[25.0]);
§Errors

Returns typed foreign-runtime, invalid-axis, unsupported-dtype, or backend errors.

Source

pub fn reduce_prod( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Reduce the product of selected axes in this borrowed session. None reduces every axis.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0])?)?;
    s.reduce_prod(&x, None)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[6.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, unsupported-dtype, or backend error.

Source

pub fn reduce_max( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Reduce the maximum over selected axes in this borrowed session. None reduces every axis.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0])?)?;
    s.reduce_max(&x, None)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[3.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, unsupported-dtype, or backend error.

Source

pub fn reduce_min( &mut self, input: &EagerTensor, axes: Option<&[isize]>, ) -> Result<EagerTensor, Error>

Reduce the minimum over selected axes in this borrowed session. None reduces every axis.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0])?)?;
    s.reduce_min(&x, None)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis, unsupported-dtype, or backend error.

Source

pub fn duplicate_value(&mut self, input: &EagerTensor) -> Result<Tensor, Error>

Duplicate an eager value into an independent tensor within the caller’s borrowed session, preserving its dtype and placement.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
let copy = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.duplicate_value(&x))?;
assert_eq!(copy.as_slice::<f64>()?, &[2.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed runtime/backend error when the retained value cannot be duplicated.

Source

pub fn constant_from(&mut self, tensor: Tensor) -> Result<EagerTensor, Error>

Import an untracked leaf within this borrowed session.

tensor must already be usable by this runtime’s backend: a host tensor on a CPU runtime, or a tensor already on the device of a CUDA or WebGPU runtime. No host/device transfer happens here. To import host data into a device runtime, use Self::constant_from_host, which uploads first; on a CPU runtime the two are equivalent.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let c = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    session.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)
})?;
assert_eq!(c.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns Error::TensorRuntime for a typed backend failure when the value cannot be registered in the session, or Error::RuntimeState when the runtime’s value registry is unavailable.

Source

pub fn constant_from_host( &mut self, tensor: Tensor, ) -> Result<EagerTensor, Error>

Upload a host tensor and import it as an untracked leaf in this session.

Unlike Self::constant_from, this explicitly crosses the host/device boundary: the host tensor is uploaded to this runtime’s backend (a host copy on a CPU runtime) and the uploaded value becomes the leaf. Use it whenever the source data lives on the host and the runtime may be a device runtime; use Self::constant_from for a tensor that is already resident on the backend.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let c = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    s.constant_from_host(Tensor::from_vec_col_major([1], vec![2.0_f64])?)
})?;
assert_eq!(c.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns Error::TensorRuntime for a typed backend failure, including a host-tensor upload failure, or Error::RuntimeState when the runtime’s value registry is unavailable.

Source

pub fn variable_from(&mut self, tensor: Tensor) -> Result<EagerTensor, Error>

Import a trainable leaf within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    session.variable_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)
})?;
assert!(x.tracks_grad());
§Errors

Returns Error::TensorRuntime for a typed backend failure when the value cannot be registered, or Error::RuntimeState when the runtime’s value or gradient registry is unavailable.

Source

pub fn detach(&mut self, input: &EagerTensor) -> Result<EagerTensor, Error>

Detach an eager tensor from the reverse graph within this session.

The result keeps the concrete value, belongs to the same runtime and contributes no gradients to the graph that produced input. To move a value into another eager runtime, duplicate it here with Self::duplicate_value and import the owned tensor in the target runtime’s session with Self::constant_from.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| s.detach(&x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0, 2.0]);
assert!(!y.tracks_grad());
§Errors

Returns Error::ContextMismatch for a tensor from another runtime, Error::TensorRuntime when the engine cannot materialize the retained value, or Error::RuntimeState when the value record or its allocation-group descriptor is unavailable.

Source

pub fn grad( &mut self, output: &EagerTensor, wrt: &EagerTensor, ) -> Result<EagerTensor, Error>

Gradient of a scalar eager output with respect to an eager tensor.

Functional eager gradients return ordinary eager tensors and do not write into grad() slots. The returned tensor keeps a trace when the derivative computation depends on tracked eager values, so it can be differentiated again (higher-order derivatives).

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
let dx = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let loss = s.mul(&x, &x)?;
    s.grad(&loss, &x)
})?;
assert_eq!(dx.value()?.as_slice::<f64>()?, &[6.0]);
§Errors

Returns Error::ContextMismatch when output or wrt belongs to another runtime (checked before anything is materialized), Error::NonScalarGrad for a non-scalar output, Error::UnsupportedAdRule when an AD rule is unavailable, or a typed validation/backend error from eager execution. An inactive wrt returns Error::Validation with argument: "wrt"; use Self::grad_optional to observe that state.

Source

pub fn grad_optional( &mut self, output: &EagerTensor, wrt: &EagerTensor, ) -> Result<Option<EagerTensor>, Error>

Gradient that returns None when wrt is inactive.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
let y = ctx.variable_from(Tensor::from_vec_col_major(vec![], vec![4.0_f64])?)?;
let dx = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let loss = s.mul(&y, &y)?;
    s.grad_optional(&loss, &x)
})?;
assert!(dx.is_none());
§Errors

Returns Error::ContextMismatch when output or wrt belongs to another runtime (checked before the seed is built), Error::NonScalarGrad for a non-scalar output, or a typed validation/backend/runtime-state error from eager execution.

Source

pub fn vjp( &mut self, output: &EagerTensor, wrt: &EagerTensor, cotangent: &EagerTensor, ) -> Result<EagerTensor, Error>

Reverse-mode vector-Jacobian product for eager tensors.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0])?)?;
let seed = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 1.0])?)?;
let dx = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let y = s.mul(&x, &x)?;
    s.vjp(&y, &x, &seed)
})?;
assert_eq!(dx.value()?.as_slice::<f64>()?, &[4.0, 6.0]);
§Errors

Returns Error::ContextMismatch when output, wrt or cotangent belongs to another runtime, Error::Validation when the cotangent shape or dtype does not match the output, Error::UnsupportedAdRule when a rule is not registered, or a typed backend/runtime-state error. An inactive wrt returns Error::Validation with argument: "wrt"; use Self::vjp_optional to observe that state.

Source

pub fn vjp_optional( &mut self, output: &EagerTensor, wrt: &EagerTensor, cotangent: &EagerTensor, ) -> Result<Option<EagerTensor>, Error>

Reverse-mode vector-Jacobian product that returns None for inactive inputs.

None means the input is disconnected, its eager computation was not recorded, or the semantic derivative has no cotangent flow (for example, real sign or an integer conversion). A present numerical zero is still returned as Some. Missing rules and execution failures return errors; semantic differentiation cannot be disabled by an environment variable.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
let y = ctx.variable_from(Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?)?;
let seed = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?)?;
let dx = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let loss = s.mul(&y, &y)?;
    s.vjp_optional(&loss, &x, &seed)
})?;
assert!(dx.is_none());
§Errors

Returns Error::ContextMismatch when output, wrt or cotangent belongs to another runtime, Error::Validation when the cotangent shape or dtype does not match the output, Error::UnsupportedAdRule when a rule is not registered, or a typed backend/runtime-state error.

Source

pub fn jvp( &mut self, output: &EagerTensor, wrt: &EagerTensor, tangent: &EagerTensor, ) -> Result<EagerTensor, Error>

Forward-mode Jacobian-vector product for eager tensors.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?)?;
let tangent = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?)?;
let dy = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let y = s.mul(&x, &x)?;
    s.jvp(&y, &x, &tangent)
})?;
assert_eq!(dy.value()?.as_slice::<f64>()?, &[6.0]);
§Errors

Returns Error::ContextMismatch when output, wrt or tangent belongs to another runtime, Error::Validation when the tangent shape or dtype does not match wrt, Error::UnsupportedAdRule when a rule is unavailable, or a typed backend/runtime-state error. An inactive wrt returns Error::Validation with argument: "wrt"; use Self::jvp_optional to observe that state.

Source

pub fn jvp_optional( &mut self, output: &EagerTensor, wrt: &EagerTensor, tangent: &EagerTensor, ) -> Result<Option<EagerTensor>, Error>

Forward-mode Jacobian-vector product that returns None for inactive outputs.

None means wrt is disconnected, its eager computation was not recorded, or the semantic derivative has no tangent flow (for example, real sign or an integer conversion). A present numerical zero is still returned as Some. Missing rules and execution failures return errors; semantic differentiation cannot be disabled by an environment variable.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
let y = ctx.variable_from(Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?)?;
let tangent = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?)?;
let dy = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let loss = s.mul(&y, &y)?;
    s.jvp_optional(&loss, &x, &tangent)
})?;
assert!(dy.is_none());
§Errors

Returns Error::ContextMismatch when output, wrt or tangent belongs to another runtime, Error::Validation when the tangent shape or dtype does not match wrt, Error::UnsupportedAdRule when a rule is unavailable, or a typed backend/runtime-state error.

Source

pub fn backward(&mut self, output: &EagerTensor) -> Result<Gradients, Error>

Run reverse-mode AD from a scalar eager output.

Returns the full cotangent map produced by the reverse pass and also accumulates into grad() for tracked eager leaves reachable from output; repeated calls add to the stored gradients until they are cleared. A pass with no gradients is an error, not an empty successful bundle. If a reachable leaf has no cotangent flow, the pass fails before accumulating any gradients; use Self::vjp_optional to observe absent flow explicitly.

For complex scalar outputs, cotangents use tenferro’s Hermitian real-inner-product convention. See https://tensor4all.org/tenferro-rs/guides/complex-ad.html.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0])?)?;
for _ in 0..2 {
    ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
        let doubled = s.add(&x, &x)?;
        let loss = s.reduce_sum(&doubled, Some(&[0]))?;
        s.backward(&loss)
    })?;
}
assert_eq!(x.grad()?.expect("tracked leaf").as_slice::<f64>()?, &[4.0, 4.0, 4.0]);
§Errors

Returns Error::ContextMismatch when output belongs to another runtime (checked before any gradient slot is written), Error::NonScalarGrad when output is not scalar, Error::Validation when a reachable tracked leaf has no cotangent, Error::RuntimeState when no tracked leaf produces a gradient, Error::UnsupportedAdRule when a graph operation lacks a reverse rule, or a typed validation/backend/runtime-state error during the reverse pass.

Source

pub fn backward_with( &mut self, output: &EagerTensor, cotangent: &EagerTensor, ) -> Result<Gradients, Error>

Run reverse-mode AD from an eager output with an explicit cotangent seed.

The seed is an operand, not an options value: this is the registry’s documented seeded form of Self::backward. Like backward, it rejects absent cotangents for reachable tracked leaves before accumulation, accumulates into the reachable leaves’ grad() slots and never returns an empty successful bundle. Use Self::vjp when the VJP result should be a composable eager tensor that touches no gradient slot.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};

let ctx = EagerRuntime::new()?;
let x = ctx.variable_from(Tensor::from_vec_col_major(vec![2], vec![2.0_f64, 3.0])?)?;
let seed = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let y = s.mul(&x, &x)?;
    s.backward_with(&y, &seed)
})?;
assert_eq!(x.grad()?.expect("tracked leaf").as_slice::<f64>()?, &[4.0, 12.0]);
§Errors

Returns Error::ContextMismatch when output or cotangent belongs to another runtime (checked before the seed is materialized or any gradient slot is written), Error::Validation when the seed’s shape or dtype does not match output or a reachable tracked leaf has no cotangent, Error::RuntimeState when no tracked leaf produces a gradient, Error::UnsupportedAdRule for an unavailable reverse rule, or a typed backend/runtime-state error during execution.

Source

pub fn add( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Add eager tensors with the same broadcast and AD rules as the eager operation surface, reusing this borrowed execution session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
let scalar = ctx.constant_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.add(&x, &scalar))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[4.0, 5.0]);
§Errors

Returns Error::ContextMismatch for a tensor from another runtime, or a typed broadcast/backend error for the operands.

Source

pub fn sub( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Subtract eager tensors within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.sub(&x, &x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[0.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed broadcast/backend error for the operands.

Source

pub fn mul( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Multiply eager tensors within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
let ctx = EagerRuntime::new()?;
let x = ctx.constant_from(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?)?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| session.mul(&x, &x))?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[9.0]);
§Errors

Returns Error::ContextMismatch for a foreign runtime, or a typed broadcast/backend error for the operands.

Source

pub fn div( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Divide eager tensors elementwise with broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![6.0_f64])?)?;
    let divisor = s.constant_from(Tensor::from_vec_col_major(vec![], vec![2.0_f64])?)?;
    s.div(&x, &divisor)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[3.0]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, a validation error with ValidationError::ShapeMismatch when the operands cannot broadcast, or Error::TensorRuntime for a typed backend failure (including integer division by zero).

Source

pub fn rem( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Compute the elementwise remainder with broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![5.0_f64])?)?;
    let divisor = s.constant_from(Tensor::from_vec_col_major(vec![], vec![2.0_f64])?)?;
    s.rem(&x, &divisor)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[1.0]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, a validation error with ValidationError::ShapeMismatch when the operands cannot broadcast, or Error::TensorRuntime for a typed backend failure (including an integer remainder by zero).

Source

pub fn pow( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Raise eager tensor elements to broadcast exponents.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    let exponent = s.constant_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
    s.pow(&x, &exponent)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[8.0]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, a validation error with ValidationError::ShapeMismatch when the operands cannot broadcast, or Error::TensorRuntime for a typed backend failure (including a negative integer exponent).

Source

pub fn maximum( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Compute the elementwise maximum under broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    let bound = s.constant_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
    s.maximum(&x, &bound)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[3.0]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn minimum( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Compute the elementwise minimum under broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    let bound = s.constant_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
    s.minimum(&x, &bound)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn compare( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, dir: CompareDir, ) -> Result<EagerTensor, Error>

Compare eager tensors elementwise under broadcast rules.

§Examples
use tenferro_ad::{CompareDir, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?)?;
    let bound = s.constant_from(Tensor::from_vec_col_major(vec![], vec![1.0_f64])?)?;
    s.compare(&x, &bound, CompareDir::Gt)
})?;
assert_eq!(y.value()?.as_slice::<bool>()?, &[true]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn where_select( &mut self, condition: &EagerTensor, on_true: &EagerTensor, on_false: &EagerTensor, ) -> Result<EagerTensor, Error>

Select eager values elementwise using a broadcast boolean condition.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let condition = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![true, false])?)?;
    let yes = s.constant_from(Tensor::from_vec_col_major(vec![], vec![10.0_f64])?)?;
    let no = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    s.where_select(&condition, &yes, &no)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[10.0, 2.0]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn select( &mut self, condition: &EagerTensor, on_true: &EagerTensor, on_false: &EagerTensor, ) -> Result<EagerTensor, Error>

Alias for Self::where_select with the same borrowed-session semantics.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let predicate = s.constant_from(Tensor::from_vec_col_major(vec![], vec![true])?)?;
    let yes = s.constant_from(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?)?;
    let no = s.constant_from(Tensor::from_vec_col_major(vec![], vec![4.0_f64])?)?;
    s.select(&predicate, &yes, &no)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[3.0]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn clamp( &mut self, input: &EagerTensor, lower: &EagerTensor, upper: &EagerTensor, ) -> Result<EagerTensor, Error>

Clamp eager values elementwise between broadcast lower and upper bounds.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![-2.0_f64, 5.0])?)?;
    let lo = s.constant_from(Tensor::from_vec_col_major(vec![], vec![-1.0_f64])?)?;
    let hi = s.constant_from(Tensor::from_vec_col_major(vec![], vec![4.0_f64])?)?;
    s.clamp(&x, &lo, &hi)
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-1.0, 4.0]);
§Errors

Returns a typed foreign-runtime, broadcast, unsupported-dtype, or backend error.

Source

pub fn dot_general( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, config: DotGeneralConfig, ) -> Result<EagerTensor, Error>

Contract eager tensors according to a dot-general dimension mapping.

The output layout is [lhs free..., rhs free..., batch...]: batch axes come last (see DotGeneralConfig).

§Examples
use tenferro_ad::{DotGeneralConfig, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let lhs = session.variable_from(Tensor::from_vec_col_major(vec![1, 2], vec![2.0_f64, 3.0])?)?;
    let rhs = session.constant_from(Tensor::from_vec_col_major(vec![2, 1], vec![4.0_f64, 5.0])?)?;
    session.dot_general(&lhs, &rhs, DotGeneralConfig {
        lhs_contracting_dims: [1].as_slice().into(),
        rhs_contracting_dims: [0].as_slice().into(),
        lhs_batch_dims: [].as_slice().into(),
        rhs_batch_dims: [].as_slice().into(),
    })
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[23.0]);
§Errors

Returns Error::ContextMismatch for a foreign eager runtime, a typed validation error for incompatible contraction dimensions, or the backend’s typed execution error.

Source

pub fn scale_real( &mut self, input: &EagerTensor, factor: f64, ) -> Result<EagerTensor, Error>

Scale an eager tensor by a real scalar in this borrowed session. Integer factors are rounded; finite zero maps to false for boolean inputs.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let scaled = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    s.scale_real(&x, 2.0)
})?;
assert_eq!(scaled.value()?.as_slice::<f64>()?, &[2.0, 4.0]);
§Errors

Returns a typed foreign-runtime, invalid-factor/dtype, or backend error.

Source

pub fn scale_complex( &mut self, input: &EagerTensor, factor: Complex<f64>, ) -> Result<EagerTensor, Error>

Scale a complex eager tensor by a complex scalar in this borrowed session.

§Examples
use num_complex::Complex64;
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let scaled = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1], vec![Complex64::new(1.0, 2.0)])?)?;
    s.scale_complex(&x, Complex64::new(0.0, 1.0))
})?;
assert_eq!(scaled.value()?.as_slice::<Complex64>()?, &[Complex64::new(-2.0, 1.0)]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, Error::TensorRuntime containing ValidationError::InvalidArgument when the input dtype is not complex, or Error::TensorRuntime for a typed backend failure.

Source

pub fn matmul( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor, Error>

Multiply two rank-2 eager tensors in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let a = s.constant_from(Tensor::from_vec_col_major(vec![1, 1], vec![2.0_f64])?)?;
    let b = s.constant_from(Tensor::from_vec_col_major(vec![1, 1], vec![3.0_f64])?)?;
    s.matmul(&a, &b)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[6.0]);
§Errors

Returns Error::ContextMismatch when an input belongs to another eager runtime, a validation error with ValidationError::RankMismatch or ValidationError::ShapeMismatch when the operands are not rank-2 with matching inner dimensions, a dtype mismatch between the operands, or Error::TensorRuntime for a typed backend failure.

Source

pub fn dot_general_with( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, config: DotGeneralConfig, options: &DotGeneralOptions, ) -> Result<EagerTensor, Error>

Contract eagerly with optional conjugation of either operand. Untracked operands use the backend’s conjugating contraction directly; tracked operands record explicit conjugations for reverse-mode AD.

§Examples
use tenferro_ad::{DotGeneralConfig, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    let lhs = session.constant_from(Tensor::from_vec_col_major(vec![1, 1], vec![2.0_f64])?)?;
    let rhs = session.constant_from(Tensor::from_vec_col_major(vec![1, 1], vec![3.0_f64])?)?;
    let conj_lhs = tenferro_tensor::DotGeneralOptions::default().lhs(tenferro_tensor::Conj::Yes);
    session.dot_general_with(&lhs, &rhs, DotGeneralConfig {
        lhs_contracting_dims: [1].as_slice().into(),
        rhs_contracting_dims: [0].as_slice().into(),
        lhs_batch_dims: [].as_slice().into(),
        rhs_batch_dims: [].as_slice().into(),
    }, &conj_lhs)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[6.0]);
§Errors

Returns Error::ContextMismatch for a foreign eager runtime, a typed validation error for invalid dimensions, or a backend error.

Source

pub fn apply_standard_op( &mut self, op: StdTensorOp, inputs: &[&EagerTensor], ) -> Result<EagerTensor, Error>

Apply one standard tensor op in this borrowed session and record it for AD when needed.

Extension crates use this when an extension-level eager operation expands into ordinary StdTensorOp nodes instead of a custom extension primitive: all of them run in this one backend session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
use tenferro_ops::std_tensor_op::StdTensorOp;

let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.variable_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    let negated = s.apply_standard_op(StdTensorOp::Neg, &[&x])?;
    s.apply_standard_op(StdTensorOp::Mul, &[&negated, &x])
})?;
assert_eq!(y.value()?.as_slice::<f64>()?, &[-1.0, -4.0]);
assert!(y.tracks_grad());
§Errors

Returns Error::TensorRuntime containing tenferro_tensor::ValidationError::InvalidArgument for an extension op, Error::ContextMismatch for a tensor from another runtime, a typed input-count error, or the backend’s typed execution error.

Source

pub fn engine(&mut self) -> &mut dyn ExecutionEngine

Borrow the engine this eager session runs on.

§Examples
use tenferro_ad::EagerRuntime;
use tenferro_cpu::CpuEngine;

let ctx = EagerRuntime::new()?;
let mut engine = CpuEngine::serial();
let id = ctx.with_eager_session(&mut engine, |s| {
    Ok::<_, tenferro_ad::Error>(s.engine().target().engine_id().clone())
})?;
assert_eq!(id, tenferro_cpu::runtime_engine_id()?);
Source

pub fn with_extension_caches<R>( &mut self, f: impl FnOnce(&mut ExtensionCacheStore) -> R, ) -> Result<R, Error>

Run f on this runtime’s extension cache store from inside the session.

Operation families use this for their own prepared-plan caches without reopening the runtime: the eager owner is already locked, and the cache lock is taken second, as in every extension execution region.

§Examples
use tenferro_ad::EagerRuntime;

let ctx = EagerRuntime::new()?;
let entries = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |session| {
    session.with_extension_caches(|caches| caches.len())
})?;
assert_eq!(entries, 0);
§Errors

Returns a runtime-state error when the extension cache lock is poisoned.

Source§

impl EagerSession<'_>

Source

pub fn index_select( &mut self, tensor: &EagerTensor, axis: isize, positions: &[usize], ) -> Result<EagerTensor, Error>

Select positions from one axis using a borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0])?)?;
    s.index_select(&x, -1, &[2, 0])
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[3.0, 1.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis/index, or backend error.

Source

pub fn take_axis( &mut self, tensor: &EagerTensor, axis: isize, positions: &[usize], ) -> Result<EagerTensor, Error>

Select entries from an axis by host-known positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?)?;
    s.take_axis(&x, 0, &[1])
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis/index, or backend error.

Source

pub fn take_rows( &mut self, tensor: &EagerTensor, rows: &[usize], ) -> Result<EagerTensor, Error>

Select matrix rows by host-known positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2, 1], vec![1.0_f64, 2.0])?)?;
    s.take_rows(&x, &[1])
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, invalid-row, or backend error.

Source

pub fn take_cols( &mut self, tensor: &EagerTensor, cols: &[usize], ) -> Result<EagerTensor, Error>

Select matrix columns by host-known positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![1, 2], vec![1.0_f64, 2.0])?)?;
    s.take_cols(&x, &[1])
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, invalid-column, or backend error.

Source

pub fn take_block( &mut self, tensor: &EagerTensor, rows: &[usize], cols: &[usize], ) -> Result<EagerTensor, Error>

Select a matrix block by host-known row and column positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0])?)?;
    s.take_block(&x, &[1], &[0])
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0]);
§Errors

Returns a typed foreign-runtime, invalid-row/column, or backend error.

Source

pub fn slice_axis( &mut self, tensor: &EagerTensor, axis: isize, range: Range<usize>, ) -> Result<EagerTensor, Error>

Slice one axis using an exclusive-end range in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let x = s.constant_from(Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0])?)?;
    s.slice_axis(&x, 0, 1..3)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[2.0, 3.0]);
§Errors

Returns a typed foreign-runtime, invalid-axis/range, or backend error.

Source

pub fn stack( &mut self, tensors: &[&EagerTensor], dim: isize, ) -> Result<EagerTensor, Error>

Stack eager tensors along a new axis in this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(&mut tenferro_cpu::CpuEngine::serial(), |s| {
    let a = s.constant_from(Tensor::from_vec_col_major(vec![], vec![1.0_f64])?)?;
    let b = s.constant_from(Tensor::from_vec_col_major(vec![], vec![2.0_f64])?)?;
    s.stack(&[&a, &b], -1)
})?;
assert_eq!(result.value()?.as_slice::<f64>()?, &[1.0, 2.0]);
§Errors

Returns a typed empty-input, invalid-axis/shape, foreign-runtime, or backend error.

Trait Implementations§

Source§

impl Debug for EagerSession<'_>

Source§

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

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

impl EagerLinalgOps for EagerSession<'_>

Available on crate feature autodiff only.
Source§

fn svd(&mut self, a: &EagerTensor) -> Result<Svd<EagerTensor, EagerTensor>>

Singular value decomposition a = u diag(s) vh; SvdShape::Full returns the full-matrices factors. Read more
Source§

fn svd_with( &mut self, a: &EagerTensor, options: &SvdOptions, ) -> Result<Svd<EagerTensor, EagerTensor>>

Singular value decomposition a = u diag(s) vh; SvdShape::Full returns the full-matrices factors. Read more
Source§

fn svdvals(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Singular values only, in descending order. Read more
Source§

fn svdvals_with( &mut self, a: &EagerTensor, options: &SvdvalsOptions, ) -> Result<EagerTensor>

Singular values only, in descending order. Read more
Source§

fn qr(&mut self, a: &EagerTensor) -> Result<Qr<EagerTensor>>

Thin QR factorization a = q r. Read more
Source§

fn qr_with( &mut self, a: &EagerTensor, options: &QrOptions, ) -> Result<Qr<EagerTensor>>

Thin QR factorization a = q r. Read more
Source§

fn householder_qr( &mut self, a: &EagerTensor, ) -> Result<HouseholderQr<EagerTensor>>

Compact Householder QR: an opaque factorization state from which r and q_columns are extracted. Read more
Source§

fn rank_revealing_qr( &mut self, a: &EagerTensor, ) -> Result<RankRevealingQrResult<EagerTensor, EagerTensor>>

Column-pivoted QR with a numerical rank: q, r, column_permutation and rank. Read more
Source§

fn rank_revealing_qr_with( &mut self, a: &EagerTensor, options: &RankRevealingQrOptions, ) -> Result<RankRevealingQrResult<EagerTensor, EagerTensor>>

Column-pivoted QR with a numerical rank: q, r, column_permutation and rank. Read more
Source§

fn lu(&mut self, a: &EagerTensor) -> Result<Lu<EagerTensor>>

Partial-pivot LU a = p l u; p is a permutation matrix and parity is the real sign of the permutation. Read more
Source§

fn full_piv_lu( &mut self, a: &EagerTensor, ) -> Result<FullPivLu<EagerTensor, EagerTensor>>

Complete-pivot LU a = p l u q; p and q are permutation matrices and parity is the real sign of the permutations. Read more
Source§

fn full_piv_lu_solve( &mut self, a: &EagerTensor, b: &EagerTensor, ) -> Result<EagerTensor>

Solves a x = b through the complete-pivot LU of a; a rank-deficient system is rejected. Read more
Source§

fn solve(&mut self, a: &EagerTensor, b: &EagerTensor) -> Result<EagerTensor>

Solves a x = b with a partial-pivot LU of a; solve_into overwrites a destination. Read more
Source§

fn lstsq(&mut self, a: &EagerTensor, b: &EagerTensor) -> Result<EagerTensor>

Least-squares solution of a x = b for a tall or square, full-column-rank a (thin QR, then a triangular solve). Read more
Source§

fn triangular_solve( &mut self, a: &EagerTensor, b: &EagerTensor, ) -> Result<EagerTensor>

Solves a triangular system with a (or its transpose) on the chosen side; only the selected triangle of a is read. Read more
Source§

fn triangular_solve_with( &mut self, a: &EagerTensor, b: &EagerTensor, options: &TriangularSolveOptions, ) -> Result<EagerTensor>

Solves a triangular system with a (or its transpose) on the chosen side; only the selected triangle of a is read. Read more
Source§

fn cholesky(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Lower Cholesky factor l of a Hermitian positive-definite matrix, a = l l^H. Read more
Source§

fn cholesky_with( &mut self, a: &EagerTensor, options: &CholeskyOptions, ) -> Result<EagerTensor>

Lower Cholesky factor l of a Hermitian positive-definite matrix, a = l l^H. Read more
Source§

fn eig(&mut self, a: &EagerTensor) -> Result<Eig<EagerTensor>>

General eigendecomposition a v = v diag(values); eigenvectors have unit 2-norm. Read more
Source§

fn eigvals(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Eigenvalues of a general matrix, as complex numbers. Read more
Source§

fn eigh(&mut self, a: &EagerTensor) -> Result<Eigh<EagerTensor, EagerTensor>>

Eigendecomposition of a Hermitian matrix (the lower triangle is read); values are real and ascending. Read more
Source§

fn eigh_with( &mut self, a: &EagerTensor, options: &EighOptions, ) -> Result<Eigh<EagerTensor, EagerTensor>>

Eigendecomposition of a Hermitian matrix (the lower triangle is read); values are real and ascending. Read more
Source§

fn eigvalsh(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Eigenvalues of a Hermitian matrix (the lower triangle is read), real and ascending. Read more
Source§

fn eigvalsh_with( &mut self, a: &EagerTensor, options: &EigvalshOptions, ) -> Result<EagerTensor>

Eigenvalues of a Hermitian matrix (the lower triangle is read), real and ascending. Read more
Source§

fn slogdet( &mut self, a: &EagerTensor, ) -> Result<Slogdet<EagerTensor, EagerTensor>>

Sign and natural log of the absolute determinant of a square matrix. Read more
Source§

fn det(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Determinant of a square matrix, computed as sign * exp(log_abs_det). Read more
Source§

fn inv(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Inverse of a square matrix (a solve against the identity). Read more
Source§

fn pinv(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Moore-Penrose pseudoinverse through the SVD; singular values below rtol * max(s) are dropped. Read more
Source§

fn pinv_with( &mut self, a: &EagerTensor, options: &PinvOptions, ) -> Result<EagerTensor>

Moore-Penrose pseudoinverse through the SVD; singular values below rtol * max(s) are dropped. Read more
Source§

fn norm(&mut self, a: &EagerTensor) -> Result<EagerTensor>

Vector or matrix norm over the chosen axes, selected by NormOrd; NormOrd::Zero counts entries != 0 (NaN counts as nonzero). Read more
Source§

fn norm_with( &mut self, a: &EagerTensor, options: &NormOptions, ) -> Result<EagerTensor>

Vector or matrix norm over the chosen axes, selected by NormOrd; NormOrd::Zero counts entries != 0 (NaN counts as nonzero). Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for EagerSession<'a>

§

impl<'a> !Send for EagerSession<'a>

§

impl<'a> !Sync for EagerSession<'a>

§

impl<'a> !UnwindSafe for EagerSession<'a>

§

impl<'a> Freeze for EagerSession<'a>

§

impl<'a> Unpin for EagerSession<'a>

§

impl<'a> UnsafeUnpin for EagerSession<'a>

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
§

impl<T> ByRef<T> for T

§

fn by_ref(&self) -> &T

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Imply<T> for U
where T: ?Sized, U: ?Sized,

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
§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(_simd: S, value: T) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

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.