Skip to content

Add tape-based reverse-mode automatic differentiation - #394

Open
rvyyv-n wants to merge 7 commits into
kmolan:mainfrom
rvyyv-n:fix/issue-47
Open

rvyyv-n wants to merge 7 commits into
kmolan:mainfrom
rvyyv-n:fix/issue-47

Conversation

@rvyyv-n

@rvyyv-n rvyyv-n commented Dec 1, 2026

Copy link
Copy Markdown

Summary

Forward-mode Dual numbers evaluate one directional derivative per pass, so computing a gradient over N inputs requires N function evaluations. This adds tape-based reverse-mode automatic differentiation behind the optional alloc feature so gradients of many-input functions used in optimization are computed in a single forward evaluation and reverse sweep.

Change

  • Adds crates/multicalc/src/scalar/reverse.rs gated behind #[cfg(feature = "alloc")] (with doc_cfg badges) implementing:
    • Tape<T = f64>: no_std+alloc Wengert list backed by RefCell<Vec<Node<T>>> (zero unsafe, zero panics). Exposes new, try_with_capacity, try_reserve, var, vars, vars_array, len, is_empty, clear, value_and_gradient, gradient, value_and_gradient_slice, and gradient_slice so callers can reserve capacity fallibly, reuse tape storage across optimization iterations, and handle both ScalarFnN<N> and dynamic-length slices.
    • TapeVar<'tape, T = f64>: Copy reverse-mode scalar implementing Numeric (all arithmetic, elementary, transcendental, step, clamping, and comparison operations matching Dual semantics) and Primal. Exposes constant, value, backward, and backward_with_seed. Constants fold without allocating tape nodes; powf handles zero base with positive exponent (∂(0^p)/∂p = 0) without 0 * ln(0) NaN poisoning; tanh computes sech²(x) = (2 / (1 + e^(-2|x|)))² * e^(-2|x|) so derivatives stay accurate in f32 even when the primal saturates to ±1; cross-tape mismatches across every binary operation (including max, min, copysign, zero-length hypot, and zero-divisor safe_div) poison the result so both value and gradient-only APIs surface NaN without panicking.
    • Adjoints<'tape, T = f64>: accumulated partial derivatives from a backward sweep with deriv, gradient, and gradient_array. Skips zero-adjoint nodes during backpropagation so unused singularities do not poison unrelated gradients.
  • Adds one-call gradient and value_and_gradient helpers in crates/multicalc/src/numerical_derivative/mod.rs (gated on alloc), and re-exports Tape, TapeVar, Adjoints, gradient, and value_and_gradient at the crate root (plus gradient and value_and_gradient in prelude).
  • Adds 14 tests in crates/multicalc/tests/suite/scalar.rs under scalar::reverse covering all Numeric operations vs Dual, a 16-variable Rosenbrock single-evaluation proof vs AutoDiffMulti and FiniteDifferenceMulti, a 64-variable slice optimization loop with tape reuse, zero-base powf exponent fitting, saturated f32 tanh derivatives, fallible capacity reservation (try_with_capacity / try_reserve), diamond DAG accumulation, dead-branch singularities, multi-output reverse Jacobians/VJPs, cross-tape NaN propagation across all binary ops (+, *, atan2, powf, max, min, copysign, zero-length hypot, zero-divisor safe_div) through gradient_slice and backward, f32 identities, Primal projection, and a 256-case proptest comparing reverse-mode gradients against forward-mode and finite differences.
  • Updates crates/multicalc/tutorials/scalars-and-automatic-differentiation.md, crates/multicalc/tutorials/derivatives-jacobians-and-hessians.md, and CHANGELOG.md under ## [Unreleased] -> Added.

Testing

  • cargo test -p multicalc --test suite --features alloc scalar::reverse: 14 passed, 0 failed.
  • cargo test -p multicalc --test suite --features alloc scalar::: 102 passed, 0 failed.
  • cargo test -p multicalc --test suite scalar::: 88 passed, 0 failed.
  • cargo test -p multicalc --lib --features alloc: 38 passed, 0 failed.
  • cargo test -p multicalc --doc --features alloc: 608 passed (605 + 3 compile-fail, 4 ignored), 0 failed.
  • cargo test -p multicalc --doc: 490 passed (487 + 3 compile-fail), 0 failed.
  • cargo clippy -p multicalc --all-targets --features alloc -- -D warnings and cargo clippy -p multicalc --all-targets -- -D warnings: clean.
  • cargo fmt --all -- --check: clean.
  • RUSTDOCFLAGS="-D warnings" cargo doc -p multicalc --no-deps --all-features: clean.
  • Full cargo test -p multicalc --test suite --features alloc on Windows MSVC previously hit 1 pre-existing unrelated failure in numerical_derivative::fd_default_step_scales_with_scalar_type due to a 1-ULP difference between libm::cbrt(f64::EPSILON) (6.0554544523933395e-6) and Windows MSVC UCRT f64::cbrt (6.055454452393339e-6).

Fixes #47

@rvyyv-n
rvyyv-n requested a review from kmolan as a code owner December 1, 2026 16:24

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the first PR! 🎉 You'll get a first review within 48 h. CI runs the 5-target matrix — a budget-gate failure isn't your fault, see ci/README.md.

Comment thread crates/multicalc/src/scalar/reverse.rs Outdated
for index in (0..=output_index).rev() {
let adjoint = values.get(index).copied().unwrap_or(T::ZERO);
// Skip zero adjoints so unused nodes neither waste work nor turn `0 * inf` into NaN.
if adjoint == T::ZERO {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This compares only the primal, so it drops the payload of a nested adjoint: sin(x)² at 0 has f'' = 2, but Tape<Dual> and Tape<TapeVar> give 0. It also hides singularities: x.sqrt() * x.sqrt() at 0 gives 0, where Dual gives NaN.

Skip unreached nodes instead, for example with Vec<Option<T>>. Please add tests for both cases.

Comment thread crates/multicalc/src/scalar/reverse.rs Outdated
fn powf(self, n: Self) -> Self {
let value = self.value.powf(n.value);
let partial_base = || {
if n.value == T::ZERO {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This drops the payload of the exponent: at b = 2, n = 0, ∂²(bⁿ)/∂b∂n is 0.5, but Tape<Dual> gives 0. Guard only when the base is also zero.

Comment thread crates/multicalc/src/scalar/reverse.rs Outdated
/// ```
#[inline]
#[must_use]
pub fn try_with_capacity(capacity: usize) -> Option<Self> {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove try_with_capacity and try_reserve. Recording and backward still allocate infallibly, so they give no guarantee.

}

let length = output_index + 1;
let mut values = vec![T::ZERO; length];

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each sweep allocates this vector, so tape reuse is not allocation-free. Keep the buffer in Tape, or document this.

}

#[inline]
fn powf(self, n: Self) -> Self {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats the match in record_binary. Compute both partials and call record_binary.

Comment thread crates/multicalc/tests/suite/scalar.rs Outdated
assert!((adj.deriv(big_y) - inv_sqrt2).abs() < TOL);
}

struct CountingRosenbrock<const N: usize> {

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move the N-dimensional Rosenbrock function to tools/testkit.

assert_eq!(slice_grad, vec![2.0, 4.0, 6.0]);
```

Errors: differentiation calls return [`DiffError`](error-handling.md): `OrderZero`, or

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gradient and value_and_gradient do not return DiffError.

`ScalarFnN` in a single reverse-mode pass, and `Jacobian::evaluate_on_heap` and
`Hessian::evaluate_on_heap` return a `Vec<Vec<T>>` for inputs too large for the stack.

Errors: these calls return [`DiffError`](error-handling.md):

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here: gradient and value_and_gradient do not return DiffError.

@kmolan

kmolan commented Dec 1, 2026

Copy link
Copy Markdown
Owner

Hi @rvyyv-n thank you very much for tackling this item. Its been on my to-do list of a long time now. I want to take some time to go over this PR and think about how it should interact with other modules in multicalc.

@rvyyv-n

rvyyv-n commented Dec 1, 2026

Copy link
Copy Markdown
Author

You're welcome, @kmolan! No rush at all — happy to iterate on the API or how it integrates with the other modules once you've had a chance to look it over.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add reverse-mode automatic differentiation

2 participants