learning_rates.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Learning rate decay functions."""
  16. import math
  17. from megatron import print_rank_0
  18. class AnnealingLR(object):
  19. """Anneals the learning rate."""
  20. def __init__(self, optimizer, max_lr, min_lr,
  21. warmup_steps, decay_steps, decay_style,
  22. use_checkpoint_lr_scheduler=True,
  23. override_lr_scheduler=False):
  24. # Class values.
  25. self.optimizer = optimizer
  26. self.max_lr = float(max_lr)
  27. self.min_lr = min_lr
  28. assert self.min_lr >= 0.0
  29. assert self.max_lr >= self.min_lr
  30. self.warmup_steps = warmup_steps
  31. self.num_steps = 0
  32. self.decay_steps = decay_steps
  33. assert self.decay_steps > 0
  34. assert self.warmup_steps < self.decay_steps
  35. self.decay_style = decay_style
  36. self.override_lr_scheduler = override_lr_scheduler
  37. self.use_checkpoint_lr_scheduler = use_checkpoint_lr_scheduler
  38. if self.override_lr_scheduler:
  39. assert not self.use_checkpoint_lr_scheduler, 'both override and '\
  40. 'use-checkpoint are set.'
  41. # Set the learning rate
  42. self.step(0)
  43. print_rank_0('> learning rate decay style: {}'.format(self.decay_style))
  44. def get_lr(self):
  45. """Learning rate decay functions from:
  46. https://openreview.net/pdf?id=BJYwwY9ll pg. 4"""
  47. # Use linear warmup for the initial part.
  48. if self.warmup_steps > 0 and self.num_steps <= self.warmup_steps:
  49. return self.max_lr * float(self.num_steps) / \
  50. float(self.warmup_steps)
  51. # If the learning rate is constant, just return the initial value.
  52. if self.decay_style == 'constant':
  53. return self.max_lr
  54. # For any steps larger than `self.decay_steps`, use `self.min_lr`.
  55. if self.num_steps > self.decay_steps:
  56. return self.min_lr
  57. # If we are done with the warmup period, use the decay style.
  58. num_steps_ = self.num_steps - self.warmup_steps
  59. decay_steps_ = self.decay_steps - self.warmup_steps
  60. decay_ratio = float(num_steps_) / float(decay_steps_)
  61. assert decay_ratio >= 0.0
  62. assert decay_ratio <= 1.0
  63. delta_lr = self.max_lr - self.min_lr
  64. if self.decay_style == 'linear':
  65. coeff = (1.0 - decay_ratio)
  66. elif self.decay_style == 'cosine':
  67. coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
  68. else:
  69. raise Exception('{} decay style is not supported.'.format(
  70. self.decay_style))
  71. return self.min_lr + coeff * delta_lr
  72. def step(self, increment):
  73. """Set lr for all parameters groups."""
  74. self.num_steps += increment
  75. new_lr = self.get_lr()
  76. for group in self.optimizer.param_groups:
  77. group['lr'] = new_lr
  78. def state_dict(self):
  79. state_dict = {
  80. 'max_lr': self.max_lr,
  81. 'warmup_steps': self.warmup_steps,
  82. 'num_steps': self.num_steps,
  83. 'decay_style': self.decay_style,
  84. 'decay_steps': self.decay_steps,
  85. 'min_lr': self.min_lr
  86. }
  87. return state_dict
  88. def _check_and_set(self, cls_value, sd_value, name):
  89. """Auxiliary function for checking the values in the checkpoint and
  90. setting them."""
  91. if self.override_lr_scheduler:
  92. print_rank_0(' > overriding {} value to {}'.format(name, cls_value))
  93. return cls_value
  94. if not self.use_checkpoint_lr_scheduler:
  95. assert cls_value == sd_value, \
  96. f'AnnealingLR: class input value {cls_value} and checkpoint' \
  97. f'value {sd_value} for {name} do not match'
  98. print_rank_0(' > using checkpoint value {} for {}'.format(sd_value,
  99. name))
  100. return sd_value
  101. def load_state_dict(self, sd):
  102. if 'start_lr' in sd:
  103. max_lr_ = sd['start_lr']
  104. else:
  105. max_lr_ = sd['max_lr']
  106. self.max_lr = self._check_and_set(self.max_lr, max_lr_,
  107. 'learning rate')
  108. self.min_lr = self._check_and_set(self.min_lr, sd['min_lr'],
  109. 'minimum learning rate')
  110. if 'warmup_iter' in sd:
  111. warmup_steps_ = sd['warmup_iter']
  112. else:
  113. warmup_steps_ = sd['warmup_steps']
  114. self.warmup_steps = self._check_and_set(self.warmup_steps,
  115. warmup_steps_,
  116. 'warmup iterations')
  117. if 'end_iter' in sd:
  118. decay_steps_ = sd['end_iter']
  119. else:
  120. decay_steps_ = sd['decay_steps']
  121. self.decay_steps = self._check_and_set(self.decay_steps, decay_steps_,
  122. 'total number of iterations')
  123. self.decay_style = self._check_and_set(self.decay_style,
  124. sd['decay_style'],
  125. 'decay style')
  126. if 'num_iters' in sd:
  127. num_steps = sd['num_iters']
  128. else:
  129. num_steps = sd['num_steps']
  130. self.step(increment=num_steps)