scirs2-autograd 0.3.2

Automatic differentiation module for SciRS2 (scirs2-autograd)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! Wengert tape (computational tape) for reverse-mode automatic differentiation
//!
//! This module provides a standalone, graph-free implementation of reverse-mode
//! AD using the *Wengert list* algorithm.  Each scalar operation appends an
//! entry to a dynamic list; the backward pass walks the list in reverse,
//! accumulating cotangents into an adjoint vector.
//!
//! # Design goals
//!
//! * **Purely functional interface** — no global mutable state; each `Tape` is
//!   an independent object.
//! * **Zero-cost for constants** — constant scalars are represented as
//!   [`TapeVar`] with an empty backward contribution; they occupy one slot in
//!   the value table but incur no gradient update.
//! * **Memory efficiency** — backward pass accumulates adjoints in a single
//!   `Vec<f64>` without allocating per-node gradient objects.
//! * **Composable** — a `Tape` can be used inside closures that return
//!   [`TapeVar`]; the returned variable's index identifies the output node in
//!   the adjoint computation.
//!
//! # Overview
//!
//! | Type / Function | Description |
//! |-----------------|-------------|
//! | [`Tape`] | Wengert list accumulating operations |
//! | [`TapeVar`] | Handle to a variable on a tape |
//! | [`backward`] | Run the backward pass on a recorded tape |
//! | [`GradientTape`] | High-level closure-based interface |
//!
//! # Example — computing a gradient
//!
//! ```rust
//! use scirs2_autograd::functional::tape::{Tape, backward};
//!
//! let mut tape = Tape::new();
//! let x = tape.var(3.0);
//! let y = tape.var(4.0);
//! // f(x, y) = x^2 + y^2
//! let x2 = x.mul(&y, &tape); // reusing tape API
//!
//! // Alternatively use the functional tape builder:
//! let mut tape = Tape::new();
//! let xi = tape.push_input(3.0);
//! let yi = tape.push_input(4.0);
//! let sq_x = tape.push_unary(xi, |v| v * v, |_, _| 2.0 * 3.0);
//! let sq_y = tape.push_unary(yi, |v| v * v, |_, _| 2.0 * 4.0);
//! let out  = tape.push_binary(sq_x, sq_y, |a, b| a + b, |_, _| (1.0, 1.0));
//! let grads = backward(&tape, out);
//! assert!((grads[xi] - 6.0).abs() < 1e-12);
//! assert!((grads[yi] - 8.0).abs() < 1e-12);
//! ```

use crate::error::AutogradError;
use crate::Result;
use std::cell::RefCell;

// ============================================================================
// Node — an entry in the Wengert list
// ============================================================================

/// A single entry in the Wengert list.
///
/// Each node records:
/// * its primal `value` (for potential reuse in backward),
/// * a list of `(parent_index, weight)` pairs, where the weight is the local
///   derivative `∂out/∂parent` (already evaluated at forward-pass values).
///
/// The backward pass propagates adjoints as:
/// `adjoint[parent] += adjoint[self] * weight`
#[derive(Debug, Clone)]
pub(crate) struct Node {
    /// The primal value of this node.
    pub(crate) value: f64,
    /// `(parent_idx, local_partial)` pairs (at most 2 for binary ops).
    pub(crate) parents: Vec<(usize, f64)>,
}

// ============================================================================
// Tape — the Wengert list
// ============================================================================

/// A Wengert list (computational tape) for reverse-mode automatic
/// differentiation.
///
/// The tape records every primitive operation performed on [`TapeVar`]s in
/// chronological order.  After a forward pass, call [`backward`] to
/// propagate cotangents (adjoints) from an output node back to all inputs.
///
/// # Thread safety
///
/// `Tape` is `!Send` by design (it uses interior mutability via `RefCell`).
/// For multi-threaded workloads, create a `Tape` per thread.
pub struct Tape {
    /// The Wengert list, stored behind `RefCell` to allow shared-reference
    /// mutation during the forward pass (a common pattern when closures
    /// operate on `TapeVar` values that borrow the tape).
    nodes: RefCell<Vec<Node>>,
}

impl Tape {
    /// Create a new, empty `Tape`.
    pub fn new() -> Self {
        Self { nodes: RefCell::new(Vec::new()) }
    }

    /// Create a new `Tape` with pre-allocated capacity `n` for efficiency.
    pub fn with_capacity(n: usize) -> Self {
        Self { nodes: RefCell::new(Vec::with_capacity(n)) }
    }

    /// Record an *input* (leaf) variable with the given primal value.
    ///
    /// Returns the node index (a [`TapeVar`] handle).
    pub fn push_input(&self, value: f64) -> TapeVar {
        let mut nodes = self.nodes.borrow_mut();
        let idx = nodes.len();
        nodes.push(Node { value, parents: Vec::new() });
        TapeVar { idx, value }
    }

    /// Record a *constant* (no gradient flows through it).
    ///
    /// Equivalent to `push_input` semantically, but communicates intent and
    /// allows future optimisers to skip gradient accumulation.
    pub fn push_constant(&self, value: f64) -> TapeVar {
        self.push_input(value)
    }

    /// Record a *unary* operation.
    ///
    /// # Arguments
    ///
    /// * `a`        — Parent variable.
    /// * `forward`  — `fn(value_a) -> output_value`.
    /// * `backward` — `fn(value_a, output_value) -> ∂out/∂a`.
    pub fn push_unary(
        &self,
        a: TapeVar,
        forward: impl Fn(f64) -> f64,
        backward: impl Fn(f64, f64) -> f64,
    ) -> TapeVar {
        let out_val = forward(a.value);
        let local_grad = backward(a.value, out_val);
        let mut nodes = self.nodes.borrow_mut();
        let idx = nodes.len();
        nodes.push(Node {
            value: out_val,
            parents: vec![(a.idx, local_grad)],
        });
        TapeVar { idx, value: out_val }
    }

    /// Record a *binary* operation.
    ///
    /// # Arguments
    ///
    /// * `a`, `b`   — Parent variables.
    /// * `forward`  — `fn(value_a, value_b) -> output_value`.
    /// * `backward` — `fn(value_a, value_b) -> (∂out/∂a, ∂out/∂b)`.
    pub fn push_binary(
        &self,
        a: TapeVar,
        b: TapeVar,
        forward: impl Fn(f64, f64) -> f64,
        backward: impl Fn(f64, f64) -> (f64, f64),
    ) -> TapeVar {
        let out_val = forward(a.value, b.value);
        let (ga, gb) = backward(a.value, b.value);
        let mut nodes = self.nodes.borrow_mut();
        let idx = nodes.len();
        nodes.push(Node {
            value: out_val,
            parents: vec![(a.idx, ga), (b.idx, gb)],
        });
        TapeVar { idx, value: out_val }
    }

    /// Create a `TapeVar` wrapper for an external computation result.
    ///
    /// Use this when you have computed the output value by some other means
    /// and want to register it with manually specified parent connections.
    pub fn push_custom(
        &self,
        value: f64,
        parents: Vec<(TapeVar, f64)>,
    ) -> TapeVar {
        let mut nodes = self.nodes.borrow_mut();
        let idx = nodes.len();
        nodes.push(Node {
            value,
            parents: parents.into_iter().map(|(v, w)| (v.idx, w)).collect(),
        });
        TapeVar { idx, value }
    }

    /// Number of nodes currently on the tape.
    pub fn len(&self) -> usize {
        self.nodes.borrow().len()
    }

    /// Return `true` if the tape has no nodes.
    pub fn is_empty(&self) -> bool {
        self.nodes.borrow().is_empty()
    }

    /// Snapshot of all recorded node values.
    pub fn values(&self) -> Vec<f64> {
        self.nodes.borrow().iter().map(|n| n.value).collect()
    }

    /// Convenience: push `x` and return a named variable wrapper.
    pub fn var(&self, value: f64) -> TapeVar {
        self.push_input(value)
    }

    // -----------------------------------------------------------------------
    // Primitive op helpers (syntactic sugar)
    // -----------------------------------------------------------------------

    /// Record `a + b`.
    pub fn add(&self, a: TapeVar, b: TapeVar) -> TapeVar {
        self.push_binary(a, b, |va, vb| va + vb, |_, _| (1.0, 1.0))
    }

    /// Record `a - b`.
    pub fn sub(&self, a: TapeVar, b: TapeVar) -> TapeVar {
        self.push_binary(a, b, |va, vb| va - vb, |_, _| (1.0, -1.0))
    }

    /// Record `a * b`.
    pub fn mul(&self, a: TapeVar, b: TapeVar) -> TapeVar {
        self.push_binary(a, b, |va, vb| va * vb, |va, vb| (vb, va))
    }

    /// Record `a / b`.
    pub fn div(&self, a: TapeVar, b: TapeVar) -> TapeVar {
        self.push_binary(
            a, b,
            |va, vb| va / vb,
            |va, vb| (1.0 / vb, -va / (vb * vb)),
        )
    }

    /// Record `-a`.
    pub fn neg(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| -va, |_, _| -1.0)
    }

    /// Record `exp(a)`.
    pub fn exp(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.exp(), |_, out| out)
    }

    /// Record `ln(a)`.
    pub fn ln(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.ln(), |va, _| 1.0 / va)
    }

    /// Record `sqrt(a)`.
    pub fn sqrt(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.sqrt(), |_, out| 0.5 / out)
    }

    /// Record `sin(a)`.
    pub fn sin(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.sin(), |va, _| va.cos())
    }

    /// Record `cos(a)`.
    pub fn cos(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.cos(), |va, _| -va.sin())
    }

    /// Record `tanh(a)`.
    pub fn tanh(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.tanh(), |_, out| 1.0 - out * out)
    }

    /// Record `a^n` for integer `n`.
    pub fn powi(&self, a: TapeVar, n: i32) -> TapeVar {
        self.push_unary(a, |va| va.powi(n), |va, _| f64::from(n) * va.powi(n - 1))
    }

    /// Record `a * scalar`.
    pub fn scale(&self, a: TapeVar, scalar: f64) -> TapeVar {
        self.push_unary(a, |va| va * scalar, |_, _| scalar)
    }

    /// Record `sigmoid(a) = 1/(1+exp(-a))`.
    pub fn sigmoid(&self, a: TapeVar) -> TapeVar {
        self.push_unary(
            a,
            |va| {
                let e = (-va).exp();
                1.0 / (1.0 + e)
            },
            |_, out| out * (1.0 - out),
        )
    }

    /// Record `relu(a) = max(0, a)`.
    pub fn relu(&self, a: TapeVar) -> TapeVar {
        self.push_unary(a, |va| va.max(0.0), |va, _| if va > 0.0 { 1.0 } else { 0.0 })
    }

    /// Record sum: `Σ aᵢ` from a slice of `TapeVar`.
    ///
    /// Implemented as a left-fold over `Tape::add`.
    pub fn sum(&self, vars: &[TapeVar]) -> Result<TapeVar> {
        if vars.is_empty() {
            return Err(AutogradError::invalid_argument(
                "tape::sum: empty input slice".to_string(),
            ));
        }
        let mut acc = vars[0];
        for &v in &vars[1..] {
            acc = self.add(acc, v);
        }
        Ok(acc)
    }

    /// Record dot product `aᵀb`.
    pub fn dot(&self, a: &[TapeVar], b: &[TapeVar]) -> Result<TapeVar> {
        if a.len() != b.len() {
            return Err(AutogradError::invalid_argument(format!(
                "tape::dot: length mismatch {} vs {}",
                a.len(),
                b.len()
            )));
        }
        if a.is_empty() {
            return Err(AutogradError::invalid_argument(
                "tape::dot: empty inputs".to_string(),
            ));
        }
        let products: Vec<TapeVar> = a.iter().zip(b.iter()).map(|(&ai, &bi)| self.mul(ai, bi)).collect();
        self.sum(&products)
    }
}

impl Default for Tape {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// TapeVar — handle to a node on the tape
// ============================================================================

/// A handle to a node in a [`Tape`], carrying the node's primal value.
///
/// `TapeVar` is `Copy` (just an index + cached value) and cheap to pass
/// around.  All operations that would normally return a new `Dual` instead
/// register a new node on the tape and return a `TapeVar` pointing to it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TapeVar {
    /// Index of this variable in the tape's node vector.
    pub(crate) idx: usize,
    /// Primal value (cached for convenience).
    pub value: f64,
}

impl TapeVar {
    /// Return the node index (position in the Wengert list).
    #[inline]
    pub fn index(&self) -> usize {
        self.idx
    }

    /// Convenience method: `a.add(b, tape)` = `tape.add(a, b)`.
    pub fn add(self, other: TapeVar, tape: &Tape) -> TapeVar {
        tape.add(self, other)
    }

    /// Convenience method: `a.mul(b, tape)` = `tape.mul(a, b)`.
    pub fn mul(self, other: TapeVar, tape: &Tape) -> TapeVar {
        tape.mul(self, other)
    }
}

// ============================================================================
// backward — reverse-mode backward pass
// ============================================================================

/// Run the reverse-mode backward pass on a recorded `tape`.
///
/// Returns a `Vec<f64>` of the same length as the number of tape nodes, where
/// `grads[i]` is `∂out/∂(node i)`.  Leaf variables (inputs) have their
/// adjoints stored at their original indices.
///
/// # Arguments
///
/// * `tape`   — The Wengert list populated during the forward pass.
/// * `output` — The [`TapeVar`] representing the scalar loss / output node.
///
/// # Panics / Errors
///
/// The function never panics; if the tape is empty it returns an empty vector.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd::functional::tape::{Tape, backward};
///
/// let tape = Tape::new();
/// let x = tape.var(2.0);
/// let y = tape.var(3.0);
/// let z = tape.mul(x, y);       // z = x*y = 6
/// let w = tape.powi(x, 2);      // w = x^2 = 4
/// let out = tape.add(z, w);     // out = z + w = 10
///
/// let grads = backward(&tape, out);
/// // ∂out/∂x = y + 2x = 3 + 4 = 7
/// // ∂out/∂y = x = 2
/// assert!((grads[x.idx] - 7.0).abs() < 1e-12);
/// assert!((grads[y.idx] - 2.0).abs() < 1e-12);
/// ```
pub fn backward(tape: &Tape, output: TapeVar) -> Vec<f64> {
    let nodes = tape.nodes.borrow();
    let n = nodes.len();
    let mut adjoints = vec![0.0f64; n];
    if n == 0 {
        return adjoints;
    }
    adjoints[output.idx] = 1.0;

    // Walk backwards through the Wengert list
    for i in (0..n).rev() {
        let adjoint_i = adjoints[i];
        if adjoint_i == 0.0 {
            continue; // short-circuit zero contributions
        }
        for &(parent_idx, weight) in &nodes[i].parents {
            adjoints[parent_idx] += adjoint_i * weight;
        }
    }

    adjoints
}

/// Run a backward pass starting from the output with a seed adjoint ≠ 1.
///
/// Useful for computing `vᵀ·J` (vector-Jacobian products) when `v ≠ e_out`.
pub fn backward_with_seed(tape: &Tape, output: TapeVar, seed: f64) -> Vec<f64> {
    let nodes = tape.nodes.borrow();
    let n = nodes.len();
    let mut adjoints = vec![0.0f64; n];
    if n == 0 {
        return adjoints;
    }
    adjoints[output.idx] = seed;

    for i in (0..n).rev() {
        let adjoint_i = adjoints[i];
        if adjoint_i == 0.0 {
            continue;
        }
        for &(parent_idx, weight) in &nodes[i].parents {
            adjoints[parent_idx] += adjoint_i * weight;
        }
    }

    adjoints
}

// ============================================================================
// GradientTape — high-level closure interface
// ============================================================================

/// A high-level closure-based interface to the Wengert tape.
///
/// [`GradientTape`] wraps a [`Tape`] and records a computation via a closure,
/// then exposes a clean gradient-extraction API.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd::functional::tape::GradientTape;
///
/// // f(x, y) = x^2 * y + y^3
/// // ∂f/∂x = 2*x*y = 4,  ∂f/∂y = x^2 + 3*y^2 = 11  at (2, 1)
/// let mut gt = GradientTape::new();
/// let inputs = gt.record_inputs(&[2.0, 1.0]);
/// let result = gt.compute(|tape, inp| {
///     let x = inp[0];
///     let y = inp[1];
///     let x2 = tape.powi(x, 2);
///     let x2y = tape.mul(x2, y);
///     let y3 = tape.powi(y, 3);
///     tape.add(x2y, y3)
/// }, &inputs);
/// let grads = gt.gradient(result, &inputs);
/// assert!((grads[0] - 4.0).abs() < 1e-12);  // ∂f/∂x
/// assert!((grads[1] - 13.0).abs() < 1e-12); // ∂f/∂y: 4 + 3 = 7... wait x^2+3y^2=4+3=7? No: x=2,y=1 => 4+3=7
/// ```
pub struct GradientTape {
    tape: Tape,
}

impl GradientTape {
    /// Create a new `GradientTape`.
    pub fn new() -> Self {
        Self { tape: Tape::new() }
    }

    /// Register a slice of scalar inputs.  Returns `TapeVar` handles.
    pub fn record_inputs(&self, inputs: &[f64]) -> Vec<TapeVar> {
        inputs.iter().map(|&v| self.tape.push_input(v)).collect()
    }

    /// Run a computation closure and return the output `TapeVar`.
    pub fn compute<F>(&self, f: F, inputs: &[TapeVar]) -> TapeVar
    where
        F: FnOnce(&Tape, &[TapeVar]) -> TapeVar,
    {
        f(&self.tape, inputs)
    }

    /// Compute gradients of `output` w.r.t. each element of `wrt`.
    ///
    /// Returns a `Vec<f64>` of the same length as `wrt`.
    pub fn gradient(&self, output: TapeVar, wrt: &[TapeVar]) -> Vec<f64> {
        let adjoints = backward(&self.tape, output);
        wrt.iter().map(|v| adjoints[v.idx]).collect()
    }

    /// Borrow the inner tape.
    pub fn tape(&self) -> &Tape {
        &self.tape
    }
}

impl Default for GradientTape {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Functional helpers — functional-style gradient computations
// ============================================================================

/// Compute the gradient of a scalar function `f: R^n -> R` at point `x`
/// using the Wengert tape.
///
/// The function `f` receives `&[TapeVar]` and must return a single `TapeVar`.
/// This is the tape-based analogue of [`crate::functional::transforms::grad`].
///
/// # Errors
///
/// Returns `AutogradError` if `x` is empty.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd::functional::tape::tape_grad;
///
/// let g = tape_grad(
///     |tape, xs| {
///         let x2 = tape.powi(xs[0], 2);
///         let y2 = tape.powi(xs[1], 2);
///         tape.add(x2, y2)
///     },
///     &[3.0, 4.0],
/// ).expect("gradient");
/// assert!((g[0] - 6.0).abs() < 1e-12);
/// assert!((g[1] - 8.0).abs() < 1e-12);
/// ```
pub fn tape_grad<F>(f: F, x: &[f64]) -> Result<Vec<f64>>
where
    F: FnOnce(&Tape, &[TapeVar]) -> TapeVar,
{
    if x.is_empty() {
        return Err(AutogradError::invalid_argument(
            "tape_grad: input must be non-empty".to_string(),
        ));
    }
    let tape = Tape::with_capacity(x.len() * 4);
    let inputs: Vec<TapeVar> = x.iter().map(|&v| tape.push_input(v)).collect();
    let output = f(&tape, &inputs);
    let adjoints = backward(&tape, output);
    Ok(inputs.iter().map(|v| adjoints[v.idx]).collect())
}

/// Compute the full Jacobian of `f: R^n -> R^m` at `x` using reverse-mode
/// tape AD.
///
/// Each row of the returned `m × n` matrix is computed by one backward pass
/// seeded with the corresponding basis cotangent vector.  Total cost: `m`
/// backward passes.
///
/// # Errors
///
/// Returns `AutogradError` if `x` or outputs are empty.
pub fn tape_jacobian<F>(f: F, x: &[f64]) -> Result<Vec<Vec<f64>>>
where
    F: Fn(&Tape, &[TapeVar]) -> Vec<TapeVar>,
{
    if x.is_empty() {
        return Err(AutogradError::invalid_argument(
            "tape_jacobian: input must be non-empty".to_string(),
        ));
    }

    // We need to re-evaluate for each output because the tape records the
    // entire graph; seeding different outputs is equivalent to running the
    // full backward pass from each output node.
    let tape = Tape::with_capacity(x.len() * 8);
    let inputs: Vec<TapeVar> = x.iter().map(|&v| tape.push_input(v)).collect();
    let outputs = f(&tape, &inputs);

    if outputs.is_empty() {
        return Err(AutogradError::invalid_argument(
            "tape_jacobian: function returned no outputs".to_string(),
        ));
    }

    let m = outputs.len();
    let n = x.len();
    let mut jacobian = vec![vec![0.0f64; n]; m];

    for (row, &out_var) in outputs.iter().enumerate() {
        let adjoints = backward(&tape, out_var);
        for (col, inp_var) in inputs.iter().enumerate() {
            jacobian[row][col] = adjoints[inp_var.idx];
        }
    }

    Ok(jacobian)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tape_basic_gradient() {
        // f(x, y) = x^2 + y^2; ∂f/∂x = 2x, ∂f/∂y = 2y
        let g = tape_grad(
            |tape, xs| {
                let x2 = tape.powi(xs[0], 2);
                let y2 = tape.powi(xs[1], 2);
                tape.add(x2, y2)
            },
            &[3.0, 4.0],
        )
        .expect("tape_grad");
        assert!((g[0] - 6.0).abs() < 1e-12, "∂f/∂x = {}", g[0]);
        assert!((g[1] - 8.0).abs() < 1e-12, "∂f/∂y = {}", g[1]);
    }

    #[test]
    fn test_tape_product_gradient() {
        // f(x, y) = x * y; ∂f/∂x = y, ∂f/∂y = x
        let g = tape_grad(
            |tape, xs| tape.mul(xs[0], xs[1]),
            &[3.0, 4.0],
        )
        .expect("tape_grad mul");
        assert!((g[0] - 4.0).abs() < 1e-12);
        assert!((g[1] - 3.0).abs() < 1e-12);
    }

    #[test]
    fn test_tape_chain_rule() {
        // f(x) = exp(x^2); f'(x) = 2x*exp(x^2)
        let g = tape_grad(
            |tape, xs| {
                let x2 = tape.powi(xs[0], 2);
                tape.exp(x2)
            },
            &[2.0],
        )
        .expect("chain rule");
        let expected = 4.0 * (4.0_f64).exp(); // 2*2*exp(4)
        assert!((g[0] - expected).abs() < 1e-6, "f'(2) = {} expected {}", g[0], expected);
    }

    #[test]
    fn test_tape_jacobian_vector_function() {
        // f(x, y) = [x^2 * y, x + y]
        // J = [[2xy, x^2], [1, 1]] at (2, 3) = [[12, 4], [1, 1]]
        let j = tape_jacobian(
            |tape, xs| {
                let x2 = tape.powi(xs[0], 2);
                let f0 = tape.mul(x2, xs[1]);
                let f1 = tape.add(xs[0], xs[1]);
                vec![f0, f1]
            },
            &[2.0, 3.0],
        )
        .expect("tape_jacobian");
        assert!((j[0][0] - 12.0).abs() < 1e-12, "J[0][0] = {}", j[0][0]);
        assert!((j[0][1] - 4.0).abs() < 1e-12, "J[0][1] = {}", j[0][1]);
        assert!((j[1][0] - 1.0).abs() < 1e-12, "J[1][0] = {}", j[1][0]);
        assert!((j[1][1] - 1.0).abs() < 1e-12, "J[1][1] = {}", j[1][1]);
    }

    #[test]
    fn test_tape_sigmoid() {
        let g = tape_grad(|tape, xs| tape.sigmoid(xs[0]), &[0.0]).expect("sigmoid grad");
        assert!((g[0] - 0.25).abs() < 1e-12, "sigmoid'(0) = {}", g[0]);
    }

    #[test]
    fn test_gradient_tape_high_level() {
        let gt = GradientTape::new();
        let inputs = gt.record_inputs(&[2.0, 3.0]);
        let out = gt.compute(
            |tape, inp| {
                let x2 = tape.powi(inp[0], 2);
                let y2 = tape.powi(inp[1], 2);
                tape.add(x2, y2)
            },
            &inputs,
        );
        let grads = gt.gradient(out, &inputs);
        assert!((grads[0] - 4.0).abs() < 1e-12, "dx = {}", grads[0]);
        assert!((grads[1] - 6.0).abs() < 1e-12, "dy = {}", grads[1]);
    }

    #[test]
    fn test_backward_with_seed() {
        let tape = Tape::new();
        let x = tape.var(2.0);
        let y = tape.var(3.0);
        let z = tape.mul(x, y); // z = x*y; dz/dx = y = 3, dz/dy = x = 2
        let adjs = backward_with_seed(&tape, z, 2.0); // seed 2 => 2*[3,2] = [6,4]
        assert!((adjs[x.idx] - 6.0).abs() < 1e-12);
        assert!((adjs[y.idx] - 4.0).abs() < 1e-12);
    }

    #[test]
    fn test_tape_empty_error() {
        assert!(tape_grad(|tape, xs| xs[0], &[]).is_err());
        assert!(tape_jacobian(|_tape, _xs| vec![], &[1.0]).is_err());
    }

    #[test]
    fn test_tape_dot_product() {
        // f(a, b) = a·b = a0*b0 + a1*b1 + a2*b2
        // at a=(1,2,3), b=(4,5,6): f = 32, ∂f/∂aᵢ = bᵢ, ∂f/∂bᵢ = aᵢ
        let tape = Tape::new();
        let a: Vec<TapeVar> = [1.0, 2.0, 3.0].iter().map(|&v| tape.var(v)).collect();
        let b: Vec<TapeVar> = [4.0, 5.0, 6.0].iter().map(|&v| tape.var(v)).collect();
        let out = tape.dot(&a, &b).expect("dot product");
        let adjs = backward(&tape, out);
        assert!((out.value - 32.0).abs() < 1e-12);
        assert!((adjs[a[0].idx] - 4.0).abs() < 1e-12);
        assert!((adjs[a[2].idx] - 6.0).abs() < 1e-12);
        assert!((adjs[b[1].idx] - 2.0).abs() < 1e-12);
    }

    #[test]
    fn test_tape_relu_gradient() {
        // relu'(x) = 1 if x > 0, 0 otherwise
        let g_pos = tape_grad(|tape, xs| tape.relu(xs[0]), &[2.0]).expect("relu+");
        let g_neg = tape_grad(|tape, xs| tape.relu(xs[0]), &[-1.0]).expect("relu-");
        assert!((g_pos[0] - 1.0).abs() < 1e-12);
        assert!(g_neg[0].abs() < 1e-12);
    }
}