Tape

Struct Tape 

Source
pub struct Tape<V: Differentiable> { /* private fields */ }
Expand description

Reverse-mode AD tape.

The tape records operations performed on TrackedTensor values and enables gradient computation via Tape::pullback or HVP via Tape::hvp.

Create leaf values with Tape::leaf, perform operations using AD-aware functions (e.g., tracked_einsum), then call Tape::pullback on the scalar loss to compute gradients.

Tape is cheaply cloneable (internally reference-counted). Multiple clones refer to the same underlying tape.

§Examples

use chainrules::Tape;
use tenferro_einsum::tracked_einsum;
use tenferro_tensor::{MemoryOrder, Tensor};
use tenferro_device::LogicalMemorySpace;

let tape = Tape::<Tensor<f64>>::new();
let a = tape.leaf(Tensor::ones(
    &[2, 3],
    LogicalMemorySpace::MainMemory,
    MemoryOrder::ColumnMajor,
));
let b = tape.leaf(Tensor::ones(
    &[3, 4],
    LogicalMemorySpace::MainMemory,
    MemoryOrder::ColumnMajor,
));
let c = tracked_einsum("ij,jk->ik", &[&a, &b]).unwrap();
let loss = tracked_einsum("ij,ij->", &[&c, &c]).unwrap();
let grads = tape.pullback(&loss).unwrap();
let _ga = grads.get(a.node_id().unwrap()).unwrap();

Implementations§

Source§

impl<V: Differentiable> Tape<V>

Source

pub fn new() -> Self

Creates a new empty tape.

§Examples
use chainrules::Tape;

let tape = Tape::<f64>::new();
Source

pub fn leaf(&self, _value: V) -> TrackedTensor<V>

Creates a leaf value requiring gradient on this tape.

The returned TrackedTensor is connected to this tape and will participate in gradient computation via Tape::pullback.

§Examples
use chainrules::Tape;

let tape = Tape::<f64>::new();
let x = tape.leaf(3.14);
assert!(x.requires_grad());
Source

pub fn leaf_with_tangent( &self, _value: V, _tangent: V::Tangent, ) -> AdResult<TrackedTensor<V>>

Creates a leaf value with a tangent for HVP computation.

The tangent defines the perturbation direction v used in forward-over-reverse Hessian-vector product computation.

§Errors

Returns AutodiffError::TangentShapeMismatch if shapes differ.

§Examples
use chainrules::Tape;

let tape = Tape::<f64>::new();
let x = tape.leaf_with_tangent(3.14, 1.0).unwrap();
assert!(x.requires_grad());
assert!(x.has_tangent());
Source

pub fn pullback(&self, _loss: &TrackedTensor<V>) -> AdResult<Gradients<V>>

Runs reverse-mode pullback from a scalar loss value.

§Errors

Returns AutodiffError::NonScalarLoss for non-scalar losses. Returns AutodiffError::MissingNode if the loss is not connected to this tape.

§Examples
use chainrules::Tape;

let tape = Tape::<f64>::new();
let x = tape.leaf(2.0);
// ... compute loss from x ...
let grads = tape.pullback(&x).unwrap();
Source

pub fn hvp(&self, _loss: &TrackedTensor<V>) -> AdResult<HvpResult<V>>

Computes gradient and Hessian-vector product via forward-over-reverse.

Leaf values with tangents (created via Tape::leaf_with_tangent) define the direction v. The function runs pullback through the tape, propagating both cotangents and cotangent-tangents at each node.

Returns both the gradient (in HvpResult::gradients) and H*v (in HvpResult::hvp).

§Errors

Returns AutodiffError::NonScalarLoss for non-scalar losses. Returns AutodiffError::HvpNotSupported if any ReverseRule on the tape does not implement pullback_with_tangents.

§Examples
use chainrules::Tape;
use tenferro_einsum::tracked_einsum;
use tenferro_tensor::{MemoryOrder, Tensor};
use tenferro_device::LogicalMemorySpace;

let tape = Tape::<Tensor<f64>>::new();
let x = tape.leaf_with_tangent(
    Tensor::ones(&[3], LogicalMemorySpace::MainMemory, MemoryOrder::ColumnMajor),
    Tensor::ones(&[3], LogicalMemorySpace::MainMemory, MemoryOrder::ColumnMajor),
).unwrap();
let loss = tracked_einsum("i,i->", &[&x, &x]).unwrap();
let result = tape.hvp(&loss).unwrap();
let _grad = result.gradients;
let _hv = result.hvp;

Trait Implementations§

Source§

impl<V: Differentiable> Clone for Tape<V>

Source§

fn clone(&self) -> Self

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

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

Performs copy-assignment from source. Read more
Source§

impl<V: Differentiable> Default for Tape<V>

Source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl<V> Freeze for Tape<V>

§

impl<V> RefUnwindSafe for Tape<V>
where V: RefUnwindSafe,

§

impl<V> Send for Tape<V>
where V: Send,

§

impl<V> Sync for Tape<V>
where V: Sync,

§

impl<V> Unpin for Tape<V>
where V: Unpin,

§

impl<V> UnwindSafe for Tape<V>
where V: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

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

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

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

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

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.