You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.5 KiB
51 lines
1.5 KiB
6 years ago
|
import math
|
||
|
import torch
|
||
|
|
||
|
from .scheduler import Scheduler
|
||
|
|
||
|
|
||
|
class StepLRScheduler(Scheduler):
|
||
|
"""
|
||
|
"""
|
||
|
|
||
|
def __init__(self,
|
||
|
optimizer: torch.optim.Optimizer,
|
||
6 years ago
|
decay_t: int,
|
||
6 years ago
|
decay_rate: float = 1.,
|
||
6 years ago
|
warmup_t=0,
|
||
6 years ago
|
warmup_lr_init=0,
|
||
6 years ago
|
t_in_epochs=True,
|
||
6 years ago
|
initialize=True) -> None:
|
||
|
super().__init__(optimizer, param_group_field="lr", initialize=initialize)
|
||
|
|
||
6 years ago
|
self.decay_t = decay_t
|
||
6 years ago
|
self.decay_rate = decay_rate
|
||
6 years ago
|
self.warmup_t = warmup_t
|
||
6 years ago
|
self.warmup_lr_init = warmup_lr_init
|
||
6 years ago
|
self.t_in_epochs = t_in_epochs
|
||
|
if self.warmup_t:
|
||
|
self.warmup_steps = [(v - warmup_lr_init) / self.warmup_t for v in self.base_values]
|
||
6 years ago
|
super().update_groups(self.warmup_lr_init)
|
||
|
else:
|
||
|
self.warmup_steps = [1 for _ in self.base_values]
|
||
|
|
||
6 years ago
|
def _get_lr(self, t):
|
||
|
if t < self.warmup_t:
|
||
|
lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]
|
||
6 years ago
|
else:
|
||
6 years ago
|
lrs = [v * (self.decay_rate ** (t // self.decay_t))
|
||
|
for v in self.base_values]
|
||
6 years ago
|
return lrs
|
||
|
|
||
6 years ago
|
def get_epoch_values(self, epoch: int):
|
||
|
if self.t_in_epochs:
|
||
|
return self._get_lr(epoch)
|
||
6 years ago
|
else:
|
||
6 years ago
|
return None
|
||
6 years ago
|
|
||
6 years ago
|
def get_update_values(self, num_updates: int):
|
||
|
if not self.t_in_epochs:
|
||
|
return self._get_lr(num_updates)
|
||
|
else:
|
||
|
return None
|