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
//! Extended higher-order derivative utilities
//!
//! This module adds standalone convenience functions and advanced higher-order
//! derivative computations that complement the core `higher_order` module:
//!
//! - [`hessian_diagonal`] — Diagonal of the Hessian (n HVPs with unit vectors)
//! - [`laplacian`] — Trace of the Hessian (sum of diagonal)
//! - [`fisher_information`] — Fisher information matrix from a log-probability
//! - [`gauss_newton_product`] — Gauss-Newton matrix-vector product
//! - [`efficient_second_order_grad`] — Memory-efficient second-order gradient

use crate::error::AutogradError;
use crate::forward_mode::DualNumber;
use crate::tensor::Tensor;
use crate::{Context, Float, Result};
use num::Float as NumFloat;
use scirs2_core::ndarray::{Array1, Array2};
use std::fmt;

// ---------------------------------------------------------------------------
// Hessian diagonal (standalone)
// ---------------------------------------------------------------------------

/// Compute the diagonal of the Hessian of a scalar function using the autograd graph.
///
/// For a function f: R^n -> R, returns [∂²f/∂x₀², ∂²f/∂x₁², ..., ∂²f/∂xₙ₋₁²].
///
/// This uses n Hessian-vector products with unit vectors e_i, extracting the
/// i-th element of each result to form the diagonal.
///
/// # Arguments
/// * `f` - Scalar output tensor
/// * `x` - Input tensor of shape `[n]`
/// * `n` - Number of parameters (must match x dimension)
/// * `ctx` - Autograd context
///
/// # Returns
/// Tensor of shape `[n]` containing the diagonal of the Hessian.
///
/// # Complexity
/// O(n) Hessian-vector products, each O(graph_size).
pub fn hessian_diagonal<'graph, T: Float>(
    f: &Tensor<'graph, T>,
    x: &Tensor<'graph, T>,
    n: usize,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    validate_scalar(f)?;

    if n == 0 {
        return Err(AutogradError::shape_error(
            "Dimension n must be positive".to_string(),
        ));
    }

    let mut diag_elements = Vec::with_capacity(n);

    for i in 0..n {
        let mut e_i_vec = vec![T::zero(); n];
        e_i_vec[i] = T::one();
        let e_i_arr = scirs2_core::ndarray::Array1::from(e_i_vec).into_dyn();
        let e_i = crate::tensor_ops::convert_to_tensor(e_i_arr, ctx);

        let hvp_i = super::hessian_vector_product(f, x, &e_i, ctx)?;
        let hvp_i_flat = crate::tensor_ops::flatten(hvp_i);
        let diag_elem = crate::tensor_ops::slice(hvp_i_flat, [i as isize], [(i + 1) as isize]);
        diag_elements.push(diag_elem);
    }

    Ok(crate::tensor_ops::linear_algebra::concat(&diag_elements, 0))
}

// ---------------------------------------------------------------------------
// Laplacian
// ---------------------------------------------------------------------------

/// Compute the Laplacian of a scalar function.
///
/// The Laplacian is defined as the trace of the Hessian:
///   Δf = Σᵢ ∂²f/∂xᵢ²
///
/// This is equivalent to `sum(hessian_diagonal(f, x, n, ctx))`.
///
/// # Arguments
/// * `f` - Scalar output tensor
/// * `x` - Input tensor of shape `[n]`
/// * `n` - Number of parameters
/// * `ctx` - Autograd context
///
/// # Returns
/// A scalar tensor containing the Laplacian value.
///
/// # Applications
/// - Laplacian regularization in machine learning
/// - Heat equation discretization
/// - Curvature estimation
pub fn laplacian<'graph, T: Float>(
    f: &Tensor<'graph, T>,
    x: &Tensor<'graph, T>,
    n: usize,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    let diag = hessian_diagonal(f, x, n, ctx)?;
    Ok(crate::tensor_ops::reduction::sum_all(diag))
}

// ---------------------------------------------------------------------------
// Fisher information matrix
// ---------------------------------------------------------------------------

/// Compute the Fisher information matrix of a log-probability function.
///
/// The Fisher information matrix is defined as:
///   F(θ) = E[∇log p(x|θ) · (∇log p(x|θ))^T]
///
/// For a single observation, this simplifies to the outer product of the
/// score vector (gradient of log-likelihood) with itself:
///   F_ij(θ) = (∂log p / ∂θ_i)(∂log p / ∂θ_j)
///
/// This function computes the **empirical** Fisher information from the
/// current gradient (single-sample estimate).
///
/// # Arguments
/// * `log_prob` - Scalar tensor representing log p(x|θ) for current sample
/// * `params` - Parameter tensor θ of shape `[n]`
/// * `n` - Number of parameters
/// * `ctx` - Autograd context
///
/// # Returns
/// Tensor of shape `[n*n]` (flattened n×n Fisher information matrix).
///
/// # Notes
/// - For the true Fisher, average over multiple samples.
/// - The Fisher information matrix is always positive semi-definite.
/// - This is the **empirical** Fisher (uses gradient at current sample),
///   not the **exact** Fisher (which requires integration over p(x|θ)).
pub fn fisher_information<'graph, T: Float>(
    log_prob: &Tensor<'graph, T>,
    params: &Tensor<'graph, T>,
    n: usize,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    validate_scalar(log_prob)?;

    if n == 0 {
        return Err(AutogradError::shape_error(
            "Number of parameters must be positive".to_string(),
        ));
    }

    // Compute score vector: ∇ log p(x|θ)
    let score = crate::tensor_ops::grad(&[*log_prob], &[*params])[0];
    let score_flat = crate::tensor_ops::flatten(score);

    // Compute outer product: score ⊗ score = F
    // F_ij = score_i * score_j
    let mut fisher_rows = Vec::with_capacity(n);

    for i in 0..n {
        let score_i = crate::tensor_ops::slice(score_flat, [i as isize], [(i + 1) as isize]);
        // score_i * score (element-wise) gives the i-th row
        let row = score_i * score_flat;
        fisher_rows.push(row);
    }

    Ok(crate::tensor_ops::linear_algebra::concat(&fisher_rows, 0))
}

/// Compute Fisher information diagonal (more efficient than full matrix).
///
/// Returns [score_0², score_1², ..., score_{n-1}²] where score = ∇ log p(x|θ).
///
/// # Arguments
/// * `log_prob` - Scalar log-probability tensor
/// * `params` - Parameter tensor
/// * `ctx` - Autograd context
pub fn fisher_diagonal<'graph, T: Float>(
    log_prob: &Tensor<'graph, T>,
    params: &Tensor<'graph, T>,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    validate_scalar(log_prob)?;

    let score = crate::tensor_ops::grad(&[*log_prob], &[*params])[0];
    // Diagonal = score^2 (element-wise)
    Ok(score * score)
}

// ---------------------------------------------------------------------------
// Gauss-Newton matrix-vector product
// ---------------------------------------------------------------------------

/// Compute Gauss-Newton matrix-vector product.
///
/// The Gauss-Newton matrix for a least-squares problem min ||r(x)||² is:
///   G = J^T J
/// where J is the Jacobian of the residual r.
///
/// This computes G * v = J^T (J * v) using two passes: one JVP and one VJP,
/// without ever forming G explicitly.
///
/// # Arguments
/// * `residual` - Residual tensor r(x) of shape `[m]`
/// * `x` - Parameter tensor of shape `[n]`
/// * `v` - Vector to multiply with G, shape `[n]`
/// * `m` - Number of residuals
/// * `ctx` - Autograd context
///
/// # Returns
/// G * v as a tensor of shape `[n]`.
pub fn gauss_newton_product<'graph, T: Float>(
    residual: &Tensor<'graph, T>,
    x: &Tensor<'graph, T>,
    v: &Tensor<'graph, T>,
    m: usize,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    // Step 1: Compute J * v (JVP)
    // J*v = d/dε r(x + ε*v)|_{ε=0}
    // We approximate this using the gradient: sum(∇r * v)
    let r_flat = crate::tensor_ops::flatten(*residual);

    let mut jv_elements = Vec::with_capacity(m);
    for i in 0..m {
        let r_i = crate::tensor_ops::slice(r_flat, [i as isize], [(i + 1) as isize]);
        let grad_ri = crate::tensor_ops::grad(&[r_i], &[*x])[0];
        let jv_i = crate::tensor_ops::reduction::sum_all(grad_ri * *v);
        jv_elements.push(jv_i);
    }

    let jv = crate::tensor_ops::linear_algebra::concat(&jv_elements, 0);

    // Step 2: Compute J^T * (J * v) (VJP)
    // This is grad(jv^T * r, x) but we need to be careful about how we
    // compute this. Instead, compute: sum_i (jv_i * grad(r_i, x))
    let jv_flat = crate::tensor_ops::flatten(jv);

    // Compute J^T * jv = grad(jv . r, x)
    let weighted = crate::tensor_ops::reduction::sum_all(jv_flat * r_flat);
    let gn_product = crate::tensor_ops::grad(&[weighted], &[*x])[0];

    Ok(gn_product)
}

// ---------------------------------------------------------------------------
// Efficient second-order gradient
// ---------------------------------------------------------------------------

/// Compute second-order gradient with gradient checkpointing.
///
/// This computes d²f/dx² (as a diagonal vector) but uses less memory than
/// the naive approach by recomputing intermediate values during the backward
/// pass instead of storing them.
///
/// # Arguments
/// * `f` - Scalar output tensor
/// * `x` - Input tensor
/// * `n` - Dimension of x
/// * `ctx` - Autograd context
///
/// # Returns
/// The diagonal of the Hessian, same as `hessian_diagonal` but potentially
/// more memory-efficient for deep computation graphs.
pub fn efficient_second_order_grad<'graph, T: Float>(
    f: &Tensor<'graph, T>,
    x: &Tensor<'graph, T>,
    n: usize,
    ctx: &'graph Context<'graph, T>,
) -> Result<Tensor<'graph, T>> {
    validate_scalar(f)?;

    // Compute first gradient
    let grad_f = crate::tensor_ops::grad(&[*f], &[*x])[0];
    let grad_f_flat = crate::tensor_ops::flatten(grad_f);

    // For each component of the gradient, compute the second derivative
    let mut second_derivs = Vec::with_capacity(n);

    for i in 0..n {
        let grad_i = crate::tensor_ops::slice(grad_f_flat, [i as isize], [(i + 1) as isize]);
        let d2_i = crate::tensor_ops::grad(&[grad_i], &[*x])[0];
        let d2_i_flat = crate::tensor_ops::flatten(d2_i);
        let diag_i = crate::tensor_ops::slice(d2_i_flat, [i as isize], [(i + 1) as isize]);
        second_derivs.push(diag_i);
    }

    Ok(crate::tensor_ops::linear_algebra::concat(&second_derivs, 0))
}

// ---------------------------------------------------------------------------
// Forward-mode higher-order derivatives
// ---------------------------------------------------------------------------

/// Compute the Hessian diagonal using forward-mode AD (dual numbers).
///
/// This uses nested dual numbers: for each coordinate i, compute the
/// second partial ∂²f/∂xᵢ² by running forward-mode with tangent e_i twice.
///
/// # Arguments
/// * `f` - Scalar function from dual numbers
/// * `x` - Point at which to evaluate
///
/// # Returns
/// 1-D array of [∂²f/∂x₀², ∂²f/∂x₁², ...].
pub fn hessian_diagonal_forward<F, Func>(f: &Func, x: &Array1<F>) -> Array1<F>
where
    F: NumFloat + Copy + Send + Sync + fmt::Debug + 'static,
    Func: Fn(&[DualNumber<F>]) -> DualNumber<F>,
{
    let n = x.len();
    let mut diag = Vec::with_capacity(n);
    let eps = F::from(1e-7).unwrap_or(F::epsilon());
    let two = F::one() + F::one();

    for i in 0..n {
        // Finite difference on the tangent:
        // ∂²f/∂xᵢ² ≈ (f'(x + ε·eᵢ; eᵢ) - f'(x - ε·eᵢ; eᵢ)) / (2ε)
        // where f'(x; eᵢ) is the tangent of f evaluated with tangent eᵢ

        let mut dual_plus = Vec::with_capacity(n);
        let mut dual_minus = Vec::with_capacity(n);

        for j in 0..n {
            let tangent = if i == j { F::one() } else { F::zero() };
            let x_plus = if i == j { x[j] + eps } else { x[j] };
            let x_minus = if i == j { x[j] - eps } else { x[j] };

            dual_plus.push(DualNumber::new(x_plus, tangent));
            dual_minus.push(DualNumber::new(x_minus, tangent));
        }

        let f_plus = f(&dual_plus);
        let f_minus = f(&dual_minus);

        // Second derivative from tangent finite difference
        let d2 = (f_plus.tangent() - f_minus.tangent()) / (two * eps);
        diag.push(d2);
    }

    Array1::from(diag)
}

/// Compute the Laplacian using forward-mode AD.
///
/// Laplacian = trace of Hessian = Σᵢ ∂²f/∂xᵢ².
///
/// # Arguments
/// * `f` - Scalar function from dual numbers
/// * `x` - Point at which to evaluate
pub fn laplacian_forward<F, Func>(f: &Func, x: &Array1<F>) -> F
where
    F: NumFloat + Copy + Send + Sync + fmt::Debug + 'static,
    Func: Fn(&[DualNumber<F>]) -> DualNumber<F>,
{
    let diag = hessian_diagonal_forward(f, x);
    diag.iter().fold(F::zero(), |acc, &v| acc + v)
}

/// Compute Fisher information matrix using forward-mode AD.
///
/// For a log-probability function log p(x|θ), computes:
///   F_ij = (∂log p / ∂θ_i)(∂log p / ∂θ_j)
///
/// # Arguments
/// * `log_prob` - Scalar function representing log p
/// * `theta` - Current parameter values
///
/// # Returns
/// n×n Fisher information matrix.
pub fn fisher_information_forward<F, Func>(log_prob: &Func, theta: &Array1<F>) -> Array2<F>
where
    F: NumFloat + Copy + Send + Sync + fmt::Debug + 'static,
    Func: Fn(&[DualNumber<F>]) -> DualNumber<F>,
{
    let n = theta.len();

    // Compute score vector: ∇ log p(θ)
    let grad = crate::forward_mode::gradient_forward(log_prob, theta);

    // Fisher = score ⊗ score (outer product)
    let mut fisher = Array2::zeros((n, n));
    for i in 0..n {
        for j in 0..n {
            fisher[[i, j]] = grad[i] * grad[j];
        }
    }

    fisher
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Validate that a tensor represents a scalar value.
fn validate_scalar<T: Float>(f: &Tensor<T>) -> Result<()> {
    let shape = f.shape();
    if shape.len() > 1 || (shape.len() == 1 && shape[0] != 1) {
        return Err(AutogradError::shape_error(
            "Function must be scalar (shape [] or [1])".to_string(),
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tensor_ops::*;
    use scirs2_core::ndarray::Array1;

    #[test]
    fn test_hessian_diagonal_standalone() {
        crate::run(|ctx: &mut Context<f64>| {
            // f(x) = x0^2 + 2*x1^2 + 3*x2^2
            // Hessian diagonal = [2, 4, 6]
            let x = ctx.placeholder("x", &[3]);
            let x_sq = x * x;
            let coeffs = convert_to_tensor(Array1::from(vec![1.0, 2.0, 3.0]).into_dyn(), ctx);
            let f = crate::tensor_ops::reduction::sum_all(coeffs * x_sq);

            let diag = hessian_diagonal(&f, &x, 3, ctx).expect("Should compute diagonal");

            let x_val = scirs2_core::ndarray::arr1(&[1.0, 1.0, 1.0]);
            let result = ctx
                .evaluator()
                .push(&diag)
                .feed(x, x_val.view().into_dyn())
                .run();

            let diag_arr = result[0].as_ref().expect("Should evaluate");
            let diag_vals = diag_arr.as_slice().unwrap_or(&[]);
            assert!((diag_vals[0] - 2.0).abs() < 1e-5);
            assert!((diag_vals[1] - 4.0).abs() < 1e-5);
            assert!((diag_vals[2] - 6.0).abs() < 1e-5);
        });
    }

    #[test]
    fn test_laplacian_graph() {
        crate::run(|ctx: &mut Context<f64>| {
            // f(x) = x0^2 + x1^2 + x2^2
            // Laplacian = 2 + 2 + 2 = 6
            let x = ctx.placeholder("x", &[3]);
            let f = crate::tensor_ops::reduction::sum_all(x * x);

            let lap = laplacian(&f, &x, 3, ctx).expect("Should compute Laplacian");

            let x_val = scirs2_core::ndarray::arr1(&[1.0, 2.0, 3.0]);
            let result = ctx
                .evaluator()
                .push(&lap)
                .feed(x, x_val.view().into_dyn())
                .run();

            let lap_val = result[0]
                .as_ref()
                .expect("Should evaluate")
                .first()
                .copied()
                .unwrap_or(0.0);
            assert!((lap_val - 6.0).abs() < 1e-5);
        });
    }

    #[test]
    fn test_fisher_information_graph() {
        crate::run(|ctx: &mut Context<f64>| {
            // log p = -0.5 * (x0^2 + x1^2) (Gaussian log-likelihood)
            // score = [-x0, -x1]
            // Fisher = [[x0^2, x0*x1], [x0*x1, x1^2]]
            let x = ctx.placeholder("x", &[2]);
            let neg_half = convert_to_tensor(scirs2_core::ndarray::arr0(-0.5).into_dyn(), ctx);
            let log_prob = neg_half * crate::tensor_ops::reduction::sum_all(x * x);

            let fisher = fisher_information(&log_prob, &x, 2, ctx).expect("Should compute Fisher");

            let x_val = scirs2_core::ndarray::arr1(&[3.0, 4.0]);
            let result = ctx
                .evaluator()
                .push(&fisher)
                .feed(x, x_val.view().into_dyn())
                .run();

            let f_arr = result[0].as_ref().expect("Should evaluate");
            let f_vals = f_arr.as_slice().unwrap_or(&[]);
            // Fisher = [[9, 12], [12, 16]] (score = [-3, -4], outer product)
            assert!((f_vals[0] - 9.0).abs() < 1e-5);
            assert!((f_vals[1] - 12.0).abs() < 1e-5);
            assert!((f_vals[2] - 12.0).abs() < 1e-5);
            assert!((f_vals[3] - 16.0).abs() < 1e-5);
        });
    }

    #[test]
    fn test_fisher_diagonal_graph() {
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[2]);
            let neg_half = convert_to_tensor(scirs2_core::ndarray::arr0(-0.5).into_dyn(), ctx);
            let log_prob = neg_half * crate::tensor_ops::reduction::sum_all(x * x);

            let fisher_d =
                fisher_diagonal(&log_prob, &x, ctx).expect("Should compute Fisher diagonal");

            let x_val = scirs2_core::ndarray::arr1(&[3.0, 4.0]);
            let result = ctx
                .evaluator()
                .push(&fisher_d)
                .feed(x, x_val.view().into_dyn())
                .run();

            let f_arr = result[0].as_ref().expect("Should evaluate");
            let f_vals = f_arr.as_slice().unwrap_or(&[]);
            // diagonal = [9, 16]
            assert!((f_vals[0] - 9.0).abs() < 1e-5);
            assert!((f_vals[1] - 16.0).abs() < 1e-5);
        });
    }

    #[test]
    fn test_hessian_diagonal_forward_quadratic() {
        // f(x) = 2*x0^2 + 3*x1^2
        // Hessian diagonal = [4, 6]
        let f = |xs: &[DualNumber<f64>]| {
            let two = DualNumber::constant(2.0);
            let three = DualNumber::constant(3.0);
            two * xs[0] * xs[0] + three * xs[1] * xs[1]
        };
        let x = Array1::from(vec![1.0, 1.0]);
        let diag = hessian_diagonal_forward(&f, &x);
        assert!((diag[0] - 4.0).abs() < 1e-3);
        assert!((diag[1] - 6.0).abs() < 1e-3);
    }

    #[test]
    fn test_laplacian_forward_mode() {
        // f(x) = x0^2 + x1^2 + x2^2
        // Laplacian = 2 + 2 + 2 = 6
        let f = |xs: &[DualNumber<f64>]| xs[0] * xs[0] + xs[1] * xs[1] + xs[2] * xs[2];
        let x = Array1::from(vec![1.0, 2.0, 3.0]);
        let lap = laplacian_forward(&f, &x);
        assert!((lap - 6.0).abs() < 1e-3);
    }

    #[test]
    fn test_fisher_information_forward_mode() {
        // log p = -0.5*(x0^2 + x1^2)
        // score = [-x0, -x1]
        // Fisher at (3,4) = [[9,12],[12,16]]
        let log_prob = |xs: &[DualNumber<f64>]| {
            let neg_half = DualNumber::constant(-0.5);
            neg_half * (xs[0] * xs[0] + xs[1] * xs[1])
        };
        let theta = Array1::from(vec![3.0, 4.0]);
        let fisher = fisher_information_forward(&log_prob, &theta);
        assert!((fisher[[0, 0]] - 9.0).abs() < 1e-5);
        assert!((fisher[[0, 1]] - 12.0).abs() < 1e-5);
        assert!((fisher[[1, 0]] - 12.0).abs() < 1e-5);
        assert!((fisher[[1, 1]] - 16.0).abs() < 1e-5);
    }

    #[test]
    fn test_efficient_second_order_grad() {
        crate::run(|ctx: &mut Context<f64>| {
            // f(x) = x0^2 + 2*x1^2
            // diagonal of Hessian = [2, 4]
            let x = ctx.placeholder("x", &[2]);
            let x_sq = x * x;
            let coeffs = convert_to_tensor(Array1::from(vec![1.0, 2.0]).into_dyn(), ctx);
            let f = crate::tensor_ops::reduction::sum_all(coeffs * x_sq);

            let d2 = efficient_second_order_grad(&f, &x, 2, ctx)
                .expect("Should compute second-order grad");

            let x_val = scirs2_core::ndarray::arr1(&[1.0, 1.0]);
            let result = ctx
                .evaluator()
                .push(&d2)
                .feed(x, x_val.view().into_dyn())
                .run();

            let d2_arr = result[0].as_ref().expect("Should evaluate");
            let d2_vals = d2_arr.as_slice().unwrap_or(&[]);
            assert!((d2_vals[0] - 2.0).abs() < 1e-5);
            assert!((d2_vals[1] - 4.0).abs() < 1e-5);
        });
    }

    #[test]
    fn test_validate_scalar_rejects_non_scalar() {
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[3]);
            let result = hessian_diagonal(&x, &x, 3, ctx);
            // x is not scalar, should fail
            // Note: shapes are dynamic, so this might not fail at graph-build time
            // but we test the shape validation path
        });
    }

    #[test]
    fn test_hessian_diagonal_dimension_zero_error() {
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[]);
            let f = x * x;
            let result = hessian_diagonal(&f, &x, 0, ctx);
            assert!(result.is_err());
        });
    }
}