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};
use tenferro_cpu::CpuBackend;

let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(
    Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?, ctx.clone(),
)?;
let y = ctx.with_eager_session(|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;
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new()).unwrap();
let escaped = ctx.with_eager_session(|session| session).unwrap();
let _ = escaped;

Implementations§

Source§

impl<'a> EagerSession<'a>

Source

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

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

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

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

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

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(|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<&[usize]>, ) -> Result<EagerTensor>

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(|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: usize, ) -> Result<EagerTensor>

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(|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: usize, ) -> Result<EagerTensor>

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(|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: usize, ) -> Result<EagerTensor>

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(|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: usize, ) -> Result<EagerTensor>

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(|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: usize, weight: Option<&EagerTensor>, bias: Option<&EagerTensor>, eps: f64, ) -> Result<EagerTensor>

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(|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: usize, weight: Option<&EagerTensor>, bias: Option<&EagerTensor>, eps: f64, ) -> Result<EagerTensor>

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(|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: usize, ) -> Result<EagerTensor>

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

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

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

let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(
    Tensor::from_vec_col_major(vec![1], vec![4.0_f64])?, ctx.clone(),
)?;
let y = ctx.with_eager_session(|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>

Compute the elementwise exponential inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Compute the elementwise absolute value inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![-2.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Compute the elementwise conjugate inside this eager session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Compute the elementwise sign on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

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

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

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

Compute the elementwise sine on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Compute the elementwise cosine on this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

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

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

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

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

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

§Examples
use tenferro_ad::{DType, EagerRuntime, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let converted = ctx.with_eager_session(|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>

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

§Examples
use tenferro_ad::{DType, EagerRuntime, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let casted = ctx.with_eager_session(|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: &[usize], ) -> Result<EagerTensor>

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

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let copied = ctx.with_eager_session(|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>

Reshape an eager tensor while retaining a separate result owner.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

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

§Examples
use tenferro_ad::{EagerRuntime, SliceConfig, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let y = ctx.with_eager_session(|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>

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

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?, ctx.clone())?;
let copy = ctx.with_eager_session(|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>

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

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

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(|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: &[usize], ) -> Result<EagerTensor>

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

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

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(|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: usize, ) -> Result<EagerTensor>

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

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(|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: usize, axis_b: usize, ) -> Result<EagerTensor>

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(|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: usize, axis_b: usize, ) -> Result<EagerTensor>

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(|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<&[usize]>, ) -> Result<EagerTensor>

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?, ctx.clone())?;
let sum = ctx.with_eager_session(|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<&[usize]>, ) -> Result<EagerTensor>

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(|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<&[usize]>, ) -> Result<EagerTensor>

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(|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<&[usize]>, ) -> Result<EagerTensor>

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(|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<&[usize]>, ) -> Result<EagerTensor>

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

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![2.0_f64])?, ctx.clone())?;
let copy = ctx.with_eager_session(|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>

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let c = ctx.with_eager_session(|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>

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

Import a trainable leaf within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = ctx.with_eager_session(|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 add( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, ) -> Result<EagerTensor>

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?, ctx.clone())?;
let scalar = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![], vec![3.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Subtract eager tensors within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Multiply eager tensors within this borrowed session.

§Examples
use tenferro_ad::{EagerRuntime, EagerTensor, Tensor};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = EagerTensor::from_tensor_in(Tensor::from_vec_col_major(vec![1], vec![3.0_f64])?, ctx.clone())?;
let y = ctx.with_eager_session(|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>

Divide eager tensors elementwise with broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Compute the elementwise remainder with broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Raise eager tensor elements to broadcast exponents.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Compute the elementwise maximum under broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Compute the elementwise minimum under broadcast rules.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

Compare eager tensors elementwise under broadcast rules.

§Examples
use tenferro_ad::{CompareDir, EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let y = ctx.with_eager_session(|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>

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

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

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

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let result = ctx.with_eager_session(|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>

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(|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: Complex64, ) -> Result<EagerTensor>

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

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(|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_conj( &mut self, lhs: &EagerTensor, rhs: &EagerTensor, config: DotGeneralConfig, lhs_conj: bool, rhs_conj: bool, ) -> Result<EagerTensor>

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};
use tenferro_cpu::CpuBackend;
let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let result = ctx.with_eager_session(|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])?)?;
    session.dot_general_with_conj(&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(),
    }, true, false)
})?;
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>

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_cpu::CpuBackend;
use tenferro_ops::std_tensor_op::StdTensorOp;

let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let y = ctx.with_eager_session(|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 backend_session(&mut self) -> &mut dyn BackendSession

Borrow the backend session this eager session runs on.

Extension crates use it to run their backend kernels on untracked values inside the same execution region instead of entering a second session, which would be rejected as reentry. It grants the same access as EagerRuntime::with_execution_session.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
use tenferro_cpu::CpuBackend;
use tenferro_tensor::TensorRead;

let ctx = EagerRuntime::with_cpu_backend(CpuBackend::new())?;
let x = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, -2.0])?;
let copy = ctx.with_eager_session(|s| {
    s.backend_session()
        .to_contiguous_read(TensorRead::from_tensor(&x))
        .map_err(tenferro_ad::Error::from)
})?;
assert_eq!(copy.as_slice::<f64>()?, &[1.0, -2.0]);
Source

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

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

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(|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: usize, positions: &[usize], ) -> Result<EagerTensor>

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

Select matrix rows by host-known positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(|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>

Select matrix columns by host-known positions.

§Examples
use tenferro_ad::{EagerRuntime, Tensor};
let ctx = EagerRuntime::new()?;
let result = ctx.with_eager_session(|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>

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(|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: usize, range: Range<usize>, ) -> Result<EagerTensor>

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

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

Formats the value using the given formatter. 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
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.