optimizer.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import torch
  2. import numpy as np
  3. class ScheduledOptim:
  4. """ A simple wrapper class for learning rate scheduling """
  5. def __init__(self, model, train_config, model_config, current_step):
  6. self._optimizer = torch.optim.Adam(
  7. model.parameters(),
  8. betas=train_config["optimizer"]["betas"],
  9. eps=train_config["optimizer"]["eps"],
  10. weight_decay=train_config["optimizer"]["weight_decay"],
  11. )
  12. self.n_warmup_steps = train_config["optimizer"]["warm_up_step"]
  13. self.anneal_steps = train_config["optimizer"]["anneal_steps"]
  14. self.anneal_rate = train_config["optimizer"]["anneal_rate"]
  15. self.current_step = current_step
  16. self.init_lr = np.power(model_config["transformer"]["encoder_hidden"], -0.5)
  17. def step_and_update_lr(self):
  18. self._update_learning_rate()
  19. self._optimizer.step()
  20. def zero_grad(self):
  21. # print(self.init_lr)
  22. self._optimizer.zero_grad()
  23. def load_state_dict(self, path):
  24. self._optimizer.load_state_dict(path)
  25. def _get_lr_scale(self):
  26. lr = np.min(
  27. [
  28. np.power(self.current_step, -0.5),
  29. np.power(self.n_warmup_steps, -1.5) * self.current_step,
  30. ]
  31. )
  32. for s in self.anneal_steps:
  33. if self.current_step > s:
  34. lr = lr * self.anneal_rate
  35. return lr
  36. def _update_learning_rate(self):
  37. """ Learning rate scheduling per step """
  38. self.current_step += 1
  39. lr = self.init_lr * self._get_lr_scale()
  40. for param_group in self._optimizer.param_groups:
  41. param_group["lr"] = lr