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
use crate::accumulate_grad::AccumulateGrad;
use crate::gradient_function::GradientFunction;
use crate::ndarray::flags::NdArrayFlags;
use crate::{Constructors, NdArray, StridedMemory, Tensor, TensorDataType};
use crate::none_backwards::NoneBackwards;
impl<'a, T: TensorDataType> Tensor<'a, T> {
/// Checks if the tensor is a leaf.
///
/// A tensor is considered a leaf node if `requires_grad = true`
/// and it was explicitly created by the user, or if `requires_grad = false`.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut tensor = Tensor::new([1.0, 2.0, 3.0]);
/// tensor.set_requires_grad(true);
/// assert!(tensor.is_leaf());
///
/// let tensor2 = -tensor;
/// assert!(!tensor2.is_leaf());
/// ```
#[inline]
pub fn is_leaf(&self) -> bool {
if self.requires_grad() {
self.flags.contains(NdArrayFlags::UserCreated)
} else {
true
}
}
/// Returns whether gradients must be computed for this tensor.
///
/// A tensor is marked with the `requires_grad` flag if it was explicitly specified by the user
/// through the `set_requires_grad()` method or if the tensor was created using operations
/// on other tensors which were marked `requires_grad`.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut tensor = Tensor::new([1.0, 2.0, 3.0]);
/// tensor.set_requires_grad(true);
///
/// let tensor2 = -tensor;
/// assert!(tensor2.requires_grad());
/// ```
#[inline]
pub fn requires_grad(&self) -> bool {
self.flags.contains(NdArrayFlags::RequiresGrad)
}
/// Sets whether gradients must be computed for this tensor.
pub fn set_requires_grad(&mut self, requires_grad: bool) -> &mut Self {
let required_grad = self.requires_grad();
if requires_grad {
self.flags |= NdArrayFlags::RequiresGrad;
} else {
self.flags -= NdArrayFlags::RequiresGrad;
}
if !required_grad && requires_grad {
self.grad_fn = AccumulateGrad::new(self.shape().to_vec());
}
if required_grad && !requires_grad {
self.grad_fn = NoneBackwards::new();
}
self
}
/// Retrieves the gradient function associated with the current object.
///
/// This is `NoneBackwards` if the tensor has `requires_grad = false`
/// or `AccumulateBackwards` if the tensor is a leaf node.
pub(crate) fn grad_fn(&self) -> GradientFunction<T> {
self.grad_fn.clone()
}
/// Returns the gradient of the differentiated tensor with respect to `self`.
///
/// This method returns a view into the gradient.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut a = Tensor::scalar(2.0f32);
/// let b = Tensor::scalar(3.0);
///
/// a.set_requires_grad(true);
///
/// let c = &a * &b;
/// c.backward();
///
/// // dc/da = b
/// assert_eq!(a.gradient().unwrap(), b);
/// ```
pub fn gradient(&'a self) -> Option<NdArray<'a, T>> {
unsafe { (*self.grad_fn.as_ptr()).gradient() }
}
/// Sets the gradient of this tensor to zero.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut a = Tensor::scalar(2.0f32);
/// let b = Tensor::scalar(3.0);
///
/// a.set_requires_grad(true);
///
/// let c = &a * &b;
/// c.backward();
///
/// a.zero_gradient();
/// assert_eq!(a.gradient().unwrap(), Tensor::scalar(0.0));
/// ```
pub fn zero_gradient(&self) {
self.grad_fn.borrow_mut().zero_gradient();
}
/// Computes the gradient of the `self` with respect to its leaf tensors.
///
/// # Parameters
///
/// - `gradient`: the gradient of the tensor being differentiated with respect to `self`.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut a = Tensor::full(2.0, [3]); // [2, 2, 2]
/// let b = Tensor::new([3.0, 1.0, -1.0]);
///
/// a.set_requires_grad(true);
///
/// let c = &a * &b;
/// c.backward_with(NdArray::new([2.0, 1.0, 1.0]));
///
/// // dc/da = b
/// assert_eq!(a.gradient().unwrap(), Tensor::new([6.0, 1.0, -1.0]));
/// ```
pub fn backward_with(&self, gradient: impl AsRef<NdArray<'a, T>>) {
let gradient = gradient.as_ref();
assert_eq!(gradient.shape(), self.shape());
self.grad_fn.borrow_mut().backward(gradient);
}
/// Computes the gradient of the `self` with respect to its leaf tensors.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut a = Tensor::full(2.0, [3]); // [2, 2, 2]
/// let b = Tensor::new([3.0, 1.0, -1.0]);
///
/// a.set_requires_grad(true);
///
/// let c = &a * &b;
/// c.backward();
///
/// // dc/da = b
/// assert_eq!(a.gradient().unwrap(), Tensor::new([3.0, 1.0, -1.0]));
/// ```
pub fn backward(&self) {
self.backward_with(NdArray::ones(self.shape()))
}
/// Detaches the tensor from the computation graph and returns an `NdArray`.
///
/// # Examples
///
/// ```
/// # use redstone_ml::*;
///
/// let mut a = Tensor::full(2.0, [3]);
/// a.set_requires_grad(true);
///
/// let c = &a * 5.0;
///
/// let d = c.detach();
/// assert_eq!(d, NdArray::new([10.0, 10.0, 10.0]));
/// ```
pub fn detach(&self) -> NdArray<'static, T> {
self.array.as_ref().clone()
}
}