lr_scheduler.py 10.2 KB
Newer Older
yuguo960516's avatar
bloom  
yuguo960516 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# coding=utf-8
# Copyright 2021 The OneFlow Authors. All rights reserved.
#
# 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.

import logging

import oneflow as flow

logger = logging.getLogger(__name__)


def WarmupCosineLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    warmup_factor: float,
    warmup_iter: int,
    alpha: float = 0.0,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases following
    the values of the Cosine function between the initial lr set in the
    optimizer to 0, after a warmup period during which it increases linearly
    between 0 and the initial lr set in the optimizer.

    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        alpha (float, optional): The learning rate scale factor (:math:`\\alpha`). Defaults to 0.0.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in
            the first epoch and then inreases linearly to reach 1. Defaults to "linear".
    """
    cosine_decay_lr = flow.optim.lr_scheduler.CosineDecayLR(
        optimizer, decay_steps=max_iter, alpha=alpha
    )
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return CosineLR")
        return cosine_decay_lr
    elif warmup_iter > max_iter:
        logger.warning("warmup iters is larger than the total training iters")
    warmup_cosine_lr = flow.optim.lr_scheduler.WarmUpLR(
        cosine_decay_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_cosine_lr


def WarmupCosineAnnealingLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    warmup_factor: float,
    warmup_iter: int,
    eta_min: float = 0.0,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases following
    the values of the Cosine Annealing function between the initial
    lr set in the optimizer to 0, after a warmup period during which
    it increases linearly between 0 and the initial lr set in the optimizer.

    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        eta_min (float, optional): Minimum learning rate. Defaults to 0.0.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in the first epoch
            and then inreases linearly to reach 1. Defaults to "linear".
    """
    cosine_annealing_lr = flow.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=max_iter, eta_min=eta_min
    )
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return CosineAnnealingLR")
        return cosine_annealing_lr
    warmup_cosine_annealing_lr = flow.optim.lr_scheduler.WarmUpLR(
        cosine_annealing_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_cosine_annealing_lr


def WarmupStepLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    warmup_factor: float,
    warmup_iter: int,
    step_size: int,
    gamma: float = 0.1,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases following the values of the Step
    function between the initial lr set in the optimizer to 0, after a warmup period during which
    it increases linearly between 0 and the initial lr set in the optimizer.
    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        step_size (int): Period of learning rate decay.
        gamma (float, optional): Multiplicative factor of learning rate decay. Defaults to 0.1.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in the first
            epoch and then inreases linearly to reach 1. Defaults to "linear".
    """
    step_lr = flow.optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma)
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return StepLR")
        return step_lr
    warmup_step_lr = flow.optim.lr_scheduler.WarmUpLR(
        step_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_step_lr


def WarmupMultiStepLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    warmup_factor: float,
    warmup_iter: int,
    milestones: list,
    gamma: float = 0.1,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases following the values of the MultiStep
    function between the initial lr set in the optimizer to 0, after a warmup period during which
    it increases linearly between 0 and the initial lr set in the optimizer.

    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        milestones (list): List of step indices. Must be increasing.
        gamma (float, optional): Multiplicative factor of learning rate decay. Defaults to 0.1.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in the first
            epoch and then inreases linearly to reach 1. Defaults to "linear".
    """
    multistep_lr = flow.optim.lr_scheduler.MultiStepLR(
        optimizer, milestones=milestones, gamma=gamma
    )
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return MultiStepLR")
        return multistep_lr
    warmup_multistep_lr = flow.optim.lr_scheduler.WarmUpLR(
        multistep_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_multistep_lr


def WarmupExponentialLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    gamma: float,
    warmup_factor: float,
    warmup_iter: int,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases following the values of
    the Exponential function between the initial lr set in the optimizer to 0,
    after a warmup period during which it increases linearly between 0 and the
    initial lr set in the optimizer.

    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        gamma (float): Multiplicative factor of learning rate decay.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in the first epoch
            and then inreases linearly to reach 1. Defaults to "linear".
    """
    exponential_lr = flow.optim.lr_scheduler.ExponentialLR(optimizer, gamma=gamma)
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return ExponentialLR")
        return exponential_lr
    warmup_exponential_lr = flow.optim.lr_scheduler.WarmUpLR(
        exponential_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_exponential_lr


def WarmupPolynomialLR(
    optimizer: flow.optim.Optimizer,
    max_iter: int,
    warmup_factor: float,
    warmup_iter: int,
    end_learning_rate: float = 0.0001,
    power: float = 1.0,
    cycle: bool = False,
    warmup_method: str = "linear",
):
    """Create a schedule with a learning rate that decreases as a polynomial decay from
    the initial lr set in the optimizer to end lr defined by `lr_end`,
    after a warmup period during which it increases linearly from 0 to the
    initial lr set in the optimizer.


    Args:
        optimizer (flow.optim.Optimizer): Wrapped optimizer.
        max_iter (int): Total training iters.
        warmup_factor (float): The warmup factor.
        warmup_iter (int): The number of warmup steps.
        end_learning_rate (float, optional): The final learning rate. Defaults to 0.0001.
        power (float, optional): The power of polynomial. Defaults to 1.0.
        cycle (bool, optional): If cycle is True, the scheduler will decay the learning rate
            every decay steps. Defaults to False.
        warmup_method (str, optional): The method of warmup, you can choose "linear" or "constant".
            In linear mode, the multiplication factor starts with warmup_factor in the first
            epoch and then inreases linearly to reach 1. Defaults to "linear".
    """
    polynomial_lr = flow.optim.lr_scheduler.PolynomialLR(
        optimizer,
        decay_batch=max_iter,
        end_learning_rate=end_learning_rate,
        power=power,
        cycle=cycle,
    )
    if warmup_iter == 0:
        logger.warning("warmup iters equals to zero, return PolynomialLR")
        return polynomial_lr
    warmup_polynomial_lr = flow.optim.lr_scheduler.WarmUpLR(
        polynomial_lr,
        warmup_factor=warmup_factor,
        warmup_iters=warmup_iter,
        warmup_method=warmup_method,
    )
    return warmup_polynomial_lr