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
//! Gradient function trait for automatic differentiation
//!
//! This module defines the core [`GradFn`] trait that all backward operations
//! must implement to participate in the autograd system.
use crateResult;
use crateRuntime;
use crate;
use Arc;
use Var;
/// Trait for computing gradients during backward pass
///
/// Each operation that participates in autograd has an associated
/// `GradFn` that knows how to compute gradients for its inputs.
///
/// # Implementation Guide
///
/// When implementing this trait, you **must** implement both `backward()` and
/// `backward_var()` if you want proper second-order differentiation support.
///
/// The `backward()` method is used for first-order gradients (standard backprop).
/// The `backward_var()` method is used for second-order gradients (Hessians, HVPs).
///
/// # Example
///
/// ```ignore
/// # use numr::prelude::*;
/// # use numr::autograd::{GradFn, Var};
/// # use numr::error::Result;
/// # use std::sync::Arc;
/// struct MyOpBackward<R: Runtime> {
/// saved_tensor: Tensor<R>,
/// }
///
/// impl<R: Runtime> GradFn<R> for MyOpBackward<R> {
/// fn backward(&self, grad_output: &Tensor<R>) -> Result<Vec<Option<Tensor<R>>>> {
/// // Compute gradients using tensor ops
/// // let grad = client.mul(grad_output, &self.saved_tensor)?;
/// Ok(vec![Some(grad_output.clone())])
/// }
///
/// fn backward_var(&self, grad_output: &Var<R>) -> Result<Vec<Option<Var<R>>>> {
/// // Compute gradients using var_ops to maintain computation graph
/// Ok(vec![Some(grad_output.clone())])
/// }
/// }
/// ```