gam_math/nested_dual.rs
1//! Nested second-order forward-AD dual for FD-free high-order cross-checks (#932).
2//!
3//! [`Dual2<S>`] is a single-direction second-order jet (`value`, first and second
4//! derivative in ONE direction) over a scalar field `S`. Because the field is
5//! generic, it composes with itself: `Dual2<Dual2<f64>>` carries every mixed
6//! partial `∂^i_a ∂^j_b` for `i, j ∈ {0, 1, 2}`, i.e. the full `2 + 2 = 4`th-order
7//! bidirectional derivative in two INDEPENDENT directions `a`, `b`.
8//!
9//! Why this exists: the flexible survival marginal-slope Jet4 tower (the
10//! moving-boundary implicit-intercept path, gam#932) is the last derivative
11//! surface whose fourth-order channel is verified only by a finite-difference
12//! stencil — the hand reference is provably incomplete there, and a 4th-order
13//! FD probes a 6th derivative, so the truncation floor sits far above machine
14//! precision (the same pathology as gam#979). A nested dual evaluates the SAME
15//! single-source program by a DIFFERENT composition ordering (two nested
16//! second-order sweeps instead of one fourth-order sweep), so its
17//! `∂²_a ∂²_b` channel is a truncation-free, hand-oracle-free cross-check of the
18//! Jet4 bidirectional block.
19//!
20//! The construction is standard forward-over-forward automatic differentiation;
21//! its correctness is pinned channel-for-channel against the engine
22//! [`crate::jet_tower::Tower4`] on smooth programs (see the module tests).
23
24/// Minimal scalar field a [`Dual2`] can be built over. Implemented by `f64` (the
25/// base case) and by [`Dual2`] itself (the nesting case). Every operation mirrors
26/// the [`crate::jet_tower::Tower4`] / [`crate::jet_scalar::JetScalar`] Faà di
27/// Bruno convention exactly, so a program written against `JetField` evaluates
28/// identically on the engine tower and on a nested dual.
29///
30/// This is the SHARED scalar-field algebra base of the #932 tower: the
31/// const-`K` packed [`crate::jet_scalar::JetScalar`] and the runtime-`p`
32/// Vec-backed flex jets (`survival::marginal_slope::timepoint_exact::FlexJet`)
33/// both EXTEND it, so the field ops and the single Faà di Bruno composition are
34/// declared exactly ONCE here. It is deliberately NOT `Copy` (the Vec-backed
35/// flex jets are `Clone`, not `Copy`) and carries no constructor (a Vec-backed
36/// constant needs a primary count) — the `Copy`, `from_f64`-carrying nested-dual
37/// oracle path adds those through [`JetFieldConst`].
38pub trait JetField: Clone {
39 /// The real value channel (recurses through any nesting to the `f64` leaf).
40 fn value(&self) -> f64;
41 fn add(&self, o: &Self) -> Self;
42 fn sub(&self, o: &Self) -> Self;
43 fn mul(&self, o: &Self) -> Self;
44 fn neg(&self) -> Self;
45 /// Multiply every channel by a plain `f64`.
46 fn scale(&self, s: f64) -> Self;
47 /// Faà di Bruno composition `f ∘ self` given the OUTER real function's
48 /// derivative stack `d = [f(u), f′(u), f″(u), f‴(u), f⁗(u)]` evaluated at
49 /// `u = self.value()` — the identical `[f64; 5]` stack shape
50 /// [`crate::jet_tower::Tower4::compose_unary`] consumes.
51 fn compose_unary(&self, d: [f64; 5]) -> Self;
52
53 /// A constant carrying THIS element's shape: real value `v`, every
54 /// derivative channel zero.
55 ///
56 /// [`JetField`] deliberately has no dimensionless constructor (a Vec-backed
57 /// runtime-width constant needs a primary count), so a shape has to come
58 /// from an existing element. The default routes through [`Self::compose_unary`]
59 /// with a zero-derivative stack, which is correct for every implementor but
60 /// walks the whole Faa di Bruno partition sum to write a constant — at
61 /// `Dual2<Order2<K>>` that is three inner compositions plus four products,
62 /// all of whose channels are known zero ahead of time. Implementors on a hot
63 /// path override it with the direct construction. (#932)
64 fn constant_like(&self, v: f64) -> Self {
65 self.compose_unary([v, 0.0, 0.0, 0.0, 0.0])
66 }
67
68 /// `self` with its real value channel replaced by `v`, every derivative
69 /// channel untouched.
70 ///
71 /// This is the explicit form of the "anchor the value, keep the
72 /// derivatives" idiom that a row program uses to hold a previously computed
73 /// f64 result bitwise while lifting it into a jet. Expressing it as a
74 /// primitive (rather than as subtract-a-constant-then-add-a-constant) makes
75 /// the bitwise contract exact by construction instead of emergent from
76 /// floating-point cancellation. (#932)
77 fn with_value(&self, v: f64) -> Self {
78 self.sub(&self.constant_like(self.value()))
79 .add(&self.constant_like(v))
80 }
81}
82
83/// A [`JetField`] that is `Copy` and can be built from a real constant with
84/// every derivative channel zero. The nested-dual oracle (`Dual2` over a `Copy`
85/// leaf) needs a dimensionless constructor; the runtime-`p` Vec-backed flex jets
86/// deliberately do NOT satisfy this (their constant needs a primary count), so
87/// it lives on this subtrait rather than the shared algebra base.
88pub trait JetFieldConst: JetField + Copy {
89 /// A constant field element with value `x` and every derivative channel zero.
90 fn from_f64(x: f64) -> Self;
91}
92
93impl JetField for f64 {
94 #[inline]
95 fn value(&self) -> f64 {
96 *self
97 }
98 #[inline]
99 fn add(&self, o: &Self) -> Self {
100 *self + *o
101 }
102 #[inline]
103 fn sub(&self, o: &Self) -> Self {
104 *self - *o
105 }
106 #[inline]
107 fn mul(&self, o: &Self) -> Self {
108 *self * *o
109 }
110 #[inline]
111 fn neg(&self) -> Self {
112 -*self
113 }
114 #[inline]
115 fn scale(&self, s: f64) -> Self {
116 *self * s
117 }
118 #[inline]
119 fn compose_unary(&self, d: [f64; 5]) -> Self {
120 // The stack is already evaluated at `u = *self`; `f(u)` is `d[0]`.
121 d[0]
122 }
123 #[inline]
124 fn constant_like(&self, v: f64) -> Self {
125 v
126 }
127 #[inline]
128 fn with_value(&self, v: f64) -> Self {
129 v
130 }
131}
132
133impl JetFieldConst for f64 {
134 #[inline]
135 fn from_f64(x: f64) -> Self {
136 x
137 }
138}
139
140/// A single-direction second-order jet over the field `S`: value `v`, first
141/// derivative `g`, second derivative `h`, all with respect to ONE seeded
142/// direction. Nest it (`Dual2<Dual2<f64>>`) for a second, independent direction.
143#[derive(Clone, Copy, Debug)]
144pub struct Dual2<S: JetField> {
145 /// Value channel.
146 pub v: S,
147 /// First derivative in this dual's direction.
148 pub g: S,
149 /// Second derivative in this dual's direction.
150 pub h: S,
151}
152
153impl<S: JetFieldConst> Dual2<S> {
154 /// A constant (value `v`, zero derivatives) — carries no dependence on this
155 /// dual's direction (but `v` may still depend on an inner nested direction).
156 #[inline]
157 pub fn constant(v: S) -> Self {
158 Self {
159 v,
160 g: S::from_f64(0.0),
161 h: S::from_f64(0.0),
162 }
163 }
164
165 /// The seeded variable at `v`: unit first derivative in this dual's
166 /// direction, zero second derivative.
167 #[inline]
168 pub fn variable(v: S) -> Self {
169 Self {
170 v,
171 g: S::from_f64(1.0),
172 h: S::from_f64(0.0),
173 }
174 }
175}
176
177impl<S: JetField> JetField for Dual2<S> {
178 #[inline]
179 fn value(&self) -> f64 {
180 self.v.value()
181 }
182 #[inline]
183 fn add(&self, o: &Self) -> Self {
184 Self {
185 v: self.v.add(&o.v),
186 g: self.g.add(&o.g),
187 h: self.h.add(&o.h),
188 }
189 }
190 #[inline]
191 fn sub(&self, o: &Self) -> Self {
192 Self {
193 v: self.v.sub(&o.v),
194 g: self.g.sub(&o.g),
195 h: self.h.sub(&o.h),
196 }
197 }
198 #[inline]
199 fn mul(&self, o: &Self) -> Self {
200 // Leibniz in one direction: (uv)′ = u′v + uv′,
201 // (uv)″ = u″v + 2u′v′ + uv″.
202 Self {
203 v: self.v.mul(&o.v),
204 g: self.v.mul(&o.g).add(&self.g.mul(&o.v)),
205 h: self
206 .v
207 .mul(&o.h)
208 .add(&self.g.mul(&o.g).scale(2.0))
209 .add(&self.h.mul(&o.v)),
210 }
211 }
212 #[inline]
213 fn neg(&self) -> Self {
214 Self {
215 v: self.v.neg(),
216 g: self.g.neg(),
217 h: self.h.neg(),
218 }
219 }
220 #[inline]
221 fn scale(&self, s: f64) -> Self {
222 Self {
223 v: self.v.scale(s),
224 g: self.g.scale(s),
225 h: self.h.scale(s),
226 }
227 }
228 #[inline]
229 fn compose_unary(&self, d: [f64; 5]) -> Self {
230 // f∘self in one direction: with u = self, φ = f,
231 // value = φ(u)
232 // first = φ′(u)·u′
233 // second = φ′(u)·u″ + φ″(u)·(u′)²
234 // φ(u), φ′(u), φ″(u) are field-valued: compose the SHIFTED real stacks
235 // with the inner value `self.v`, which propagates any nested direction.
236 let f0 = self.v.compose_unary([d[0], d[1], d[2], d[3], d[4]]);
237 let f1 = self.v.compose_unary([d[1], d[2], d[3], d[4], 0.0]);
238 let f2 = self.v.compose_unary([d[2], d[3], d[4], 0.0, 0.0]);
239 Self {
240 v: f0,
241 g: f1.mul(&self.g),
242 h: f1.mul(&self.h).add(&f2.mul(&self.g).mul(&self.g)),
243 }
244 }
245 #[inline]
246 fn constant_like(&self, v: f64) -> Self {
247 // The default's `g`/`h` are `compose_unary([0;5]).mul(..)` products of a
248 // zero jet, i.e. structurally zero: build them directly.
249 Self {
250 v: self.v.constant_like(v),
251 g: self.v.constant_like(0.0),
252 h: self.v.constant_like(0.0),
253 }
254 }
255 #[inline]
256 fn with_value(&self, v: f64) -> Self {
257 // Only the real value channel lives in `self.v`; this dual's own
258 // derivative channels are untouched.
259 Self {
260 v: self.v.with_value(v),
261 g: self.g.clone(),
262 h: self.h.clone(),
263 }
264 }
265}
266
267impl<S: JetFieldConst> JetFieldConst for Dual2<S> {
268 #[inline]
269 fn from_f64(x: f64) -> Self {
270 Self::constant(S::from_f64(x))
271 }
272}
273
274/// A `Dual2<Dual2<f64>>` seeded with independent directions `a` (outer) and `b`
275/// (inner): value `x`, unit first derivative along both requested directions.
276/// `p0` should be seeded `(a=1, b=0)` and `p1` `(a=0, b=1)` for a two-primary
277/// program (mirrors `Tower4::variable(x, 0)` / `Tower4::variable(x, 1)`).
278pub type Dual22 = Dual2<Dual2<f64>>;
279
280impl Dual22 {
281 /// Seed a primary that varies only along the OUTER direction `a`
282 /// (`∂/∂a = 1`, `∂/∂b = 0`) — the `Tower4::variable(x, 0)` analogue.
283 #[inline]
284 pub fn seed_outer(x: f64) -> Self {
285 Dual2::variable(Dual2::<f64>::constant(x))
286 }
287 /// Seed a primary that varies only along the INNER direction `b`
288 /// (`∂/∂a = 0`, `∂/∂b = 1`) — the `Tower4::variable(x, 1)` analogue.
289 #[inline]
290 pub fn seed_inner(x: f64) -> Self {
291 Dual2::constant(Dual2::<f64>::variable(x))
292 }
293
294 /// Seed a primary at value `base` that moves as `base + s·d1 + t·d2` under the
295 /// two independent scalar directions `s` (outer `a`) and `t` (inner `b`):
296 /// `∂/∂a = d1`, `∂/∂b = d2`, all second-and-higher self-derivatives zero
297 /// (the primary is affine in `s, t`). This is what a directional
298 /// bidirectional contraction along arbitrary weight vectors `d1, d2` needs —
299 /// seed every primary `i` with `seed_directional(base_i, d1_i, d2_i)`, run
300 /// the program, and read `channels()[8]` (`∂²_a ∂²_b`) for
301 /// `Σ_{a,b,c,d} ℓ_{abcd}·d1_a d1_b d2_c d2_d`.
302 #[inline]
303 pub fn seed_directional(base: f64, d1: f64, d2: f64) -> Self {
304 Dual2 {
305 // value carries the inner (`t`) direction on its `g` channel.
306 v: Dual2::<f64> {
307 v: base,
308 g: d2,
309 h: 0.0,
310 },
311 // outer (`s`) first derivative is `d1`, itself constant in `t`.
312 g: Dual2::<f64>::constant(d1),
313 h: Dual2::<f64>::constant(0.0),
314 }
315 }
316
317 /// Build a nested dual directly from its nine `(s-order, t-order)` channels,
318 /// ordered as [`Self::channels`]: `[v, ∂a, ∂b, ∂aa, ∂ab, ∂bb, ∂aab, ∂abb,
319 /// ∂aabb]`. The inverse of [`Self::channels`]. Used to assemble the result of
320 /// a channel-space operation (e.g. a moment-recurrence residual term) back
321 /// into a `Dual22`.
322 #[inline]
323 pub fn from_channels(c: [f64; 9]) -> Self {
324 Dual2 {
325 v: Dual2::<f64> {
326 v: c[0],
327 g: c[2],
328 h: c[5],
329 },
330 g: Dual2::<f64> {
331 v: c[1],
332 g: c[4],
333 h: c[7],
334 },
335 h: Dual2::<f64> {
336 v: c[3],
337 g: c[6],
338 h: c[8],
339 },
340 }
341 }
342
343 /// The nine channels this nested dual represents, keyed to the two-primary
344 /// [`crate::jet_tower::Tower4`] indices `0` (outer `a`) and `1` (inner `b`):
345 /// `(value, ∂a, ∂b, ∂aa, ∂ab, ∂bb, ∂aab, ∂abb, ∂aabb)`.
346 #[inline]
347 pub fn channels(&self) -> [f64; 9] {
348 [
349 self.v.v, self.g.v, self.v.g, self.h.v, self.g.g, self.v.h, self.h.g, self.g.h,
350 self.h.h,
351 ]
352 }
353}
354
355#[cfg(test)]
356mod nested_dual_tower4_oracle_tests {
357 use super::*;
358 use crate::jet_tower::Tower4;
359
360 // `Tower4` is a production `JetField` (its `JetScalar` impl in `jet_scalar.rs`
361 // now rides the shared base), so the SAME `program` runs on both `Tower4<2>`
362 // and `Dual2<Dual2<f64>>` with no test-only bridge. The oracle path adds only
363 // the `Copy` constructor through `JetFieldConst`.
364 impl<const K: usize> JetFieldConst for Tower4<K> {
365 fn from_f64(x: f64) -> Self {
366 Tower4::constant(x)
367 }
368 }
369
370 /// exp stack `[e,e,e,e,e]` at `u`.
371 fn exp_stack(u: f64) -> [f64; 5] {
372 let e = u.exp();
373 [e, e, e, e, e]
374 }
375 /// ln stack `[ln u, 1/u, -1/u², 2/u³, -6/u⁴]` at `u > 0`.
376 fn ln_stack(u: f64) -> [f64; 5] {
377 let r = 1.0 / u;
378 [u.ln(), r, -r * r, 2.0 * r * r * r, -6.0 * r * r * r * r]
379 }
380
381 /// A smooth two-primary program with genuinely nonzero mixed fourth
382 /// derivatives, written once over `JetField` so it evaluates identically on
383 /// the engine `Tower4<2>` and on the nested `Dual2<Dual2<f64>>`.
384 ///
385 /// f(p0, p1) = exp(p0·p1 + 0.3·p0)
386 /// + ln(1 + p0² + 0.5·p1² + 0.2·p0·p1)
387 /// − 0.7·(p0 − p1)²
388 fn program<J: JetFieldConst>(p0: &J, p1: &J) -> J {
389 let one = J::from_f64(1.0);
390 // exp(p0·p1 + 0.3·p0)
391 let arg_e = p0.mul(p1).add(&p0.scale(0.3));
392 let term_exp = arg_e.compose_unary(exp_stack(arg_e.value()));
393 // ln(1 + p0² + 0.5·p1² + 0.2·p0·p1)
394 let arg_l = one
395 .add(&p0.mul(p0))
396 .add(&p1.mul(p1).scale(0.5))
397 .add(&p0.mul(p1).scale(0.2));
398 let term_ln = arg_l.compose_unary(ln_stack(arg_l.value()));
399 // −0.7·(p0 − p1)²
400 let diff = p0.sub(p1);
401 let term_quad = diff.mul(&diff).scale(-0.7);
402 term_exp.add(&term_ln).add(&term_quad)
403 }
404
405 /// The nested `Dual2<Dual2<f64>>` reproduces every channel it represents —
406 /// value, both gradients, the full Hessian, the two order-3 mixed channels,
407 /// and the order-4 bidirectional `∂²_a ∂²_b` — of the engine `Tower4<2>`, to
408 /// machine precision, over several smooth base points. This is the
409 /// truncation-free, hand-oracle-free proof the nested dual is a correct
410 /// fourth-order path before it is used to gate the flex Jet4 tower (#932).
411 #[test]
412 fn nested_dual2_reproduces_tower4_channels_932() {
413 let points = [
414 (0.31_f64, -0.42_f64),
415 (-0.85, 0.17),
416 (0.05, 0.93),
417 (1.2, -0.6),
418 ];
419 let mut max_rel = 0.0_f64;
420 for &(x0, x1) in &points {
421 // Engine tower.
422 let t0 = Tower4::<2>::variable(x0, 0);
423 let t1 = Tower4::<2>::variable(x1, 1);
424 let tower = program(&t0, &t1);
425
426 // Nested dual (outer = axis 0, inner = axis 1).
427 let d0 = Dual22::seed_outer(x0);
428 let d1 = Dual22::seed_inner(x1);
429 let nested = program(&d0, &d1);
430 let ch = nested.channels();
431
432 // (label, nested channel, tower channel).
433 let cmp = [
434 ("value", ch[0], tower.v),
435 ("d_a", ch[1], tower.g[0]),
436 ("d_b", ch[2], tower.g[1]),
437 ("d_aa", ch[3], tower.h[0][0]),
438 ("d_ab", ch[4], tower.h[0][1]),
439 ("d_bb", ch[5], tower.h[1][1]),
440 ("d_aab", ch[6], tower.t3[0][0][1]),
441 ("d_abb", ch[7], tower.t3[0][1][1]),
442 ("d_aabb", ch[8], tower.t4[0][0][1][1]),
443 ];
444 for (label, got, want) in cmp {
445 let rel = (got - want).abs() / want.abs().max(1.0);
446 max_rel = max_rel.max(rel);
447 assert!(
448 rel <= 1e-12,
449 "point ({x0},{x1}) channel {label}: nested {got:.16e} != tower {want:.16e} (rel {rel:.3e})"
450 );
451 }
452 }
453 eprintln!(
454 "[nested-dual #932] Dual2<Dual2> vs Tower4<2> max_rel over 4 points = {max_rel:.3e}"
455 );
456 }
457
458 /// The directional seeding (arbitrary weight vectors `d1`, `d2`) reproduces
459 /// the engine tower's fully-contracted derivatives:
460 /// `∂_s f = Σ_a g_a d1_a`,
461 /// `∂_t f = Σ_a g_a d2_a`,
462 /// `∂_s∂_t f = Σ_{ab} h_ab d1_a d2_b`,
463 /// `∂²_s∂²_t f = Σ_{abcd} ℓ_abcd d1_a d1_b d2_c d2_d`,
464 /// the last being exactly the bidirectional 4th-order contraction a flex
465 /// Jet4 gate needs (`ℓ_{dir1,dir1,dir2,dir2}`), FD-free. This is the seeding
466 /// the flex-geometry consumer will use.
467 #[test]
468 fn nested_dual2_directional_matches_tower4_contraction_932() {
469 let d1 = [0.7_f64, -0.3_f64];
470 let d2 = [0.4_f64, 0.9_f64];
471 let points = [(0.31_f64, -0.42_f64), (-0.85, 0.17), (1.2, -0.6)];
472 let mut max_rel = 0.0_f64;
473 for &(x0, x1) in &points {
474 let t0 = Tower4::<2>::variable(x0, 0);
475 let t1 = Tower4::<2>::variable(x1, 1);
476 let tower = program(&t0, &t1);
477
478 // Full engine contractions.
479 let mut c_s = 0.0;
480 let mut c_t = 0.0;
481 let mut c_st = 0.0;
482 let mut c_sstt = 0.0;
483 for a in 0..2 {
484 c_s += tower.g[a] * d1[a];
485 c_t += tower.g[a] * d2[a];
486 for b in 0..2 {
487 c_st += tower.h[a][b] * d1[a] * d2[b];
488 for cc in 0..2 {
489 for dd in 0..2 {
490 c_sstt += tower.t4[a][b][cc][dd] * d1[a] * d1[b] * d2[cc] * d2[dd];
491 }
492 }
493 }
494 }
495
496 let p0 = Dual22::seed_directional(x0, d1[0], d2[0]);
497 let p1 = Dual22::seed_directional(x1, d1[1], d2[1]);
498 let ch = program(&p0, &p1).channels();
499
500 for (label, got, want) in [
501 ("d_s", ch[1], c_s),
502 ("d_t", ch[2], c_t),
503 ("d_st", ch[4], c_st),
504 ("d_sstt", ch[8], c_sstt),
505 ] {
506 let rel = (got - want).abs() / want.abs().max(1.0);
507 max_rel = max_rel.max(rel);
508 assert!(
509 rel <= 1e-12,
510 "point ({x0},{x1}) {label}: nested {got:.16e} != tower-contraction {want:.16e} (rel {rel:.3e})"
511 );
512 }
513 }
514 eprintln!(
515 "[nested-dual #932] directional Dual2<Dual2> vs Tower4<2> contraction max_rel = {max_rel:.3e}"
516 );
517 }
518
519 /// `from_channels` is the exact inverse of `channels` (round-trip identity),
520 /// so a channel-space operation can be assembled back into a `Dual22`
521 /// without silently transposing a slot.
522 #[test]
523 fn nested_dual2_channels_from_channels_roundtrip_932() {
524 let c = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0];
525 let round = Dual22::from_channels(c).channels();
526 assert_eq!(round, c, "channels∘from_channels must be identity");
527 }
528
529 /// Symmetry guard: the mixed channels are order-independent — `∂a∂b == ∂b∂a`
530 /// and `∂²a∂²b` computed with the seeds swapped agrees — so the nested read
531 /// is not silently reading a transposed channel.
532 #[test]
533 fn nested_dual2_seed_swap_symmetry_932() {
534 let (x0, x1) = (0.4_f64, -0.55_f64);
535 let d0 = Dual22::seed_outer(x0);
536 let d1 = Dual22::seed_inner(x1);
537 let ab = program(&d0, &d1).channels();
538
539 // Swap which variable carries the outer vs inner seed.
540 let e0 = Dual22::seed_inner(x0);
541 let e1 = Dual22::seed_outer(x1);
542 let ba = program(&e0, &e1).channels();
543
544 // value, and the fully-symmetric 4th channel, must be seed-order
545 // invariant; the gradients swap (a<->b), as do the order-3 channels.
546 let close = |a: f64, b: f64| (a - b).abs() <= 1e-12 * (1.0 + b.abs());
547 assert!(close(ab[0], ba[0]), "value not seed-order invariant");
548 assert!(close(ab[8], ba[8]), "d_aabb not seed-order invariant");
549 assert!(close(ab[1], ba[2]), "d_a (ab) != d_b (ba)");
550 assert!(close(ab[6], ba[7]), "d_aab (ab) != d_abb (ba)");
551 }
552}