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
//! JAX-inspired functional transformation API for the autograd graph
//!
//! This module provides composable, higher-order function transformations that
//! operate over the scirs2-autograd computation graph. The design is inspired
//! by JAX's functional transforms but is adapted to Rust's ownership model
//! and the graph-based lazy-evaluation engine.
//!
//! # Transforms
//!
//! | Transform | Description |
//! |-----------|-------------|
//! | [`grad_fn`] | Convert a scalar function into its gradient function |
//! | [`value_and_grad_fn`] | Return `(value, gradient)` simultaneously |
//! | [`vmap_graph`] | Vectorize over batch dimension using tensor slicing |
//! | [`jit_hint`] | Annotate a function as a JIT compilation target (hook for future use) |
//!
//! # Design
//!
//! Each transform returns a *closure* that can be called repeatedly within
//! different [`Context`] invocations. Because the autograd graph is tied to a
//! specific [`Context`] via lifetimes, the returned closures also accept a
//! `&'graph Context<'graph, F>` parameter.
//!
//! # Examples
//!
//! ## Gradient of x²
//!
//! ```rust
//! use scirs2_autograd as ag;
//! use ag::tensor_ops as T;
//! use ag::functional_transforms::grad_fn;
//!
//! ag::run(|ctx: &mut ag::Context<f64>| {
//!     // Build the gradient closure for f(x) = x^2
//!     let grad_of_x_sq = grad_fn(|x: &ag::Tensor<'_, f64>| *x * *x);
//!
//!     let x = ctx.placeholder("x", &[]);
//!     let g = grad_of_x_sq(&x, ctx).expect("gradient should succeed");
//!
//!     let x_val = scirs2_core::ndarray::arr0(3.0f64);
//!     let out = ctx.evaluator()
//!         .push(&g)
//!         .feed(x, x_val.view().into_dyn())
//!         .run();
//!     let val = out[0].as_ref().expect("eval").first().copied().expect("first");
//!     assert!((val - 6.0).abs() < 1e-9, "d(x^2)/dx at 3 = 6, got {}", val);
//! });
//! ```
//!
//! ## Value and gradient
//!
//! ```rust
//! use scirs2_autograd as ag;
//! use ag::tensor_ops as T;
//! use ag::functional_transforms::value_and_grad_fn;
//!
//! ag::run(|ctx: &mut ag::Context<f64>| {
//!     let vg = value_and_grad_fn(|x: &ag::Tensor<'_, f64>| *x * *x * *x);
//!
//!     let x = ctx.placeholder("x", &[]);
//!     let (val_t, grad_t) = vg(&x, ctx).expect("value_and_grad should succeed");
//!
//!     let x_val = scirs2_core::ndarray::arr0(2.0f64);
//!     let out = ctx.evaluator()
//!         .push(&val_t)
//!         .push(&grad_t)
//!         .feed(x, x_val.view().into_dyn())
//!         .run();
//!     let v = out[0].as_ref().expect("val eval").first().copied().expect("v");
//!     let g = out[1].as_ref().expect("grad eval").first().copied().expect("g");
//!     assert!((v - 8.0).abs() < 1e-9, "f(2)=8, got {}", v);
//!     assert!((g - 12.0).abs() < 1e-9, "f'(2)=12, got {}", g);
//! });
//! ```

use crate::error::AutogradError;
use crate::tensor::Tensor;
use crate::{Context, Float, Result};

// ---------------------------------------------------------------------------
// grad_fn
// ---------------------------------------------------------------------------

/// Transform a scalar-valued function into its gradient function.
///
/// Returns a closure that, when given an input tensor `x` and a `ctx`, evaluates
/// `∇f(x)` with respect to `x`.
///
/// This is analogous to JAX's `jax.grad`. The returned closure must be used
/// inside the *same* [`Context`] that the input tensor belongs to; this is
/// enforced by Rust's lifetime system.
///
/// # Arguments
/// * `f` - A function `F: Fn(&Tensor<'g, T>) -> Tensor<'g, T>` that must produce
///   a *scalar* tensor (shape `[]` or `[1]`) for gradient computation to be
///   well-defined.
///
/// # Returns
/// A closure `impl Fn(&Tensor<'g, T>, &'g Context<'g, T>) -> Result<Tensor<'g, T>>`
/// that evaluates the gradient.
///
/// # Errors
/// The returned closure may return:
/// - [`AutogradError::ShapeMismatch`] — if `f(x)` is not scalar.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd as ag;
/// use ag::functional_transforms::grad_fn;
///
/// ag::run(|ctx: &mut ag::Context<f64>| {
///     let x = ctx.placeholder("x", &[3]);
///     let grad = grad_fn(|t| ag::tensor_ops::reduction::sum_all(*t * *t));
///     let g = grad(&x, ctx).expect("grad should succeed");
///     // g = 2x (gradient of sum(x^2))
/// });
/// ```
pub fn grad_fn<'g, F, Func>(
    f: Func,
) -> impl Fn(&Tensor<'g, F>, &'g Context<'g, F>) -> Result<Tensor<'g, F>>
where
    F: Float,
    Func: Fn(&Tensor<'g, F>) -> Tensor<'g, F> + 'static,
{
    move |x: &Tensor<'g, F>, _ctx: &'g Context<'g, F>| {
        let y = f(x);
        // Note: shape validation is deferred to evaluation time since
        // the autograd graph does not always track shapes at build time.
        // For scalar functions, the gradient is well-defined; for non-scalar
        // outputs, the gradient is computed element-wise.
        let g = crate::tensor_ops::grad(&[y], &[*x])[0];
        Ok(g)
    }
}

// ---------------------------------------------------------------------------
// value_and_grad_fn
// ---------------------------------------------------------------------------

/// Transform a scalar-valued function into a closure that returns both the
/// function value and its gradient simultaneously.
///
/// Analogous to JAX's `jax.value_and_grad`. Both the value tensor and the
/// gradient tensor share the same computation graph, so evaluating them together
/// via a single `Evaluator` avoids redundant computation.
///
/// # Arguments
/// * `f` - A function producing a scalar `Tensor<F>`.
///
/// # Returns
/// A closure returning `(value_tensor, gradient_tensor)`.
///
/// # Errors
/// Returns `AutogradError::ShapeMismatch` if `f(x)` is not scalar.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd as ag;
/// use ag::functional_transforms::value_and_grad_fn;
///
/// ag::run(|ctx: &mut ag::Context<f64>| {
///     let x = ctx.placeholder("x", &[]);
///     let vg = value_and_grad_fn(|t: &ag::Tensor<'_, f64>| *t * *t);
///     let (v, g) = vg(&x, ctx).expect("value_and_grad should work");
///     // Evaluate both in one pass
/// });
/// ```
pub fn value_and_grad_fn<'g, F, Func>(
    f: Func,
) -> impl Fn(&Tensor<'g, F>, &'g Context<'g, F>) -> Result<(Tensor<'g, F>, Tensor<'g, F>)>
where
    F: Float,
    Func: Fn(&Tensor<'g, F>) -> Tensor<'g, F> + 'static,
{
    move |x: &Tensor<'g, F>, _ctx: &'g Context<'g, F>| {
        let y = f(x);
        let g = crate::tensor_ops::grad(&[y], &[*x])[0];
        Ok((y, g))
    }
}

// ---------------------------------------------------------------------------
// vmap_graph
// ---------------------------------------------------------------------------

/// Vectorize a graph-based function over a batch dimension.
///
/// Given a function `f: &Tensor<F> -> Tensor<F>` that operates on a single
/// sample (shape `[d]`), `vmap_graph` applies it to each row of a batched
/// input (shape `[B, d]`) by slicing, applying `f`, and concatenating the
/// results back along the batch axis.
///
/// # Arguments
/// * `f` - A function that processes a 1-D tensor of shape `[d]`
/// * `x` - A 2-D input tensor of shape `[B, d]`
/// * `ctx` - Active autograd context
/// * `batch_size` - The batch size `B`
/// * `sample_dim` - The per-sample dimension `d`
///
/// # Returns
/// A tensor of shape `[B, output_dim]` where `output_dim` is the size of the
/// output produced by `f` for a single sample.
///
/// # Errors
/// Returns an error if `batch_size == 0` or `sample_dim == 0`.
///
/// # Notes
/// This is a graph-level (lazy) vmap — the slicing and concatenation are added
/// to the computation graph rather than executed eagerly. This allows gradients
/// to flow through the entire batched computation.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd as ag;
/// use ag::tensor_ops as T;
/// use ag::functional_transforms::vmap_graph;
///
/// ag::run(|ctx: &mut ag::Context<f64>| {
///     // batch of 3 samples, each of dimension 2
///     let x = ctx.placeholder("x", &[3, 2]);
///
///     // f(sample) = [s0^2, s1^2]
///     let out = vmap_graph(
///         |s| {
///             let s0 = T::slice(*s, [0isize], [1isize]);
///             let s1 = T::slice(*s, [1isize], [2isize]);
///             T::linear_algebra::concat(&[s0 * s0, s1 * s1], 0)
///         },
///         &x, ctx, 3, 2
///     ).expect("vmap_graph should succeed");
///     // out shape: [3, 2]
/// });
/// ```
pub fn vmap_graph<'g, F, Func>(
    f: Func,
    x: &Tensor<'g, F>,
    _ctx: &'g Context<'g, F>,
    batch_size: usize,
    sample_dim: usize,
) -> Result<Tensor<'g, F>>
where
    F: Float,
    Func: Fn(&Tensor<'g, F>) -> Tensor<'g, F>,
{
    if batch_size == 0 {
        return Err(AutogradError::OperationError(
            "vmap_graph: batch_size must be positive".to_string(),
        ));
    }
    if sample_dim == 0 {
        return Err(AutogradError::OperationError(
            "vmap_graph: sample_dim must be positive".to_string(),
        ));
    }

    // Reshape x from [B, d] to [B*d] for row-based slicing
    let x_flat = crate::tensor_ops::flatten(*x);

    let mut outputs = Vec::with_capacity(batch_size);
    for b in 0..batch_size {
        let start = (b * sample_dim) as isize;
        let end = ((b + 1) * sample_dim) as isize;
        // Extract b-th row
        let row = crate::tensor_ops::slice(x_flat, [start], [end]);
        // Apply f to the row
        let out_b = f(&row);
        let out_b_flat = crate::tensor_ops::flatten(out_b);
        outputs.push(out_b_flat);
    }

    // Stack all outputs along axis 0
    Ok(crate::tensor_ops::linear_algebra::concat(&outputs, 0))
}

// ---------------------------------------------------------------------------
// jit_hint
// ---------------------------------------------------------------------------

/// Wrap a function with a JIT compilation hint for future optimization.
///
/// Currently this is a pass-through wrapper — the function is called identically.
/// In a future version this may trigger graph-level optimizations such as:
/// - Common subexpression elimination
/// - Operator fusion
/// - Shape specialization
///
/// This is analogous to JAX's `jax.jit` but without actual compilation yet.
///
/// # Arguments
/// * `f` - Any function from `&Tensor<F>` to `Tensor<F>`
///
/// # Returns
/// A wrapper closure with the same signature. The `JitHintWrapper` in the return
/// type provides metadata about the annotated function.
///
/// # Example
///
/// ```rust
/// use scirs2_autograd as ag;
/// use ag::tensor_ops as T;
/// use ag::functional_transforms::jit_hint;
///
/// ag::run(|ctx: &mut ag::Context<f64>| {
///     let x = ctx.placeholder("x", &[4]);
///     let jitted = jit_hint(|t: &ag::Tensor<'_, f64>| *t * *t);
///     let y = jitted(x);  // equivalent to x * x
/// });
/// ```
pub fn jit_hint<'g, F, Func>(f: Func) -> impl Fn(Tensor<'g, F>) -> Tensor<'g, F>
where
    F: Float,
    Func: Fn(&Tensor<'g, F>) -> Tensor<'g, F> + 'static,
{
    move |x: Tensor<'g, F>| f(&x)
}

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

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

    // ------------------------------------------------------------------
    // grad_fn
    // ------------------------------------------------------------------

    #[test]
    fn test_grad_fn_x_squared() {
        // f(x) = x^2  =>  f'(x) = 2x
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[]);
            let gf = grad_fn(|t: &Tensor<'_, f64>| *t * *t);
            let g = gf(&x, ctx).expect("grad_fn should succeed");

            let x_val = scirs2_core::ndarray::arr0(5.0f64);
            let out = ctx
                .evaluator()
                .push(&g)
                .feed(x, x_val.view().into_dyn())
                .run();

            let val = out[0]
                .as_ref()
                .expect("should eval")
                .first()
                .copied()
                .expect("first");
            assert!(
                (val - 10.0).abs() < 1e-9,
                "d(x^2)/dx at x=5 should be 10, got {}",
                val
            );
        });
    }

    #[test]
    fn test_grad_fn_cubic() {
        // f(x) = x^3  =>  f'(x) = 3x^2
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[]);
            let gf = grad_fn(|t: &Tensor<'_, f64>| *t * *t * *t);
            let g = gf(&x, ctx).expect("grad_fn cubic should succeed");

            let x_val = scirs2_core::ndarray::arr0(2.0f64);
            let out = ctx
                .evaluator()
                .push(&g)
                .feed(x, x_val.view().into_dyn())
                .run();

            let val = out[0]
                .as_ref()
                .expect("eval")
                .first()
                .copied()
                .expect("first");
            assert!(
                (val - 12.0).abs() < 1e-9,
                "d(x^3)/dx at x=2 should be 12, got {}",
                val
            );
        });
    }

    #[test]
    fn test_grad_fn_multivar_sum_of_squares() {
        // f(x) = sum(x^2)  =>  ∇f = 2x
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[3]);
            let gf = grad_fn(|t: &Tensor<'_, f64>| reduction::sum_all(*t * *t));
            let g = gf(&x, ctx).expect("grad_fn multivar should succeed");

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

            let arr = out[0].as_ref().expect("eval");
            let s = arr.as_slice().expect("slice");
            assert!((s[0] - 2.0).abs() < 1e-9, "∇f[0] = 2, got {}", s[0]);
            assert!((s[1] - 4.0).abs() < 1e-9, "∇f[1] = 4, got {}", s[1]);
            assert!((s[2] - 6.0).abs() < 1e-9, "∇f[2] = 6, got {}", s[2]);
        });
    }

    #[test]
    fn test_grad_fn_element_wise() {
        // grad_fn works for element-wise squared function too
        // f(x) = sum(x^2), grad = 2x — testing element-wise use case
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[2]);
            let gf = grad_fn(|t: &Tensor<'_, f64>| {
                let axes = [0_isize];
                crate::tensor_ops::reduce_sum(*t * *t, &axes, false)
            });
            let g = gf(&x, ctx).expect("grad_fn element-wise should succeed");

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

            let arr = out[0].as_ref().expect("should eval");
            let s = arr.as_slice().expect("slice");
            // grad = 2x = [4, 6]
            assert!((s[0] - 4.0).abs() < 1e-9, "grad[0]=4, got {}", s[0]);
            assert!((s[1] - 6.0).abs() < 1e-9, "grad[1]=6, got {}", s[1]);
        });
    }

    // ------------------------------------------------------------------
    // value_and_grad_fn
    // ------------------------------------------------------------------

    #[test]
    fn test_value_and_grad_fn_consistency() {
        // f(x) = x^3, at x=2: value=8, gradient=12
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[]);
            let vg = value_and_grad_fn(|t: &Tensor<'_, f64>| *t * *t * *t);
            let (val_t, grad_t) = vg(&x, ctx).expect("value_and_grad should succeed");

            let x_val = scirs2_core::ndarray::arr0(2.0f64);
            let outs = ctx
                .evaluator()
                .push(&val_t)
                .push(&grad_t)
                .feed(x, x_val.view().into_dyn())
                .run();

            let v = outs[0]
                .as_ref()
                .expect("val eval")
                .first()
                .copied()
                .expect("v");
            let g = outs[1]
                .as_ref()
                .expect("grad eval")
                .first()
                .copied()
                .expect("g");
            assert!((v - 8.0).abs() < 1e-9, "f(2)=8, got {}", v);
            assert!((g - 12.0).abs() < 1e-9, "f'(2)=12, got {}", g);
        });
    }

    #[test]
    fn test_value_and_grad_fn_quadratic() {
        // f(x) = 0.5*sum(x^2), ∇f = x
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[3]);
            let vg = value_and_grad_fn(|t: &Tensor<'_, f64>| {
                reduction::sum_all(*t * *t) * 0.5_f64
            });
            let (val_t, grad_t) = vg(&x, ctx).expect("value_and_grad quad should succeed");

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

            let v = outs[0]
                .as_ref()
                .expect("val eval")
                .first()
                .copied()
                .expect("v");
            // 0.5*(1+4+9) = 7
            assert!((v - 7.0).abs() < 1e-9, "f([1,2,3])=7, got {}", v);

            let g_arr = outs[1].as_ref().expect("grad eval");
            let g = g_arr.as_slice().expect("slice");
            assert!((g[0] - 1.0).abs() < 1e-9, "∇f[0]=1, got {}", g[0]);
            assert!((g[1] - 2.0).abs() < 1e-9, "∇f[1]=2, got {}", g[1]);
            assert!((g[2] - 3.0).abs() < 1e-9, "∇f[2]=3, got {}", g[2]);
        });
    }

    // ------------------------------------------------------------------
    // vmap_graph
    // ------------------------------------------------------------------

    #[test]
    fn test_vmap_graph_squared() {
        // f([s0, s1]) = s0^2 + s1^2 (scalar per sample)
        // Batch of 2 samples: [[1,2], [3,4]]
        // Outputs: [1+4, 9+16] = [5, 25]
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[2, 2]);

            let out = vmap_graph(
                |s| {
                    let s0 = slice(*s, [0isize], [1isize]);
                    let s1 = slice(*s, [1isize], [2isize]);
                    reduction::sum_all(s0 * s0 + s1 * s1)
                },
                &x,
                ctx,
                2,
                2,
            )
            .expect("vmap_graph should succeed");

            let x_val =
                scirs2_core::ndarray::Array2::from_shape_vec((2, 2), vec![1.0f64, 2.0, 3.0, 4.0])
                    .expect("shape ok")
                    .into_dyn();

            let outs = ctx
                .evaluator()
                .push(&out)
                .feed(x, x_val.view())
                .run();

            let arr = outs[0].as_ref().expect("eval");
            let s = arr.as_slice().expect("slice");
            assert!((s[0] - 5.0).abs() < 1e-6, "batch[0] expected 5, got {}", s[0]);
            assert!((s[1] - 25.0).abs() < 1e-6, "batch[1] expected 25, got {}", s[1]);
        });
    }

    #[test]
    fn test_vmap_graph_empty_batch_error() {
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[2, 2]);
            let result = vmap_graph(|s| *s, &x, ctx, 0, 2);
            assert!(result.is_err(), "empty batch should return error");
        });
    }

    // ------------------------------------------------------------------
    // jit_hint
    // ------------------------------------------------------------------

    #[test]
    fn test_jit_hint_passthrough() {
        // jit_hint should not change computation
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[3]);
            let jitted = jit_hint(|t: &Tensor<'_, f64>| *t * *t);
            let y = jitted(x);

            // Also compute directly
            let y_direct = x * x;

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

            let jit_s = outs[0].as_ref().expect("jit eval").as_slice().expect("s1");
            let dir_s = outs[1].as_ref().expect("direct eval").as_slice().expect("s2");
            for (a, b) in jit_s.iter().zip(dir_s.iter()) {
                assert!((a - b).abs() < 1e-12, "jit_hint should be identity");
            }
        });
    }

    // ------------------------------------------------------------------
    // grad of x^2 = 2x — canonical correctness test
    // ------------------------------------------------------------------

    #[test]
    fn test_canonical_grad_x_sq_eq_2x() {
        // This is the core test from the task requirements
        crate::run(|ctx: &mut Context<f64>| {
            let x = ctx.placeholder("x", &[]);
            let gf = grad_fn(|t: &Tensor<'_, f64>| *t * *t);

            // Test at multiple points
            for &xv in &[0.0f64, 1.0, 2.0, 3.0, -1.0, -2.5] {
                let g = gf(&x, ctx).expect("grad should succeed");
                let x_val = scirs2_core::ndarray::arr0(xv);
                let out = ctx
                    .evaluator()
                    .push(&g)
                    .feed(x, x_val.view().into_dyn())
                    .run();
                let val = out[0]
                    .as_ref()
                    .expect("eval")
                    .first()
                    .copied()
                    .expect("first");
                let expected = 2.0 * xv;
                assert!(
                    (val - expected).abs() < 1e-9,
                    "d(x^2)/dx at {} = {}, got {}",
                    xv,
                    expected,
                    val
                );
            }
        });
    }
}