learning_rates.py 7.04 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
Mostofa Patwary's avatar
Mostofa Patwary committed
21
from megatron import get_args
22

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

26
    def __init__(self, optimizer, max_lr, min_lr,
27
                 warmup_steps, decay_steps, decay_style,
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.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
        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
54
        self.step(0)
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"""

Mostofa Patwary's avatar
Mostofa Patwary committed
63
        #print_rank_0("self.warmup_steps {} self.num_steps {} self.decay_steps {} self.min_lr {} self.maxlr {}".format(self.warmup_steps, self.num_steps, self.decay_steps, self.min_lr, self.max_lr))
mohammad's avatar
mohammad committed
64
        # Use linear warmup for the initial part.
65
66
67
        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
68
69
70

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

73
74
        # For any steps larger than `self.decay_steps`, use `self.min_lr`.
        if self.num_steps > self.decay_steps:
mohammad's avatar
mohammad committed
75
76
77
            return self.min_lr
        
        # If we are done with the warmup period, use the decay style.
78
79
80
        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
81
82
        assert decay_ratio >= 0.0
        assert decay_ratio <= 1.0
83
        delta_lr = self.max_lr - self.min_lr
Mohammad's avatar
Mohammad committed
84
85

        if self.decay_style == 'linear':
mohammad's avatar
mohammad committed
86
            coeff = (1.0 - decay_ratio)
Mohammad's avatar
Mohammad committed
87
        elif self.decay_style == 'cosine':
mohammad's avatar
mohammad committed
88
            coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
Raul Puri's avatar
Raul Puri committed
89
        else:
mohammad's avatar
mohammad committed
90
91
            raise Exception('{} decay style is not supported.'.format(
                self.decay_style))
Mostofa Patwary's avatar
Mostofa Patwary committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

        args = get_args()

        if args.override_lr_new:
            mod_num_steps_ = min(self.num_steps, self.decay_steps - self.warmup_steps)
            mod_num_steps_ = mod_num_steps_ - self.warmup_steps
            use_lr = delta_lr * float(self.decay_steps - mod_num_steps_) / float(self.decay_steps)
            should_use_lr = self.min_lr + coeff * delta_lr
            print_rank_0("num_steps {} decay_steps {} decay_ratio {} coeff {} delta_lr {} use lr {} should_use_lr {} self.warmup_steps {} self.num_steps {} self.decay_steps {}".format(num_steps_, decay_steps_, decay_ratio, coeff, delta_lr, use_lr, should_use_lr, self.warmup_steps, self.num_steps, self.decay_steps))
        else:
            use_lr = self.min_lr + coeff * delta_lr
            print_rank_0("num_steps {} decay_steps {} decay_ratio {} coeff {} delta_lr {} use lr {} self.warmup_steps {} self.num_steps {} self.decay_steps {}".format(num_steps_, decay_steps_, decay_ratio, coeff, delta_lr, use_lr, self.warmup_steps, self.num_steps, self.decay_steps))

        return use_lr

mohammad's avatar
mohammad committed
107
108
        return self.min_lr + coeff * delta_lr

Mohammad's avatar
Mohammad committed
109

110
    def step(self, increment):
Mohammad's avatar
Mohammad committed
111
        """Set lr for all parameters groups."""
112
        self.num_steps += increment
Raul Puri's avatar
Raul Puri committed
113
114
115
116
        new_lr = self.get_lr()
        for group in self.optimizer.param_groups:
            group['lr'] = new_lr

mohammad's avatar
mohammad committed
117

Raul Puri's avatar
Raul Puri committed
118
    def state_dict(self):
Mohammad's avatar
Mohammad committed
119
        state_dict = {
120
121
122
            'max_lr': self.max_lr,
            'warmup_steps': self.warmup_steps,
            'num_steps': self.num_steps,
Mohammad's avatar
Mohammad committed
123
            'decay_style': self.decay_style,
124
            'decay_steps': self.decay_steps,
Mohammad's avatar
Mohammad committed
125
            'min_lr': self.min_lr
Raul Puri's avatar
Raul Puri committed
126
        }
Mohammad's avatar
Mohammad committed
127
        return state_dict
Raul Puri's avatar
Raul Puri committed
128

mohammad's avatar
mohammad committed
129

Mohammad's avatar
Mohammad committed
130
131
132
    def _check_and_set(self, cls_value, sd_value, name):
        """Auxiliary function for checking the values in the checkpoint and
        setting them."""
133
134
135
        if self.override_lr_scheduler:
            print_rank_0(' > overriding {} value to {}'.format(name, cls_value))
            return cls_value
Mohammad's avatar
Mohammad committed
136
137

        if not self.use_checkpoint_lr_scheduler:
138
139
140
            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
141
142
143
144
        print_rank_0(' > using checkpoint value {} for {}'.format(sd_value,
                                                                  name))
        return sd_value

mohammad's avatar
mohammad committed
145

Raul Puri's avatar
Raul Puri committed
146
    def load_state_dict(self, sd):
147

148
149
150
151
152
153
154
        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
155
        self.min_lr = self._check_and_set(self.min_lr, sd['min_lr'],
156
                                          'minimum learning rate')
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171

        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
172
        self.decay_style = self._check_and_set(self.decay_style,
173
174
175
                                               sd['decay_style'],
                                               'decay style')

176
        if 'num_iters' in sd:
177
            num_steps = sd['num_iters']
178
        else:
179
180
            num_steps = sd['num_steps']
        self.step(increment=num_steps)