Repository navigation
Conversation
| 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 { |
There was a problem hiding this comment.
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.
| fn powf(self, n: Self) -> Self { | ||
| let value = self.value.powf(n.value); | ||
| let partial_base = || { | ||
| if n.value == T::ZERO { |
There was a problem hiding this comment.
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.
| /// ``` | ||
| #[inline] | ||
| #[must_use] | ||
| pub fn try_with_capacity(capacity: usize) -> Option<Self> { |
There was a problem hiding this comment.
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]; |
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
This repeats the match in record_binary. Compute both partials and call record_binary.
| assert!((adj.deriv(big_y) - inv_sqrt2).abs() < TOL); | ||
| } | ||
|
|
||
| struct CountingRosenbrock<const N: usize> { |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
Same here: gradient and value_and_gradient do not return DiffError.
|
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. |
|
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. |
Summary
Forward-mode
Dualnumbers evaluate one directional derivative per pass, so computing a gradient overNinputs requiresNfunction evaluations. This adds tape-based reverse-mode automatic differentiation behind the optionalallocfeature so gradients of many-input functions used in optimization are computed in a single forward evaluation and reverse sweep.Change
crates/multicalc/src/scalar/reverse.rsgated behind#[cfg(feature = "alloc")](withdoc_cfgbadges) implementing:Tape<T = f64>:no_std+allocWengert list backed byRefCell<Vec<Node<T>>>(zerounsafe, zero panics). Exposesnew,try_with_capacity,try_reserve,var,vars,vars_array,len,is_empty,clear,value_and_gradient,gradient,value_and_gradient_slice, andgradient_sliceso callers can reserve capacity fallibly, reuse tape storage across optimization iterations, and handle bothScalarFnN<N>and dynamic-length slices.TapeVar<'tape, T = f64>:Copyreverse-mode scalar implementingNumeric(all arithmetic, elementary, transcendental, step, clamping, and comparison operations matchingDualsemantics) andPrimal. Exposesconstant,value,backward, andbackward_with_seed. Constants fold without allocating tape nodes;powfhandles zero base with positive exponent (∂(0^p)/∂p = 0) without0 * ln(0)NaN poisoning;tanhcomputessech²(x) = (2 / (1 + e^(-2|x|)))² * e^(-2|x|)so derivatives stay accurate inf32even when the primal saturates to±1; cross-tape mismatches across every binary operation (includingmax,min,copysign, zero-lengthhypot, and zero-divisorsafe_div) poison the result so both value and gradient-only APIs surfaceNaNwithout panicking.Adjoints<'tape, T = f64>: accumulated partial derivatives from a backward sweep withderiv,gradient, andgradient_array. Skips zero-adjoint nodes during backpropagation so unused singularities do not poison unrelated gradients.gradientandvalue_and_gradienthelpers incrates/multicalc/src/numerical_derivative/mod.rs(gated onalloc), and re-exportsTape,TapeVar,Adjoints,gradient, andvalue_and_gradientat the crate root (plusgradientandvalue_and_gradientinprelude).crates/multicalc/tests/suite/scalar.rsunderscalar::reversecovering allNumericoperations vsDual, a 16-variable Rosenbrock single-evaluation proof vsAutoDiffMultiandFiniteDifferenceMulti, a 64-variable slice optimization loop with tape reuse, zero-basepowfexponent fitting, saturatedf32tanhderivatives, fallible capacity reservation (try_with_capacity/try_reserve), diamond DAG accumulation, dead-branch singularities, multi-output reverse Jacobians/VJPs, cross-tapeNaNpropagation across all binary ops (+,*,atan2,powf,max,min,copysign, zero-lengthhypot, zero-divisorsafe_div) throughgradient_sliceandbackward,f32identities,Primalprojection, and a 256-case proptest comparing reverse-mode gradients against forward-mode and finite differences.crates/multicalc/tutorials/scalars-and-automatic-differentiation.md,crates/multicalc/tutorials/derivatives-jacobians-and-hessians.md, andCHANGELOG.mdunder## [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 warningsandcargo 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.cargo test -p multicalc --test suite --features allocon Windows MSVC previously hit 1 pre-existing unrelated failure innumerical_derivative::fd_default_step_scales_with_scalar_typedue to a 1-ULP difference betweenlibm::cbrt(f64::EPSILON)(6.0554544523933395e-6) and Windows MSVC UCRTf64::cbrt(6.055454452393339e-6).Fixes #47