optimizer_param_scheduler.py 7 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

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

25
    def __init__(self, optimizer, max_lr, min_lr,
26
                 warmup_steps, decay_steps, decay_style,
27
                 start_wd, end_wd, wd_incr_style,
28
29
                 use_checkpoint_opt_param_scheduler=True,
                 override_opt_param_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.max_lr = float(max_lr)
35
        self.min_lr = min_lr
mohammad's avatar
mohammad committed
36
        assert self.min_lr >= 0.0
37
        assert self.max_lr >= self.min_lr
mohammad's avatar
mohammad committed
38

39
        self.warmup_steps = warmup_steps
40
        self.num_steps = 0
41
42
43
        self.decay_steps = decay_steps
        assert self.decay_steps > 0
        assert self.warmup_steps < self.decay_steps
mohammad's avatar
mohammad committed
44

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

47
48
49
50
51
52
53
        self.start_wd = start_wd
        self.end_wd = end_wd
        assert self.start_wd >= 0.0
        assert self.end_wd >= self.start_wd
        
        self.wd_incr_style = wd_incr_style

54
55
56
57
        self.override_opt_param_scheduler = override_opt_param_scheduler
        self.use_checkpoint_opt_param_scheduler = use_checkpoint_opt_param_scheduler
        if self.override_opt_param_scheduler:
            assert not self.use_checkpoint_opt_param_scheduler, 'both override and '\
58
                'use-checkpoint are set.'
mohammad's avatar
mohammad committed
59

Mohammad's avatar
Mohammad committed
60
        # Set the learning rate
61
        self.step(0)
Mohammad's avatar
Mohammad committed
62
63
        print_rank_0('> learning rate decay style: {}'.format(self.decay_style))

mohammad's avatar
mohammad committed
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
    def get_wd(self):
        if self.num_steps > self.decay_steps:
            return self.end_wd

        if self.wd_incr_style == 'constant':
            assert self.start_wd == self.end_wd
            return self.end_wd

        decay_ratio = float(self.num_steps) / float(self.decay_steps)
        assert decay_ratio >= 0.0
        assert decay_ratio <= 1.0
        delta_wd = self.end_wd - self.start_wd

        if self.wd_incr_style == 'linear':
            coeff = decay_ratio
        elif self.wd_incr_style == 'cosine':
            coeff = 0.5 * (math.cos(math.pi * (1 - decay_ratio)) + 1.0)
        else:
            raise Exception('{} weight decay increment style is not supported.'.format(
                self.wd_incr_style))

        return self.start_wd + coeff * delta_wd


Raul Puri's avatar
Raul Puri committed
89
    def get_lr(self):
Mohammad's avatar
Mohammad committed
90
91
92
        """Learning rate decay functions from:
              https://openreview.net/pdf?id=BJYwwY9ll pg. 4"""

mohammad's avatar
mohammad committed
93
        # Use linear warmup for the initial part.
94
95
96
        if self.warmup_steps > 0 and self.num_steps <= self.warmup_steps:
            return self.max_lr * float(self.num_steps) / \
                float(self.warmup_steps)
mohammad's avatar
mohammad committed
97
98
99

        # If the learning rate is constant, just return the initial value.
        if self.decay_style == 'constant':
100
            return self.max_lr
mohammad's avatar
mohammad committed
101

102
103
        # For any steps larger than `self.decay_steps`, use `self.min_lr`.
        if self.num_steps > self.decay_steps:
mohammad's avatar
mohammad committed
104
105
106
            return self.min_lr
        
        # If we are done with the warmup period, use the decay style.
107
108
109
        num_steps_ = self.num_steps - self.warmup_steps
        decay_steps_ = self.decay_steps - self.warmup_steps
        decay_ratio = float(num_steps_) / float(decay_steps_)
mohammad's avatar
mohammad committed
110
111
        assert decay_ratio >= 0.0
        assert decay_ratio <= 1.0
112
        delta_lr = self.max_lr - self.min_lr
Mohammad's avatar
Mohammad committed
113
114

        if self.decay_style == 'linear':
mohammad's avatar
mohammad committed
115
            coeff = (1.0 - decay_ratio)
Mohammad's avatar
Mohammad committed
116
        elif self.decay_style == 'cosine':
mohammad's avatar
mohammad committed
117
            coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
Raul Puri's avatar
Raul Puri committed
118
        else:
mohammad's avatar
mohammad committed
119
120
            raise Exception('{} decay style is not supported.'.format(
                self.decay_style))
Mostofa Patwary's avatar
Mostofa Patwary committed
121

mohammad's avatar
mohammad committed
122
123
        return self.min_lr + coeff * delta_lr

Mohammad's avatar
Mohammad committed
124

125
    def step(self, increment):
Mohammad's avatar
Mohammad committed
126
        """Set lr for all parameters groups."""
127
        self.num_steps += increment
Raul Puri's avatar
Raul Puri committed
128
        new_lr = self.get_lr()
129
        new_wd = self.get_wd()
Raul Puri's avatar
Raul Puri committed
130
        for group in self.optimizer.param_groups:
Vijay Korthikanti's avatar
Vijay Korthikanti committed
131
132
            group['lr'] = new_lr * group.get('lr_mult', 1.0)
            group['weight_decay'] = new_wd * group.get('wd_mult', 1.0)
Raul Puri's avatar
Raul Puri committed
133

mohammad's avatar
mohammad committed
134

Raul Puri's avatar
Raul Puri committed
135
    def state_dict(self):
Mohammad's avatar
Mohammad committed
136
        state_dict = {
137
138
139
            'max_lr': self.max_lr,
            'warmup_steps': self.warmup_steps,
            'num_steps': self.num_steps,
Mohammad's avatar
Mohammad committed
140
            'decay_style': self.decay_style,
141
            'decay_steps': self.decay_steps,
Mohammad's avatar
Mohammad committed
142
            'min_lr': self.min_lr
Raul Puri's avatar
Raul Puri committed
143
        }
Mohammad's avatar
Mohammad committed
144
        return state_dict
Raul Puri's avatar
Raul Puri committed
145

mohammad's avatar
mohammad committed
146

Mohammad's avatar
Mohammad committed
147
148
149
    def _check_and_set(self, cls_value, sd_value, name):
        """Auxiliary function for checking the values in the checkpoint and
        setting them."""
150
        if self.override_opt_param_scheduler:
151
152
            print_rank_0(' > overriding {} value to {}'.format(name, cls_value))
            return cls_value
Mohammad's avatar
Mohammad committed
153

154
        if not self.use_checkpoint_opt_param_scheduler:
155
156
157
            assert cls_value == sd_value, \
                f'AnnealingLR: class input value {cls_value} and checkpoint' \
                f'value {sd_value} for {name} do not match'
Mohammad's avatar
Mohammad committed
158
159
160
161
        print_rank_0(' > using checkpoint value {} for {}'.format(sd_value,
                                                                  name))
        return sd_value

mohammad's avatar
mohammad committed
162

Raul Puri's avatar
Raul Puri committed
163
    def load_state_dict(self, sd):
164

165
166
167
168
169
170
171
        if 'start_lr' in sd:
            max_lr_ = sd['start_lr']
        else:
            max_lr_ = sd['max_lr']
        self.max_lr = self._check_and_set(self.max_lr, max_lr_,
                                          'learning rate')
        
Mohammad's avatar
Mohammad committed
172
        self.min_lr = self._check_and_set(self.min_lr, sd['min_lr'],
173
                                          'minimum learning rate')
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188

        if 'warmup_iter' in sd:
            warmup_steps_ = sd['warmup_iter']
        else:
            warmup_steps_ = sd['warmup_steps']
        self.warmup_steps = self._check_and_set(self.warmup_steps,
                                                warmup_steps_,
                                                'warmup iterations')

        if 'end_iter' in sd:
            decay_steps_ = sd['end_iter']
        else:
            decay_steps_ = sd['decay_steps']
        self.decay_steps = self._check_and_set(self.decay_steps, decay_steps_,
                                               'total number of iterations')
Mohammad's avatar
Mohammad committed
189
        self.decay_style = self._check_and_set(self.decay_style,
190
191
192
                                               sd['decay_style'],
                                               'decay style')

193
        if 'num_iters' in sd:
194
            num_steps = sd['num_iters']
195
        else:
196
197
            num_steps = sd['num_steps']
        self.step(increment=num_steps)