learning_rates.py 5.4 KB
Newer Older
Raul Puri's avatar
Raul Puri committed
1
# coding=utf-8
Mohammad's avatar
Mohammad committed
2
# Copyright (c) 2020, NVIDIA CORPORATION.  All rights reserved.
Raul Puri's avatar
Raul Puri committed
3
4
5
6
7
8
9
10
11
12
13
14
15
#
# 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.

Mohammad's avatar
Mohammad committed
16
17
"""Learning rate decay functions."""

Raul Puri's avatar
Raul Puri committed
18
19
import math

20
from megatron import print_rank_0
21

Mohammad's avatar
Mohammad committed
22
23
class AnnealingLR(object):
    """Anneals the learning rate."""
Raul Puri's avatar
Raul Puri committed
24

Mohammad's avatar
Mohammad committed
25
26
27
    def __init__(self, optimizer, start_lr,
                 warmup_iter, total_iters,
                 decay_style, last_iter, min_lr=0.0,
28
29
                 use_checkpoint_lr_scheduler=True,
                 override_lr_scheduler=False):
Mohammad's avatar
Mohammad committed
30
31

        # Class values.
Raul Puri's avatar
Raul Puri committed
32
        self.optimizer = optimizer
mohammad's avatar
mohammad committed
33
34

        self.start_lr = float(start_lr)
35
        self.min_lr = min_lr
mohammad's avatar
mohammad committed
36
37
38
        assert self.min_lr >= 0.0
        assert self.start_lr >= self.min_lr

Raul Puri's avatar
Raul Puri committed
39
        self.warmup_iter = warmup_iter
Mohammad's avatar
Mohammad committed
40
41
42
        self.num_iters = last_iter
        self.end_iter = total_iters
        assert self.end_iter > 0
mohammad's avatar
mohammad committed
43
44
        assert self.warmup_iter < self.end_iter

Mohammad's avatar
Mohammad committed
45
        self.decay_style = decay_style
mohammad's avatar
mohammad committed
46

47
48
49
50
51
        self.override_lr_scheduler = override_lr_scheduler
        self.use_checkpoint_lr_scheduler = use_checkpoint_lr_scheduler
        if self.override_lr_scheduler:
            assert not self.use_checkpoint_lr_scheduler, 'both override and '\
                'use-checkpoint are set.'
mohammad's avatar
mohammad committed
52

Mohammad's avatar
Mohammad committed
53
        # Set the learning rate
Raul Puri's avatar
Raul Puri committed
54
        self.step(self.num_iters)
Mohammad's avatar
Mohammad committed
55
56
57

        print_rank_0('> learning rate decay style: {}'.format(self.decay_style))

mohammad's avatar
mohammad committed
58

Raul Puri's avatar
Raul Puri committed
59
    def get_lr(self):
Mohammad's avatar
Mohammad committed
60
61
62
        """Learning rate decay functions from:
              https://openreview.net/pdf?id=BJYwwY9ll pg. 4"""

mohammad's avatar
mohammad committed
63
        # Use linear warmup for the initial part.
Raul Puri's avatar
Raul Puri committed
64
        if self.warmup_iter > 0 and self.num_iters <= self.warmup_iter:
mohammad's avatar
mohammad committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
            return self.start_lr * float(self.num_iters) / \
                float(self.warmup_iter)

        # If the learning rate is constant, just return the initial value.
        if self.decay_style == 'constant':
            return self.start_lr

        # For any iterations larger than `self.end_iter`, use `self.min_lr`.
        if self.num_iters > self.end_iter:
            return self.min_lr
        
        # If we are done with the warmup period, use the decay style.
        current_iter = self.num_iters - self.warmup_iter
        decay_iters = self.end_iter - self.warmup_iter
        decay_ratio = float(current_iter) / float(decay_iters)
        assert decay_ratio >= 0.0
        assert decay_ratio <= 1.0
        delta_lr = self.start_lr - self.min_lr
Mohammad's avatar
Mohammad committed
83
84

        if self.decay_style == 'linear':
mohammad's avatar
mohammad committed
85
            coeff = (1.0 - decay_ratio)
Mohammad's avatar
Mohammad committed
86
        elif self.decay_style == 'cosine':
mohammad's avatar
mohammad committed
87
            coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
Raul Puri's avatar
Raul Puri committed
88
        else:
mohammad's avatar
mohammad committed
89
90
91
92
93
            raise Exception('{} decay style is not supported.'.format(
                self.decay_style))
       
        return self.min_lr + coeff * delta_lr

Mohammad's avatar
Mohammad committed
94

Raul Puri's avatar
Raul Puri committed
95
    def step(self, step_num=None):
Mohammad's avatar
Mohammad committed
96
        """Set lr for all parameters groups."""
Raul Puri's avatar
Raul Puri committed
97
98
99
100
101
102
103
        if step_num is None:
            step_num = self.num_iters + 1
        self.num_iters = step_num
        new_lr = self.get_lr()
        for group in self.optimizer.param_groups:
            group['lr'] = new_lr

mohammad's avatar
mohammad committed
104

Raul Puri's avatar
Raul Puri committed
105
    def state_dict(self):
Mohammad's avatar
Mohammad committed
106
107
108
109
110
111
112
        state_dict = {
            'start_lr': self.start_lr,
            'warmup_iter': self.warmup_iter,
            'num_iters': self.num_iters,
            'decay_style': self.decay_style,
            'end_iter': self.end_iter,
            'min_lr': self.min_lr
Raul Puri's avatar
Raul Puri committed
113
        }
Mohammad's avatar
Mohammad committed
114
        return state_dict
Raul Puri's avatar
Raul Puri committed
115

mohammad's avatar
mohammad committed
116

Mohammad's avatar
Mohammad committed
117
118
119
    def _check_and_set(self, cls_value, sd_value, name):
        """Auxiliary function for checking the values in the checkpoint and
        setting them."""
120
121
122
        if self.override_lr_scheduler:
            print_rank_0(' > overriding {} value to {}'.format(name, cls_value))
            return cls_value
Mohammad's avatar
Mohammad committed
123
124
125
126
127
128
129
130

        if not self.use_checkpoint_lr_scheduler:
            assert cls_value == sd_value, 'AnnealingLR: class input value' \
                'and checkpoint values for {} do not match'.format(name)
        print_rank_0(' > using checkpoint value {} for {}'.format(sd_value,
                                                                  name))
        return sd_value

mohammad's avatar
mohammad committed
131

Raul Puri's avatar
Raul Puri committed
132
    def load_state_dict(self, sd):
133

Mohammad's avatar
Mohammad committed
134
        self.start_lr = self._check_and_set(self.start_lr, sd['start_lr'],
135
                                            'learning rate')
Mohammad's avatar
Mohammad committed
136
        self.min_lr = self._check_and_set(self.min_lr, sd['min_lr'],
137
                                          'minimum learning rate')
Mohammad's avatar
Mohammad committed
138
        self.warmup_iter = self._check_and_set(self.warmup_iter,
139
140
                                               sd['warmup_iter'],
                                               'warmup iterations')
Mohammad's avatar
Mohammad committed
141
        self.end_iter = self._check_and_set(self.end_iter, sd['end_iter'],
142
                                            'total number of iterations')
Mohammad's avatar
Mohammad committed
143
        self.decay_style = self._check_and_set(self.decay_style,
144
145
146
                                               sd['decay_style'],
                                               'decay style')

Raul Puri's avatar
Raul Puri committed
147
148
        self.num_iters = sd['num_iters']
        self.step(self.num_iters)