Skip to main content

echidna_optim/
piggyback.rs

1use std::fmt;
2
3use echidna::{BytecodeTape, Dual, Float};
4
5/// Reason a piggyback solve failed to converge.
6///
7/// Marked `#[non_exhaustive]` so future variants can be added without
8/// breaking exhaustive `match`es. Numeric fields use `f64` (cast via
9/// `Float::to_f64`) for uniform diagnostic output regardless of the
10/// solver's `F` type.
11#[non_exhaustive]
12#[derive(Debug, Clone)]
13pub enum PiggybackError {
14    /// The primal `z_{k+1} = G(z_k, x)` produced a non-finite norm
15    /// (relative-norm `||z_new - z||/(1 + ||z||)` is NaN/Inf), or
16    /// the primal vector itself contained non-finite components in
17    /// the forward-adjoint loop. `last_norm` is the primal-delta
18    /// relative norm at the detecting iteration: non-finite when
19    /// detection came from the norm check (the usual case);
20    /// finite — and itself diagnostic — when detection came from
21    /// the componentwise finite check (primal vector overflowed
22    /// mid-iteration while the step-to-step delta stayed bounded).
23    PrimalDivergence { iteration: usize, last_norm: f64 },
24    /// Primal stayed finite but the tangent
25    /// `ż_{k+1} = G_z · ż_k + G_x · ẋ` produced non-finite values.
26    /// Catches the ratio-converging case where the primal norm
27    /// remains bounded while individual tangent components overflow.
28    /// `last_norm` is the primal-delta relative norm at the
29    /// detecting iteration — **finite** by construction here (the
30    /// tangent-only divergence path takes the norm-finite branch
31    /// before the componentwise check fires); surfacing it tells
32    /// the caller the primal iteration was bounded while the JVP
33    /// overflowed.
34    TangentDivergence { iteration: usize, last_norm: f64 },
35    /// Adjoint `λ_{k+1} = G_z^T · λ_k + z̄` produced non-finite
36    /// values (norm or individual components). `last_norm` is the
37    /// adjoint-delta relative norm at the detecting iteration:
38    /// non-finite when detection came from the norm check; finite
39    /// when it came from the componentwise `lambda_new` check.
40    AdjointDivergence { iteration: usize, last_norm: f64 },
41    /// `piggyback_tangent_solve` reached `max_iter` before **both** the
42    /// primal and tangent step-deltas met `tol`. `z_norm` is the final
43    /// iteration's relative primal-delta norm
44    /// (`||z_new - z|| / (1 + ||z||)`) — a value just over `tol` signals
45    /// proximity to convergence; many orders over signals stagnation; a
46    /// value **at or below** `tol` means the primal had converged and the
47    /// tangent (which starts at zero and converges on its own schedule)
48    /// was the stream still iterating. `iteration` equals `max_iter`.
49    IterationsExhaustedTangent { iteration: usize, z_norm: f64 },
50    /// `piggyback_adjoint_solve` reached `max_iter` without meeting
51    /// `tol`. `lam_norm` is the final iteration's relative adjoint-
52    /// delta norm (`||λ_new - λ|| / (1 + ||λ||)`).
53    IterationsExhaustedAdjoint { iteration: usize, lam_norm: f64 },
54    /// `piggyback_forward_adjoint_solve` reached `max_iter` without
55    /// meeting `tol` on both norms simultaneously. Each field is the
56    /// final iteration's relative norm for the corresponding stream.
57    IterationsExhaustedForwardAdjoint {
58        iteration: usize,
59        z_norm: f64,
60        lam_norm: f64,
61    },
62    /// A runtime-supplied vector argument to a public `*_solve` fn
63    /// had an unexpected length. `field` names the argument (e.g.
64    /// `"z_dot"`, `"z_bar"`), `expected` is the length the API
65    /// requires (typically `num_states` or `x.len()`), `actual` is
66    /// the length the caller supplied.
67    ///
68    /// Note: tape-shape contract mismatches
69    /// (`validate_step_tape`) and step-fn argument mismatches
70    /// (`piggyback_tangent_step[_with_buf]`) continue to panic —
71    /// those are programmer-contract violations, not recoverable
72    /// runtime failures.
73    DimensionMismatch {
74        field: &'static str,
75        expected: usize,
76        actual: usize,
77    },
78}
79
80impl fmt::Display for PiggybackError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        match self {
83            PiggybackError::PrimalDivergence {
84                iteration,
85                last_norm,
86            } => {
87                write!(
88                    f,
89                    "piggyback: primal diverged at iteration {iteration} (last_norm = {last_norm:.3e})"
90                )
91            }
92            PiggybackError::TangentDivergence {
93                iteration,
94                last_norm,
95            } => {
96                write!(
97                    f,
98                    "piggyback: tangent diverged at iteration {iteration} (last_norm = {last_norm:.3e})"
99                )
100            }
101            PiggybackError::AdjointDivergence {
102                iteration,
103                last_norm,
104            } => {
105                write!(
106                    f,
107                    "piggyback: adjoint diverged at iteration {iteration} (last_norm = {last_norm:.3e})"
108                )
109            }
110            PiggybackError::IterationsExhaustedTangent { iteration, z_norm } => {
111                write!(
112                    f,
113                    "piggyback: tangent solve reached max_iter = {iteration} (z_norm = {z_norm:.3e})"
114                )
115            }
116            PiggybackError::IterationsExhaustedAdjoint {
117                iteration,
118                lam_norm,
119            } => {
120                write!(
121                    f,
122                    "piggyback: adjoint solve reached max_iter = {iteration} (lam_norm = {lam_norm:.3e})"
123                )
124            }
125            PiggybackError::IterationsExhaustedForwardAdjoint {
126                iteration,
127                z_norm,
128                lam_norm,
129            } => {
130                write!(
131                    f,
132                    "piggyback: forward-adjoint solve reached max_iter = {iteration} (z_norm = {z_norm:.3e}, lam_norm = {lam_norm:.3e})"
133                )
134            }
135            PiggybackError::DimensionMismatch {
136                field,
137                expected,
138                actual,
139            } => {
140                write!(
141                    f,
142                    "piggyback: dimension mismatch for `{field}` (expected {expected}, got {actual})"
143                )
144            }
145        }
146    }
147}
148
149impl std::error::Error for PiggybackError {}
150
151echidna::assert_send_sync!(PiggybackError);
152
153/// Validate that a step tape G: R^(m+n) -> R^m has the expected shape.
154///
155/// Uses `assert_eq!` (panic) rather than `Result` because shape
156/// mismatches are programmer errors — calling `piggyback_*_solve` with
157/// an inconsistent tape is a contract violation, not a runtime
158/// numerical failure that callers should recover from.
159fn validate_step_tape<F: Float>(tape: &BytecodeTape<F>, z: &[F], x: &[F], num_states: usize) {
160    assert_eq!(z.len(), num_states);
161    assert_eq!(tape.num_inputs(), num_states + x.len());
162    assert_eq!(
163        tape.num_outputs(),
164        num_states,
165        "step tape must have num_outputs == num_states (G: R^(m+n) -> R^m)"
166    );
167}
168
169/// Relative step delta `||new - old|| / (1 + ||old||)` — the fixed-point
170/// convergence convention shared by every piggyback stream. Plain
171/// accumulation on purpose: `convergence::norm` switches to compensated
172/// summation at larger n, which would shift gate values and the norms
173/// reported in `PiggybackError`.
174fn relative_delta_norm<F: Float>(new: &[F], old: &[F]) -> F {
175    let mut delta_sq = F::zero();
176    let mut old_sq = F::zero();
177    for (&n, &o) in new.iter().zip(old.iter()) {
178        let d = n - o;
179        delta_sq = delta_sq + d * d;
180        old_sq = old_sq + o * o;
181    }
182    delta_sq.sqrt() / (F::one() + old_sq.sqrt())
183}
184
185/// One tangent piggyback step through a fixed-point map G.
186///
187/// Given the iteration `z_{k+1} = G(z_k, x)`, computes both the primal step
188/// and the tangent propagation `ż_{k+1} = G_z · ż_k + G_x · ẋ` in a single
189/// forward pass using dual numbers.
190///
191/// Returns `(z_new, z_dot_new)`.
192pub fn piggyback_tangent_step<F: Float>(
193    step_tape: &BytecodeTape<F>,
194    z: &[F],
195    x: &[F],
196    z_dot: &[F],
197    x_dot: &[F],
198    num_states: usize,
199) -> (Vec<F>, Vec<F>) {
200    let mut buf = Vec::new();
201    piggyback_tangent_step_with_buf(step_tape, z, x, z_dot, x_dot, num_states, &mut buf)
202}
203
204/// One tangent piggyback step, reusing `buf` across calls.
205///
206/// Same as [`piggyback_tangent_step`] but avoids reallocating the internal
207/// dual-number buffer on each call.
208pub fn piggyback_tangent_step_with_buf<F: Float>(
209    step_tape: &BytecodeTape<F>,
210    z: &[F],
211    x: &[F],
212    z_dot: &[F],
213    x_dot: &[F],
214    num_states: usize,
215    buf: &mut Vec<Dual<F>>,
216) -> (Vec<F>, Vec<F>) {
217    validate_step_tape(step_tape, z, x, num_states);
218    let m = num_states;
219    let n = x.len();
220    assert_eq!(z_dot.len(), m, "z_dot length must equal num_states");
221    assert_eq!(x_dot.len(), n, "x_dot length must equal x length");
222
223    // Build dual inputs: [Dual(z_i, ż_i), ..., Dual(x_j, ẋ_j), ...]
224    let mut dual_inputs = Vec::with_capacity(m + n);
225    for i in 0..m {
226        dual_inputs.push(Dual::new(z[i], z_dot[i]));
227    }
228    for j in 0..n {
229        dual_inputs.push(Dual::new(x[j], x_dot[j]));
230    }
231
232    // Dual-specialized sweep: custom ops evaluate their tangents at the
233    // current (z, x) via eval_dual instead of a recording-time linearization.
234    step_tape.forward_tangent_dual(&dual_inputs, buf);
235
236    // Extract outputs: .re -> z_new, .eps -> z_dot_new
237    let out_indices = step_tape.all_output_indices();
238    let mut z_new = Vec::with_capacity(m);
239    let mut z_dot_new = Vec::with_capacity(m);
240    for &idx in out_indices {
241        let d = buf[idx as usize];
242        z_new.push(d.re);
243        z_dot_new.push(d.eps);
244    }
245
246    (z_new, z_dot_new)
247}
248
249/// Tangent piggyback solve: find fixed point z* = G(z*, x) and its tangent ż*.
250///
251/// Iterates the fixed-point map `z_{k+1} = G(z_k, x)` while simultaneously
252/// propagating tangents `ż_{k+1} = G_z · ż_k + G_x · ẋ`.
253///
254/// Returns `Ok((z_star, z_dot_star, iterations))` when **both** iterates
255/// have converged (relative step-delta below `tol` for each). The tangent
256/// starts at zero and converges on its own schedule — its error decays as
257/// `ρᵏ·‖ż*‖` regardless of how close `z0` is to `z*` — so primal
258/// convergence alone would return a truncated Neumann sum for a
259/// warm-started primal. Returns
260/// `Err(PiggybackError::PrimalDivergence)` when the primal norm becomes
261/// non-finite, `Err(PiggybackError::TangentDivergence)` when the primal
262/// stays finite but the tangent overflows (ratio-converging case), or
263/// `Err(PiggybackError::IterationsExhaustedTangent { iteration, z_norm })` when
264/// `max_iter` is reached before both deltas satisfy `tol`.
265pub fn piggyback_tangent_solve<F: Float>(
266    step_tape: &BytecodeTape<F>,
267    z0: &[F],
268    x: &[F],
269    x_dot: &[F],
270    num_states: usize,
271    max_iter: usize,
272    tol: F,
273) -> Result<(Vec<F>, Vec<F>, usize), PiggybackError> {
274    // Runtime vector-length check at solve-level: surfaces dimension
275    // mismatches as `Err` before the first iteration dispatches to the
276    // step fn (which still panics on bad input as a contract-level
277    // guarantee).
278    if x_dot.len() != x.len() {
279        return Err(PiggybackError::DimensionMismatch {
280            field: "x_dot",
281            expected: x.len(),
282            actual: x_dot.len(),
283        });
284    }
285    let m = num_states;
286    let mut z = z0.to_vec();
287    let mut z_dot = vec![F::zero(); m];
288    let mut buf = Vec::new();
289    let mut last_norm: f64 = f64::NAN;
290
291    for k in 0..max_iter {
292        let (z_new, z_dot_new) =
293            piggyback_tangent_step_with_buf(step_tape, &z, x, &z_dot, x_dot, num_states, &mut buf);
294
295        // Relative convergence: ||z_new - z|| / (1 + ||z||)
296        let norm = relative_delta_norm(&z_new, &z);
297        // Variant-mapping order: norm-check first → PrimalDivergence;
298        // tangent-finite check second → TangentDivergence. A non-finite
299        // primal naturally produces a non-finite norm, so it falls into
300        // PrimalDivergence by detection priority.
301        if !norm.is_finite() {
302            return Err(PiggybackError::PrimalDivergence {
303                iteration: k,
304                last_norm: norm.to_f64().unwrap_or(f64::NAN),
305            });
306        }
307        // Detect tangent divergence even when the primal `z_new` itself is
308        // finite: the JVP iteration `z_dot_{k+1} = G_z·z_dot_k + G_x·x_dot`
309        // can produce Inf/NaN tangents that a primal-only norm check misses.
310        if !z_dot_new.iter().all(|v| v.is_finite()) {
311            // `norm` is guaranteed finite here — the `!norm.is_finite()`
312            // branch above would have returned `PrimalDivergence` first.
313            // The debug_assert guards against a future refactor that
314            // reorders these checks and silently invalidates the
315            // `TangentDivergence::last_norm` docstring's "finite by
316            // construction" promise.
317            debug_assert!(
318                norm.is_finite(),
319                "TangentDivergence path must see a finite primal norm"
320            );
321            return Err(PiggybackError::TangentDivergence {
322                iteration: k,
323                last_norm: norm.to_f64().unwrap_or(f64::NAN),
324            });
325        }
326        // Tangent convergence, mirroring the primal's relative-delta form
327        // (and `piggyback_forward_adjoint_solve`'s two-stream gate). The
328        // tangent starts at zero, so its delta shrinks on its own schedule;
329        // gating on the primal alone would return early with a truncated
330        // Neumann sum whenever the primal is warm-started. A non-finite
331        // `tangent_norm` cannot fake convergence (`NaN < tol` and
332        // `Inf < tol` are both false), and non-finite tangents were already
333        // rejected componentwise above.
334        let tangent_norm = relative_delta_norm(&z_dot_new, &z_dot);
335
336        last_norm = norm.to_f64().unwrap_or(f64::NAN);
337        if norm < tol && tangent_norm < tol {
338            return Ok((z_new, z_dot_new, k + 1));
339        }
340
341        z = z_new;
342        z_dot = z_dot_new;
343    }
344
345    Err(PiggybackError::IterationsExhaustedTangent {
346        iteration: max_iter,
347        z_norm: last_norm,
348    })
349}
350
351/// Adjoint piggyback solve at a converged fixed point z* = G(z*, x).
352///
353/// Iterates the adjoint fixed-point equation `λ_{k+1} = G_z^T · λ_k + z̄`
354/// using reverse-mode sweeps through the step tape. At convergence, returns
355/// `x̄ = G_x^T · λ*`.
356///
357/// Requires z* to already be computed (e.g. by the primal solver).
358/// The iteration converges when G is a contraction (‖G_z‖ < 1).
359///
360/// Returns `Ok((x_bar, iterations))` on convergence. Returns
361/// `Err(PiggybackError::AdjointDivergence)` when the adjoint norm is
362/// non-finite or `lambda_new` overflows (ratio-converging case), or
363/// `Err(PiggybackError::IterationsExhaustedAdjoint { iteration, lam_norm })`
364/// when `max_iter` is reached without satisfying `tol`.
365pub fn piggyback_adjoint_solve<F: Float>(
366    step_tape: &mut BytecodeTape<F>,
367    z_star: &[F],
368    x: &[F],
369    z_bar: &[F],
370    num_states: usize,
371    max_iter: usize,
372    tol: F,
373) -> Result<(Vec<F>, usize), PiggybackError> {
374    // Runtime arg-length check first so solve-fn users see
375    // `Err(DimensionMismatch)` in preference to a `validate_step_tape`
376    // panic when both would fire. Matches the check ordering in
377    // `piggyback_tangent_solve`.
378    let m = num_states;
379    if z_bar.len() != m {
380        return Err(PiggybackError::DimensionMismatch {
381            field: "z_bar",
382            expected: m,
383            actual: z_bar.len(),
384        });
385    }
386    validate_step_tape(step_tape, z_star, x, num_states);
387
388    // Set primal values: forward([z*, x])
389    let mut input = Vec::with_capacity(m + x.len());
390    input.extend_from_slice(z_star);
391    input.extend_from_slice(x);
392    step_tape.forward(&input);
393
394    let mut lambda = z_bar.to_vec();
395    let mut last_norm: f64 = f64::NAN;
396
397    for k in 0..max_iter {
398        // reverse_seeded(λ) returns [G_z^T · λ; G_x^T · λ] (length m+n)
399        let adj = step_tape.reverse_seeded(&lambda);
400
401        // λ_new[i] = adj[i] + z_bar[i] for i = 0..m
402        let lambda_new: Vec<F> = (0..m).map(|i| adj[i] + z_bar[i]).collect();
403        let norm = relative_delta_norm(&lambda_new, &lambda);
404        if !norm.is_finite() {
405            return Err(PiggybackError::AdjointDivergence {
406                iteration: k,
407                last_norm: norm.to_f64().unwrap_or(f64::NAN),
408            });
409        }
410        // A ratio-converging iteration with exponentially-growing `lambda`
411        // magnitudes (spectral radius of `G_z^T` ≥ 1) can produce finite
412        // `norm` while `lambda_new` is Inf/NaN. Explicit finite check
413        // catches the divergence regardless of ratio behaviour.
414        if !lambda_new.iter().all(|v| v.is_finite()) {
415            debug_assert!(
416                norm.is_finite(),
417                "AdjointDivergence componentwise path must see a finite norm"
418            );
419            return Err(PiggybackError::AdjointDivergence {
420                iteration: k,
421                last_norm: norm.to_f64().unwrap_or(f64::NAN),
422            });
423        }
424        last_norm = norm.to_f64().unwrap_or(f64::NAN);
425        if norm < tol {
426            // One extra reverse pass with converged lambda to get consistent x_bar.
427            // Without this, adj[m..] uses the pre-convergence lambda, introducing
428            // O(tol * ||G_x||) error.
429            let adj_final = step_tape.reverse_seeded(&lambda_new);
430            return Ok((adj_final[m..].to_vec(), k + 1));
431        }
432
433        lambda = lambda_new;
434    }
435
436    Err(PiggybackError::IterationsExhaustedAdjoint {
437        iteration: max_iter,
438        lam_norm: last_norm,
439    })
440}
441
442/// Interleaved forward-adjoint piggyback solve.
443///
444/// Simultaneously iterates the primal fixed-point `z_{k+1} = G(z_k, x)` and
445/// the adjoint equation `λ_{k+1} = G_z^T · λ_k + z̄`. This cuts the total
446/// iteration count from `K_primal + K_adjoint` to `max(K_primal, K_adjoint)`.
447///
448/// Returns `Ok((z_star, x_bar, iterations))` when both `z` and `λ` converge.
449/// Returns `Err(PiggybackError::PrimalDivergence)` when `z_norm` becomes
450/// non-finite or `z_new` itself contains non-finite components,
451/// `Err(PiggybackError::AdjointDivergence)` when the adjoint norm or
452/// `lambda_new` overflows, or
453/// `Err(PiggybackError::IterationsExhaustedForwardAdjoint { iteration, z_norm, lam_norm })`
454/// when `max_iter` is reached without satisfying `tol`.
455pub fn piggyback_forward_adjoint_solve<F: Float>(
456    step_tape: &mut BytecodeTape<F>,
457    z0: &[F],
458    x: &[F],
459    z_bar: &[F],
460    num_states: usize,
461    max_iter: usize,
462    tol: F,
463) -> Result<(Vec<F>, Vec<F>, usize), PiggybackError> {
464    // Runtime arg-length check first — see note on
465    // `piggyback_adjoint_solve`.
466    let m = num_states;
467    if z_bar.len() != m {
468        return Err(PiggybackError::DimensionMismatch {
469            field: "z_bar",
470            expected: m,
471            actual: z_bar.len(),
472        });
473    }
474    validate_step_tape(step_tape, z0, x, num_states);
475
476    // Pre-allocate input buffer [z, x]
477    let mut input = Vec::with_capacity(m + x.len());
478    input.extend_from_slice(z0);
479    input.extend_from_slice(x);
480
481    let mut lambda = z_bar.to_vec();
482    let mut last_z_norm: f64 = f64::NAN;
483    let mut last_lam_norm: f64 = f64::NAN;
484
485    for k in 0..max_iter {
486        // Forward pass at current z
487        step_tape.forward(&input);
488        let z_new = step_tape.output_values();
489
490        // Reverse pass with current λ
491        let adj = step_tape.reverse_seeded(&lambda);
492
493        // Primal convergence: ||z_new - z|| / (1 + ||z||)
494        let z_norm = relative_delta_norm(&z_new, &input);
495        if !z_norm.is_finite() {
496            return Err(PiggybackError::PrimalDivergence {
497                iteration: k,
498                last_norm: z_norm.to_f64().unwrap_or(f64::NAN),
499            });
500        }
501
502        // Adjoint update and convergence: λ_new = G_z^T · λ + z̄
503        let lambda_new: Vec<F> = (0..m).map(|i| adj[i] + z_bar[i]).collect();
504        let lam_norm = relative_delta_norm(&lambda_new, &lambda);
505        if !lam_norm.is_finite() {
506            return Err(PiggybackError::AdjointDivergence {
507                iteration: k,
508                last_norm: lam_norm.to_f64().unwrap_or(f64::NAN),
509            });
510        }
511        // Same divergence case as the standalone solvers: a ratio-converging
512        // iteration with exponentially-growing lambda magnitudes can produce
513        // finite `lam_norm` while `lambda_new` itself is Inf/NaN.
514        if !lambda_new.iter().all(|v| v.is_finite()) {
515            debug_assert!(
516                lam_norm.is_finite(),
517                "AdjointDivergence componentwise path must see a finite lam_norm"
518            );
519            return Err(PiggybackError::AdjointDivergence {
520                iteration: k,
521                last_norm: lam_norm.to_f64().unwrap_or(f64::NAN),
522            });
523        }
524        // Defense-in-depth: a non-finite `z_new[i]` would typically have
525        // already shown up as `!z_norm.is_finite()` above (the delta/sq
526        // loops touch every index), but guard the componentwise case
527        // explicitly so a future refactor of the norm computation can't
528        // silently lose primal-divergence detection.
529        if !z_new.iter().all(|v| v.is_finite()) {
530            debug_assert!(
531                z_norm.is_finite(),
532                "PrimalDivergence componentwise path must see a finite z_norm"
533            );
534            return Err(PiggybackError::PrimalDivergence {
535                iteration: k,
536                last_norm: z_norm.to_f64().unwrap_or(f64::NAN),
537            });
538        }
539
540        last_z_norm = z_norm.to_f64().unwrap_or(f64::NAN);
541        last_lam_norm = lam_norm.to_f64().unwrap_or(f64::NAN);
542
543        if z_norm < tol && lam_norm < tol {
544            // One extra reverse pass with converged lambda_new to get consistent x_bar,
545            // matching the pattern in piggyback_adjoint_solve.
546            input[..m].copy_from_slice(&z_new[..m]);
547            step_tape.forward(&input);
548            let adj_final = step_tape.reverse_seeded(&lambda_new);
549            return Ok((z_new, adj_final[m..].to_vec(), k + 1));
550        }
551
552        // Update z in the input buffer
553        input[..m].copy_from_slice(&z_new[..m]);
554        lambda = lambda_new;
555    }
556
557    Err(PiggybackError::IterationsExhaustedForwardAdjoint {
558        iteration: max_iter,
559        z_norm: last_z_norm,
560        lam_norm: last_lam_norm,
561    })
562}