forked from rosinality/vq-vae-2-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scheduler.py
executable file
·354 lines (253 loc) · 9.68 KB
/
scheduler.py
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
from math import cos, pi, floor, sin
from torch.optim import lr_scheduler
class CosineLR(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, step_size):
self.lr_min = lr_min
self.lr_max = lr_max
self.step_size = step_size
self.iteration = 0
super().__init__(optimizer, -1)
def get_lr(self):
lr = self.lr_min + 0.5 * (self.lr_max - self.lr_min) * (
1 + cos(self.iteration / self.step_size * pi)
)
self.iteration += 1
if self.iteration == self.step_size:
self.iteration = 0
return [lr for base_lr in self.base_lrs]
class PowerLR(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, warmup):
self.lr_min = lr_min
self.lr_max = lr_max
self.warmup = warmup
self.iteration = 0
super().__init__(optimizer, -1)
def get_lr(self):
if self.iteration < self.warmup:
lr = (
self.lr_min + (self.lr_max - self.lr_min) / self.warmup * self.iteration
)
else:
lr = self.lr_max * (self.iteration - self.warmup + 1) ** -0.5
self.iteration += 1
return [lr for base_lr in self.base_lrs]
class SineLR(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, step_size):
self.lr_min = lr_min
self.lr_max = lr_max
self.step_size = step_size
self.iteration = 0
super().__init__(optimizer, -1)
def get_lr(self):
lr = self.lr_min + (self.lr_max - self.lr_min) * sin(
self.iteration / self.step_size * pi
)
self.iteration += 1
if self.iteration == self.step_size:
self.iteration = 0
return [lr for base_lr in self.base_lrs]
class LinearLR(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, warmup, step_size):
self.lr_min = lr_min
self.lr_max = lr_max
self.step_size = step_size
self.warmup = warmup
self.iteration = 0
super().__init__(optimizer, -1)
def get_lr(self):
if self.iteration < self.warmup:
lr = self.lr_max
else:
lr = self.lr_max + (self.iteration - self.warmup) * (
self.lr_min - self.lr_max
) / (self.step_size - self.warmup)
self.iteration += 1
if self.iteration == self.step_size:
self.iteration = 0
return [lr for base_lr in self.base_lrs]
class CLR(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, step_size):
self.epoch = 0
self.lr_min = lr_min
self.lr_max = lr_max
self.current_lr = lr_min
self.step_size = step_size
super().__init__(optimizer, -1)
def get_lr(self):
cycle = floor(1 + self.epoch / (2 * self.step_size))
x = abs(self.epoch / self.step_size - 2 * cycle + 1)
lr = self.lr_min + (self.lr_max - self.lr_min) * max(0, 1 - x)
self.current_lr = lr
self.epoch += 1
return [lr for base_lr in self.base_lrs]
class Warmup(lr_scheduler._LRScheduler):
def __init__(self, optimizer, model_dim, factor=1, warmup=16000):
self.optimizer = optimizer
self.model_dim = model_dim
self.factor = factor
self.warmup = warmup
self.iteration = 0
super().__init__(optimizer, -1)
def get_lr(self):
self.iteration += 1
lr = (
self.factor
* self.model_dim ** (-0.5)
* min(self.iteration ** (-0.5), self.iteration * self.warmup ** (-1.5))
)
return [lr for base_lr in self.base_lrs]
# Copyright 2019 fastai
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Borrowed from https://github.com/fastai/fastai and changed to make it runs like PyTorch lr scheduler
class CycleAnnealScheduler:
def __init__(
self, optimizer, lr_max, lr_divider, cut_point, step_size, momentum=None
):
self.lr_max = lr_max
self.lr_divider = lr_divider
self.cut_point = step_size // cut_point
self.step_size = step_size
self.iteration = 0
self.cycle_step = int(step_size * (1 - cut_point / 100) / 2)
self.momentum = momentum
self.optimizer = optimizer
def get_lr(self):
if self.iteration > 2 * self.cycle_step:
cut = (self.iteration - 2 * self.cycle_step) / (
self.step_size - 2 * self.cycle_step
)
lr = self.lr_max * (1 + (cut * (1 - 100) / 100)) / self.lr_divider
elif self.iteration > self.cycle_step:
cut = 1 - (self.iteration - self.cycle_step) / self.cycle_step
lr = self.lr_max * (1 + cut * (self.lr_divider - 1)) / self.lr_divider
else:
cut = self.iteration / self.cycle_step
lr = self.lr_max * (1 + cut * (self.lr_divider - 1)) / self.lr_divider
return lr
def get_momentum(self):
if self.iteration > 2 * self.cycle_step:
momentum = self.momentum[0]
elif self.iteration > self.cycle_step:
cut = 1 - (self.iteration - self.cycle_step) / self.cycle_step
momentum = self.momentum[0] + cut * (self.momentum[1] - self.momentum[0])
else:
cut = self.iteration / self.cycle_step
momentum = self.momentum[0] + cut * (self.momentum[1] - self.momentum[0])
return momentum
def step(self):
lr = self.get_lr()
if self.momentum is not None:
momentum = self.get_momentum()
self.iteration += 1
if self.iteration == self.step_size:
self.iteration = 0
for group in self.optimizer.param_groups:
group['lr'] = lr
if self.momentum is not None:
group['betas'] = (momentum, group['betas'][1])
return lr
def anneal_linear(start, end, proportion):
return start + proportion * (end - start)
def anneal_cos(start, end, proportion):
cos_val = cos(pi * proportion) + 1
return end + (start - end) / 2 * cos_val
class Phase:
def __init__(self, start, end, n_iter, anneal_fn):
self.start, self.end = start, end
self.n_iter = n_iter
self.anneal_fn = anneal_fn
self.n = 0
def step(self):
self.n += 1
return self.anneal_fn(self.start, self.end, self.n / self.n_iter)
def reset(self):
self.n = 0
@property
def is_done(self):
return self.n >= self.n_iter
class CycleScheduler:
def __init__(
self,
optimizer,
lr_max,
n_iter,
momentum=(0.95, 0.85),
divider=25,
warmup_proportion=0.3,
phase=('linear', 'cos'),
):
self.optimizer = optimizer
phase1 = int(n_iter * warmup_proportion)
phase2 = n_iter - phase1
lr_min = lr_max / divider
phase_map = {'linear': anneal_linear, 'cos': anneal_cos}
self.lr_phase = [
Phase(lr_min, lr_max, phase1, phase_map[phase[0]]),
Phase(lr_max, lr_min / 1e4, phase2, phase_map[phase[1]]),
]
self.momentum = momentum
if momentum is not None:
mom1, mom2 = momentum
self.momentum_phase = [
Phase(mom1, mom2, phase1, phase_map[phase[0]]),
Phase(mom2, mom1, phase2, phase_map[phase[1]]),
]
else:
self.momentum_phase = []
self.phase = 0
def step(self):
lr = self.lr_phase[self.phase].step()
if self.momentum is not None:
momentum = self.momentum_phase[self.phase].step()
else:
momentum = None
for group in self.optimizer.param_groups:
group['lr'] = lr
if self.momentum is not None:
if 'betas' in group:
group['betas'] = (momentum, group['betas'][1])
else:
group['momentum'] = momentum
if self.lr_phase[self.phase].is_done:
self.phase += 1
if self.phase >= len(self.lr_phase):
for phase in self.lr_phase:
phase.reset()
for phase in self.momentum_phase:
phase.reset()
self.phase = 0
return lr, momentum
class LRFinder(lr_scheduler._LRScheduler):
def __init__(self, optimizer, lr_min, lr_max, step_size, linear=False):
ratio = lr_max / lr_min
self.linear = linear
self.lr_min = lr_min
self.lr_mult = (ratio / step_size) if linear else ratio ** (1 / step_size)
self.iteration = 0
self.lrs = []
self.losses = []
super().__init__(optimizer, -1)
def get_lr(self):
lr = (
self.lr_mult * self.iteration
if self.linear
else self.lr_mult ** self.iteration
)
lr = self.lr_min + lr if self.linear else self.lr_min * lr
self.iteration += 1
self.lrs.append(lr)
return [lr for base_lr in self.base_lrs]
def record(self, loss):
self.losses.append(loss)
def save(self, filename):
with open(filename, 'w') as f:
for lr, loss in zip(self.lrs, self.losses):
f.write('{},{}\n'.format(lr, loss))