learning_rate.py 9.24 KB
Newer Older
mibaumgartner's avatar
mibaumgartner 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
258
259
260
261
262
263
264
265
266
267
268
269
270
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany

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 math
from typing import List, Union, Sequence

from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.optimizer import Optimizer

from loguru import logger


def linear_warm_up(
    iteration: int,
    initial_lr: float,
    num_iterations: int,
    final_lr: float,
    ) -> float:
    """
    Linear learning rate warm up

    Args:
        iteration: current iteration
        initial_lr: initial learning rate for poly lr
        num_iterations: total number of iterations for of warmup
        final_lr: final learning rate of warmup

    Returns:
        float: learning rate
    """
    assert final_lr > initial_lr
    if iteration >= num_iterations:
        logger.warning(f"WarmUp was stepped too often, {iteration} "
                f"but only {num_iterations} were expected!")
    
    return initial_lr + (final_lr - initial_lr) * (float(iteration) / float(num_iterations))


def poly_lr(
    iteration: int,
    initial_lr: float,
    num_iterations: int,
    gamma: float,
    ) -> float:
    """
    initial_lr * (1 - epoch / max_epochs) ** gamma

    Adapted from
    https://github.com/MIC-DKFZ/nnUNet/blob/master/nnunet/training/learning_rate/poly_lr.py
    https://arxiv.org/abs/1904.08128

    Args:
        iteration: current iteration
        initial_lr: initial learning rate for poly lr
        num_iterations: total number of iterations of poly lr
        gamma: gamma value

    Returns:
        float: learning rate
    """
    if iteration >= num_iterations:
        logger.warning(f"PolyLR was stepped too often, {iteration} "
                f"but only {num_iterations} were expected! "
                f"Using {num_iterations - 1} for lr computation.")
        iteration = num_iterations - 1
    return initial_lr * (1 - iteration / float(num_iterations)) ** gamma


def cyclic_linear_lr(
    iteration: int,
    num_iterations_cycle: int,
    initial_lr: float,
    final_lr: float,
    ) -> float:
    """
    Linearly cycle learning rate

    Args:
        iteration: current iteration
        num_iterations_cycle: number of iterations per cycle
        initial_lr: learning rate to start cycle
        final_lr: learning rate to end cycle

    Returns:
        float: learning rate
    """
    cycle_iteration = int(iteration) % num_iterations_cycle
    lr_multiplier = 1 - (cycle_iteration / float(num_iterations_cycle))
    return initial_lr + (final_lr - initial_lr) * lr_multiplier


def cosine_annealing_lr(
    iteration: int,
    num_iterations: int,
    initial_lr: float,
    final_lr: float,
):
    """
    Cosine annealing NO restarts

    Args:
        iteration: current iteration
        num_iterations: total number of iterations of coine lr
        initial_lr: learning rate to start
        final_lr: learning rate to end

    Returns:
        float: learning rate
    """
    return final_lr + 0.5 * (initial_lr - final_lr) * (1 + \
        math.cos(math.pi * float(iteration) / float(num_iterations)))


class LinearWarmupPolyLR(_LRScheduler):
    def __init__(self,
                 optimizer: Optimizer,
                 warm_iterations: int,
                 warm_lr: Union[float, Sequence[float]],
                 poly_gamma: float,
                 num_iterations: int,
                 last_epoch: int = -1,
                 ) -> None:
        """
        Linear Warm Up LR -> Poly LR -> Cycle LR

        Args:
            optimizer: optimizer for lr scheduling
            warm_iterations: number of warmup iterations
            warm_lr: initial learning rate of warm up
            poly_gamma: gamma of poly lr
            num_iterations: total number of iterations (including warmup)
            last_epoch: The index of the last epoch. Defaults to -1.
        """
        self.num_iterations = num_iterations
        # warmup
        self.warm_iterations = warm_iterations

        if not isinstance(warm_lr, list) and not isinstance(warm_lr, tuple):
            self.warm_lr = [warm_lr] * len(optimizer.param_groups)
        else:
            if len(warm_lr) != len(optimizer.param_groups):
                raise ValueError("Expected {} warm_lr, but got {}".format(
                    len(optimizer.param_groups), len(warm_lr)))
            self.warm_lr = [warm_lr]

        # poly lr
        self.poly_iterations = self.num_iterations - self.warm_iterations
        self.poly_gamma = poly_gamma
        super().__init__(optimizer, last_epoch=last_epoch)

    def get_lr(self) -> List[float]:
        """
        Compute current learning rate for each param group
        """
        if self.last_epoch < self.warm_iterations:
            # warm up period
            lrs = [linear_warm_up(
                iteration=self._step_count,
                initial_lr=self.warm_lr[idx],
                num_iterations=self.warm_iterations,
                final_lr=base_lr,
                ) for idx, base_lr in enumerate(self.base_lrs)]
        else:
            # poly lr phase
            lrs = [poly_lr(
                iteration=self._step_count - self.warm_iterations,
                initial_lr=base_lr,
                num_iterations=self.poly_iterations,
                gamma=self.poly_gamma,
            ) for idx, base_lr in enumerate(self.base_lrs)]
        return lrs


class CycleLinear(_LRScheduler):
    def __init__(self,
                 optimizer: Optimizer,
                 cycle_num_iterations: int,
                 cycle_initial_lr: Union[float, Sequence[float]],
                 cycle_final_lr:Union[float, Sequence[float]],
                 last_epoch: int = -1,
                 ) -> None:
        """
        Cyclic learning rates with linear decay

        Args:
            optimizer: optimizer for lr scheduling
            cycle_num_iterations: number of iterations per cycle
            cycle_initial_lr: initial learning rate of cycle
            cycle_final_lr: final learning rate of cycle
            last_epoch: The index of the last epoch. Defaults to -1.
        """
        # cycle linear lr
        self.cycle_num_iterations = cycle_num_iterations

        if not isinstance(cycle_initial_lr, list) and not isinstance(cycle_initial_lr, tuple):
            self.cycle_initial_lr = [cycle_initial_lr] * len(optimizer.param_groups)
        else:
            if len(cycle_initial_lr) != len(optimizer.param_groups):
                raise ValueError("Expected {} cycle_initial_lr, but got {}".format(
                    len(optimizer.param_groups), len(cycle_initial_lr)))
            self.cycle_initial_lr = [cycle_initial_lr]

        if not isinstance(cycle_final_lr, list) and not isinstance(cycle_final_lr, tuple):
            self.cycle_final_lr = [cycle_final_lr] * len(optimizer.param_groups)
        else:
            if len(cycle_final_lr) != len(optimizer.param_groups):
                raise ValueError("Expected {} cycle_final_lr, but got {}".format(
                    len(optimizer.param_groups), len(cycle_final_lr)))
            self.cycle_final_lr = [cycle_final_lr]
        super().__init__(optimizer, last_epoch=last_epoch)

    def get_lr(self) -> List[float]:
        """
        Compute current learning rate for each param group
        """
        lrs = [cyclic_linear_lr(
            iteration=max(self._step_count - 1, 0), # init steps once
            num_iterations_cycle=self.cycle_num_iterations,
            initial_lr=self.cycle_initial_lr[idx],
            final_lr=self.cycle_final_lr[idx],
        ) for idx, base_lr in enumerate(self.base_lrs)]
        return lrs


class WarmUpExponential(_LRScheduler):
    def __init__(self,
                 optimizer: Optimizer,
                 beta2: float,
                 last_epoch: int = -1,
                 ):
        """
        Expoenential learning rate warmup
        warmup_lr = base_lr * 1 - exp(- (1 - beta2) * t)
        for 2 * (1 - beta2)^(-1) iterations
        `On the adequacy of untuned warmup for adaptive optimization`
        https://arxiv.org/abs/1910.04209

        Args:
            optimizer: optimizer to schedule lr from (best used with Adam,
                AdamW)
            beta2: second beta param of Adam optimizer.
            last_epoch: The index of the last epoch. Defaults to -1.
        """
        self.iterations = int(2. * (1. / (1. - beta2)))
        self.beta2 = beta2
        logger.info(f"Running exponential warmup for {self.iterations} iterations")
        self.finished = False

        super().__init__(optimizer=optimizer, last_epoch=last_epoch)

    def get_lr(self) -> List[float]:
        """
        Compute current learning rate for each param group
        """
        # last epoch is automatically handled by parent class
        return [base_lr * (1 - math.exp(- (1 - self.beta2) * self.last_epoch))
                for base_lr in zip(self.base_lrs)]