tang-ad
Reverse-mode automatic differentiation. Record a tape, sweep backward, get gradients of scalar functions with many inputs — the shape that matters for optimization.
How it works
Forward pass: Backward pass:
x₀ ──┐ ∂L/∂x₀ ←──┐
├── f ── y │ │
x₁ ──┘ │ ∂L/∂x₁ ←──┤
│ │
└── g ── L ∂L/∂L = 1
│
tape records → sweeps ←
Quickstart
use grad;
// gradient of a scalar function
let g = grad;
// g = [2.0, 4.0, 6.0]
Full API
Five functions cover the common cases:
use ;
// ∇f: gradient (reverse-mode, scalar output)
let g = grad;
// J: Jacobian (forward-mode via Dual numbers)
let j = jacobian_fwd;
// H: Hessian (forward-over-forward, Dual<Dual<f64>>)
let h = hessian;
// vᵀJ: vector-Jacobian product (reverse-mode)
let vj = vjp;
// Jv: Jacobian-vector product (forward-mode)
let jv = jvp;
Building the tape manually
For more control, build a Tape and use Var directly:
use ;
let tape = new;
let x = new;
let y = new;
let z = .sqrt;
let grads = z.backward;
// grads[0] = 3/5, grads[1] = 4/5
Var supports sin, cos, exp, ln, sqrt, abs, tanh, powf, and all arithmetic operators with mixed Var/f64 operands.
Mixed-mode AD
| Function | Mode | Best for |
|---|---|---|
grad |
Reverse | f: ℝⁿ → ℝ (loss functions) |
jacobian_fwd |
Forward (Dual) | f: ℝⁿ → ℝᵐ where m ≈ n |
hessian |
Forward-over-forward | Second derivatives |
vjp |
Reverse | Backpropagation through vector outputs |
jvp |
Forward | Directional derivatives |
Design
#![no_std]— usesallocfor heap- Tape is
Arc-wrapped — thread-safe reference counting - Index-based graph — each
Varis a position on the tape, no pointer chasing - Sparse backward — skips zero adjoints during the sweep