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
use super::var_store::{VarStore, Variables};
use crate::wrappers::optimizer::COptimizer;
use crate::{TchError, Tensor};
use std::sync::{Arc, Mutex};
#[derive(Debug)]
pub struct Optimizer {
opt: COptimizer,
variables: Arc<Mutex<Variables>>,
variables_in_optimizer: usize,
}
pub trait OptimizerConfig
where
Self: std::marker::Sized,
{
fn build_copt(&self, lr: f64) -> Result<COptimizer, TchError>;
fn build(self, vs: &VarStore, lr: f64) -> Result<Optimizer, TchError> {
let mut opt = self.build_copt(lr)?;
let v = vs.variables_.lock().unwrap();
for var in &v.trainable_variables {
opt.add_parameters(&var.tensor, var.group)?;
}
Ok(Optimizer {
opt,
variables: vs.variables_.clone(),
variables_in_optimizer: v.trainable_variables.len(),
})
}
}
#[derive(Debug, Copy, Clone)]
pub struct Sgd {
pub momentum: f64,
pub dampening: f64,
pub wd: f64,
pub nesterov: bool,
}
impl Default for Sgd {
fn default() -> Self {
Sgd { momentum: 0., dampening: 0., wd: 0., nesterov: false }
}
}
pub fn sgd(momentum: f64, dampening: f64, wd: f64, nesterov: bool) -> Sgd {
Sgd { momentum, dampening, wd, nesterov }
}
impl OptimizerConfig for Sgd {
fn build_copt(&self, lr: f64) -> Result<COptimizer, TchError> {
COptimizer::sgd(lr, self.momentum, self.dampening, self.wd, self.nesterov)
}
}
#[derive(Debug, Copy, Clone)]
pub struct Adam {
pub beta1: f64,
pub beta2: f64,
pub wd: f64,
pub eps: f64,
pub amsgrad: bool,
}
impl Default for Adam {
fn default() -> Self {
Adam { beta1: 0.9, beta2: 0.999, wd: 0., eps: 1e-8, amsgrad: false }
}
}
pub fn adam(beta1: f64, beta2: f64, wd: f64) -> Adam {
Adam { beta1, beta2, wd, eps: 1e-8, amsgrad: false }
}
impl Adam {
pub fn beta1(mut self, b: f64) -> Self {
self.beta1 = b;
self
}
pub fn beta2(mut self, b: f64) -> Self {
self.beta2 = b;
self
}
pub fn wd(mut self, w: f64) -> Self {
self.wd = w;
self
}
pub fn eps(mut self, e: f64) -> Self {
self.eps = e;
self
}
pub fn amsgrad(mut self, a: bool) -> Self {
self.amsgrad = a;
self
}
}
impl OptimizerConfig for Adam {
fn build_copt(&self, lr: f64) -> Result<COptimizer, TchError> {
COptimizer::adam(lr, self.beta1, self.beta2, self.wd, self.eps, self.amsgrad)
}
}
#[derive(Debug, Copy, Clone)]
pub struct AdamW {
pub beta1: f64,
pub beta2: f64,
pub wd: f64,
pub eps: f64,
pub amsgrad: bool,
}
impl Default for AdamW {
fn default() -> Self {
AdamW { beta1: 0.9, beta2: 0.999, wd: 0.01, eps: 1e-8, amsgrad: false }
}
}
pub fn adamw(beta1: f64, beta2: f64, wd: f64) -> AdamW {
AdamW { beta1, beta2, wd, eps: 1e-8, amsgrad: false }
}
impl AdamW {
pub fn beta1(mut self, b: f64) -> Self {
self.beta1 = b;
self
}
pub fn beta2(mut self, b: f64) -> Self {
self.beta2 = b;
self
}
pub fn wd(mut self, w: f64) -> Self {
self.wd = w;
self
}
pub fn eps(mut self, e: f64) -> Self {
self.eps = e;
self
}
pub fn amsgrad(mut self, a: bool) -> Self {
self.amsgrad = a;
self
}
}
impl OptimizerConfig for AdamW {
fn build_copt(&self, lr: f64) -> Result<COptimizer, TchError> {
COptimizer::adamw(lr, self.beta1, self.beta2, self.wd, self.eps, self.amsgrad)
}
}
#[derive(Debug, Copy, Clone)]
pub struct RmsProp {
pub alpha: f64,
pub eps: f64,
pub wd: f64,
pub momentum: f64,
pub centered: bool,
}
impl Default for RmsProp {
fn default() -> Self {
RmsProp { alpha: 0.99, eps: 1e-8, wd: 0., momentum: 0., centered: false }
}
}
pub fn rms_prop(alpha: f64, eps: f64, wd: f64, momentum: f64, centered: bool) -> RmsProp {
RmsProp { alpha, eps, wd, momentum, centered }
}
impl OptimizerConfig for RmsProp {
fn build_copt(&self, lr: f64) -> Result<COptimizer, TchError> {
COptimizer::rms_prop(lr, self.alpha, self.eps, self.wd, self.momentum, self.centered)
}
}
impl Optimizer {
fn add_missing_variables(&mut self) {
let v = self.variables.lock().unwrap();
if v.trainable_variables.len() > self.variables_in_optimizer {
for var in &v.trainable_variables[self.variables_in_optimizer..] {
self.opt.add_parameters(&var.tensor, var.group).unwrap();
}
self.variables_in_optimizer = v.trainable_variables.len();
}
}
pub fn zero_grad(&mut self) {
self.add_missing_variables();
self.opt.zero_grad().unwrap()
}
pub fn clip_grad_value(&self, max: f64) {
let v = self.variables.lock().unwrap();
for var in v.trainable_variables.iter() {
let _t = var.tensor.grad().clamp_(-max, max);
}
}
pub fn clip_grad_norm(&self, max: f64) {
crate::no_grad(|| {
let v = self.variables.lock().unwrap();
let mut norms = vec![];
for var in v.trainable_variables.iter() {
norms.push(var.tensor.grad().norm());
}
let total_norm = f64::from(Tensor::stack(&norms, 0).norm());
let clip_coef = max / (total_norm + 1e-6);
if clip_coef < 1.0 {
for var in v.trainable_variables.iter() {
let _t = var.tensor.grad().g_mul_scalar_(clip_coef);
}
}
})
}
pub fn step(&mut self) {
self.add_missing_variables();
self.opt.step().unwrap()
}
pub fn backward_step(&mut self, loss: &Tensor) {
self.add_missing_variables();
self.opt.zero_grad().unwrap();
loss.backward();
self.opt.step().unwrap()
}
pub fn backward_step_clip(&mut self, loss: &Tensor, max: f64) {
self.add_missing_variables();
self.opt.zero_grad().unwrap();
loss.backward();
self.clip_grad_value(max);
self.opt.step().unwrap()
}
pub fn backward_step_clip_norm(&mut self, loss: &Tensor, max: f64) {
self.add_missing_variables();
self.opt.zero_grad().unwrap();
loss.backward();
self.clip_grad_norm(max);
self.opt.step().unwrap()
}
pub fn set_lr(&mut self, lr: f64) {
self.opt.set_learning_rate(lr).unwrap()
}
pub fn set_momentum(&mut self, m: f64) {
self.opt.set_momentum(m).unwrap()
}
pub fn set_lr_group(&mut self, group: usize, lr: f64) {
self.opt.set_learning_rate_group(group, lr).unwrap()
}
pub fn set_momentum_group(&mut self, group: usize, m: f64) {
self.opt.set_momentum_group(group, m).unwrap()
}
pub fn trainable_variables(&self) -> Vec<Tensor> {
let variables = self.variables.lock().unwrap();
variables.trainable_variables.iter().map(|v| v.tensor.shallow_clone()).collect()
}
pub fn set_weight_decay(&mut self, weight_decay: f64) {
self.opt.set_weight_decay(weight_decay).unwrap()
}
pub fn set_weight_decay_group(&mut self, group: usize, weight_decay: f64) {
self.opt.set_weight_decay_group(group, weight_decay).unwrap()
}
}