optimizer.py 14.8 KB
Newer Older
Q
qingqing01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright (c) 2019 PaddlePaddle 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

19
import sys
Q
qingqing01 已提交
20
import math
W
Wenyu 已提交
21
import weakref
Q
qingqing01 已提交
22 23 24 25 26 27 28
import paddle
import paddle.nn as nn

import paddle.optimizer as optimizer
import paddle.regularizer as regularizer

from ppdet.core.workspace import register, serializable
29
import copy
Q
qingqing01 已提交
30 31 32 33 34 35 36

__all__ = ['LearningRate', 'OptimizerBuilder']

from ppdet.utils.logger import setup_logger
logger = setup_logger(__name__)


37 38 39 40 41 42 43 44 45
@serializable
class CosineDecay(object):
    """
    Cosine learning rate decay

    Args:
        max_epochs (int): max epochs for the training process.
            if you commbine cosine decay with warmup, it is recommended that
            the max_iters is much larger than the warmup iter
46 47 48 49
        use_warmup (bool): whether to use warmup. Default: True.
        min_lr_ratio (float): minimum learning rate ratio. Default: 0.
        last_plateau_epochs (int): use minimum learning rate in
            the last few epochs. Default: 0.
50 51
    """

52 53 54 55 56
    def __init__(self,
                 max_epochs=1000,
                 use_warmup=True,
                 min_lr_ratio=0.,
                 last_plateau_epochs=0):
57 58
        self.max_epochs = max_epochs
        self.use_warmup = use_warmup
59 60
        self.min_lr_ratio = min_lr_ratio
        self.last_plateau_epochs = last_plateau_epochs
61 62 63 64 65 66 67 68 69

    def __call__(self,
                 base_lr=None,
                 boundary=None,
                 value=None,
                 step_per_epoch=None):
        assert base_lr is not None, "either base LR or values should be provided"

        max_iters = self.max_epochs * int(step_per_epoch)
70 71
        last_plateau_iters = self.last_plateau_epochs * int(step_per_epoch)
        min_lr = base_lr * self.min_lr_ratio
72
        if boundary is not None and value is not None and self.use_warmup:
73
            # use warmup
M
minghaoBD 已提交
74
            warmup_iters = len(boundary)
75 76
            for i in range(int(boundary[-1]), max_iters):
                boundary.append(i)
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
                if i < max_iters - last_plateau_iters:
                    decayed_lr = min_lr + (base_lr - min_lr) * 0.5 * (math.cos(
                        (i - warmup_iters) * math.pi /
                        (max_iters - warmup_iters - last_plateau_iters)) + 1)
                    value.append(decayed_lr)
                else:
                    value.append(min_lr)
            return optimizer.lr.PiecewiseDecay(boundary, value)
        elif last_plateau_iters > 0:
            # not use warmup, but set `last_plateau_epochs` > 0
            boundary = []
            value = []
            for i in range(max_iters):
                if i < max_iters - last_plateau_iters:
                    decayed_lr = min_lr + (base_lr - min_lr) * 0.5 * (math.cos(
                        i * math.pi / (max_iters - last_plateau_iters)) + 1)
                    value.append(decayed_lr)
                else:
                    value.append(min_lr)
                if i > 0:
                    boundary.append(i)
98 99
            return optimizer.lr.PiecewiseDecay(boundary, value)

W
Wenyu 已提交
100
        return optimizer.lr.CosineAnnealingDecay(
101
            base_lr, T_max=max_iters, eta_min=min_lr)
102 103


Q
qingqing01 已提交
104 105 106 107 108 109 110 111 112 113
@serializable
class PiecewiseDecay(object):
    """
    Multi step learning rate decay

    Args:
        gamma (float | list): decay factor
        milestones (list): steps at which to decay learning rate
    """

114 115 116 117 118
    def __init__(self,
                 gamma=[0.1, 0.01],
                 milestones=[8, 11],
                 values=None,
                 use_warmup=True):
Q
qingqing01 已提交
119 120 121 122 123 124 125 126
        super(PiecewiseDecay, self).__init__()
        if type(gamma) is not list:
            self.gamma = []
            for i in range(len(milestones)):
                self.gamma.append(gamma / 10**i)
        else:
            self.gamma = gamma
        self.milestones = milestones
127 128
        self.values = values
        self.use_warmup = use_warmup
Q
qingqing01 已提交
129 130 131 132 133 134

    def __call__(self,
                 base_lr=None,
                 boundary=None,
                 value=None,
                 step_per_epoch=None):
135
        if boundary is not None and self.use_warmup:
Q
qingqing01 已提交
136
            boundary.extend([int(step_per_epoch) * i for i in self.milestones])
137 138 139
        else:
            # do not use LinearWarmup
            boundary = [int(step_per_epoch) * i for i in self.milestones]
G
George Ni 已提交
140
            value = [base_lr]  # during step[0, boundary[0]] is base_lr
Q
qingqing01 已提交
141

S
shangliang Xu 已提交
142
        # self.values is setted directly in config
143 144 145 146 147
        if self.values is not None:
            assert len(self.milestones) + 1 == len(self.values)
            return optimizer.lr.PiecewiseDecay(boundary, self.values)

        # value is computed by self.gamma
148 149 150
        value = value if value is not None else [base_lr]
        for i in self.gamma:
            value.append(base_lr * i)
Q
qingqing01 已提交
151 152 153 154 155 156 157 158 159 160 161 162

        return optimizer.lr.PiecewiseDecay(boundary, value)


@serializable
class LinearWarmup(object):
    """
    Warm up learning rate linearly

    Args:
        steps (int): warm up steps
        start_factor (float): initial learning rate factor
163 164
        epochs (int|None): use epochs as warm up steps, the priority
            of `epochs` is higher than `steps`. Default: None.
Q
qingqing01 已提交
165 166
    """

167
    def __init__(self, steps=500, start_factor=1. / 3, epochs=None):
Q
qingqing01 已提交
168 169 170
        super(LinearWarmup, self).__init__()
        self.steps = steps
        self.start_factor = start_factor
171
        self.epochs = epochs
Q
qingqing01 已提交
172

G
George Ni 已提交
173
    def __call__(self, base_lr, step_per_epoch):
Q
qingqing01 已提交
174 175
        boundary = []
        value = []
176 177 178 179 180
        warmup_steps = self.epochs * step_per_epoch \
            if self.epochs is not None else self.steps
        for i in range(warmup_steps + 1):
            if warmup_steps > 0:
                alpha = i / warmup_steps
181 182 183
                factor = self.start_factor * (1 - alpha) + alpha
                lr = base_lr * factor
                value.append(lr)
Q
qingqing01 已提交
184 185 186 187 188
            if i > 0:
                boundary.append(i)
        return boundary, value


G
George Ni 已提交
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
@serializable
class BurninWarmup(object):
    """
    Warm up learning rate in burnin mode
    Args:
        steps (int): warm up steps
    """

    def __init__(self, steps=1000):
        super(BurninWarmup, self).__init__()
        self.steps = steps

    def __call__(self, base_lr, step_per_epoch):
        boundary = []
        value = []
        burnin = min(self.steps, step_per_epoch)
        for i in range(burnin + 1):
            factor = (i * 1.0 / burnin)**4
            lr = base_lr * factor
            value.append(lr)
            if i > 0:
                boundary.append(i)
        return boundary, value


F
Feng Ni 已提交
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
@serializable
class ExpWarmup(object):
    """
    Warm up learning rate in exponential mode
    Args:
        steps (int): warm up steps.
        epochs (int|None): use epochs as warm up steps, the priority
            of `epochs` is higher than `steps`. Default: None.
    """

    def __init__(self, steps=5, epochs=None):
        super(ExpWarmup, self).__init__()
        self.steps = steps
        self.epochs = epochs

    def __call__(self, base_lr, step_per_epoch):
        boundary = []
        value = []
        warmup_steps = self.epochs * step_per_epoch if self.epochs is not None else self.steps
        for i in range(warmup_steps + 1):
            factor = (i / float(warmup_steps))**2
            value.append(base_lr * factor)
            if i > 0:
                boundary.append(i)
        return boundary, value


Q
qingqing01 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
@register
class LearningRate(object):
    """
    Learning Rate configuration

    Args:
        base_lr (float): base learning rate
        schedulers (list): learning rate schedulers
    """
    __category__ = 'optim'

    def __init__(self,
                 base_lr=0.01,
                 schedulers=[PiecewiseDecay(), LinearWarmup()]):
        super(LearningRate, self).__init__()
        self.base_lr = base_lr
257 258 259 260 261 262 263 264 265 266 267 268
        self.schedulers = []

        schedulers = copy.deepcopy(schedulers)
        for sched in schedulers:
            if isinstance(sched, dict):
                # support dict sched instantiate
                module = sys.modules[__name__]
                type = sched.pop("name")
                scheduler = getattr(module, type)(**sched)
                self.schedulers.append(scheduler)
            else:
                self.schedulers.append(sched)
Q
qingqing01 已提交
269 270

    def __call__(self, step_per_epoch):
271 272 273 274 275
        assert len(self.schedulers) >= 1
        if not self.schedulers[0].use_warmup:
            return self.schedulers[0](base_lr=self.base_lr,
                                      step_per_epoch=step_per_epoch)

S
shangliang Xu 已提交
276
        # TODO: split warmup & decay
Q
qingqing01 已提交
277
        # warmup
G
George Ni 已提交
278
        boundary, value = self.schedulers[1](self.base_lr, step_per_epoch)
Q
qingqing01 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        # decay
        decay_lr = self.schedulers[0](self.base_lr, boundary, value,
                                      step_per_epoch)
        return decay_lr


@register
class OptimizerBuilder():
    """
    Build optimizer handles
    Args:
        regularizer (object): an `Regularizer` instance
        optimizer (object): an `Optimizer` instance
    """
    __category__ = 'optim'

    def __init__(self,
                 clip_grad_by_norm=None,
                 regularizer={'type': 'L2',
                              'factor': .0001},
                 optimizer={'type': 'Momentum',
                            'momentum': .9}):
        self.clip_grad_by_norm = clip_grad_by_norm
        self.regularizer = regularizer
        self.optimizer = optimizer

W
Wenyu 已提交
305
    def __call__(self, learning_rate, model=None):
Q
qingqing01 已提交
306
        if self.clip_grad_by_norm is not None:
W
wangxinxin08 已提交
307
            grad_clip = nn.ClipGradByGlobalNorm(
Q
qingqing01 已提交
308 309 310
                clip_norm=self.clip_grad_by_norm)
        else:
            grad_clip = None
311
        if self.regularizer and self.regularizer != 'None':
Q
qingqing01 已提交
312 313 314 315 316 317 318 319 320
            reg_type = self.regularizer['type'] + 'Decay'
            reg_factor = self.regularizer['factor']
            regularization = getattr(regularizer, reg_type)(reg_factor)
        else:
            regularization = None

        optim_args = self.optimizer.copy()
        optim_type = optim_args['type']
        del optim_args['type']
321 322
        if optim_type != 'AdamW':
            optim_args['weight_decay'] = regularization
Q
qingqing01 已提交
323
        op = getattr(optimizer, optim_type)
W
Wenyu 已提交
324

W
Wenyu 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        if 'param_groups' in optim_args:
            assert isinstance(optim_args['param_groups'], list), ''

            param_groups = optim_args.pop('param_groups')

            params, visited = [], []
            for group in param_groups:
                assert isinstance(group,
                                  dict) and 'params' in group and isinstance(
                                      group['params'], list), ''
                _params = {
                    n: p
                    for n, p in model.named_parameters()
                    if any([k in n for k in group['params']])
                }
                _group = group.copy()
                _group.update({'params': list(_params.values())})

                params.append(_group)
                visited.extend(list(_params.keys()))

            ext_params = [
                p for n, p in model.named_parameters() if n not in visited
            ]

            if len(ext_params) < len(model.parameters()):
                params.append({'params': ext_params})

            elif len(ext_params) > len(model.parameters()):
                raise RuntimeError

W
Wenyu 已提交
356 357 358
        else:
            params = model.parameters()

Q
qingqing01 已提交
359 360 361 362
        return op(learning_rate=learning_rate,
                  parameters=params,
                  grad_clip=grad_clip,
                  **optim_args)
W
wangxinxin08 已提交
363 364 365


class ModelEMA(object):
G
Guanghua Yu 已提交
366 367 368 369 370 371 372 373
    """
    Exponential Weighted Average for Deep Neutal Networks
    Args:
        model (nn.Layer): Detector of model.
        decay (int):  The decay used for updating ema parameter.
            Ema's parameter are updated with the formula:
           `ema_param = decay * ema_param + (1 - decay) * cur_param`.
            Defaults is 0.9998.
F
Feng Ni 已提交
374 375
        ema_decay_type (str): type in ['threshold', 'normal', 'exponential'],
            'threshold' as default.
S
shangliang Xu 已提交
376
        cycle_epoch (int): The epoch of interval to reset ema_param and
G
Guanghua Yu 已提交
377
            step. Defaults is -1, which means not reset. Its function is to
S
shangliang Xu 已提交
378
            add a regular effect to ema, which is set according to experience
G
Guanghua Yu 已提交
379 380 381 382 383 384
            and is effective when the total training epoch is large.
    """

    def __init__(self,
                 model,
                 decay=0.9998,
F
Feng Ni 已提交
385
                 ema_decay_type='threshold',
G
Guanghua Yu 已提交
386
                 cycle_epoch=-1):
W
wangxinxin08 已提交
387
        self.step = 0
G
Guanghua Yu 已提交
388
        self.epoch = 0
W
wangxinxin08 已提交
389 390 391 392
        self.decay = decay
        self.state_dict = dict()
        for k, v in model.state_dict().items():
            self.state_dict[k] = paddle.zeros_like(v)
F
Feng Ni 已提交
393
        self.ema_decay_type = ema_decay_type
G
Guanghua Yu 已提交
394 395
        self.cycle_epoch = cycle_epoch

W
Wenyu 已提交
396 397 398 399 400
        self._model_state = {
            k: weakref.ref(p)
            for k, p in model.state_dict().items()
        }

G
Guanghua Yu 已提交
401 402 403 404 405
    def reset(self):
        self.step = 0
        self.epoch = 0
        for k, v in self.state_dict.items():
            self.state_dict[k] = paddle.zeros_like(v)
W
wangxinxin08 已提交
406

S
shangliang Xu 已提交
407
    def resume(self, state_dict, step=0):
S
shangliang Xu 已提交
408
        for k, v in state_dict.items():
W
wangxinxin08 已提交
409 410
            if k in self.state_dict:
                self.state_dict[k] = v
S
shangliang Xu 已提交
411 412
        self.step = step

W
Wenyu 已提交
413
    def update(self, model=None):
F
Feng Ni 已提交
414
        if self.ema_decay_type == 'threshold':
W
wangxinxin08 已提交
415
            decay = min(self.decay, (1 + self.step) / (10 + self.step))
F
Feng Ni 已提交
416 417
        elif self.ema_decay_type == 'exponential':
            decay = self.decay * (1 - math.exp(-(self.step + 1) / 2000))
W
wangxinxin08 已提交
418 419 420
        else:
            decay = self.decay
        self._decay = decay
W
Wenyu 已提交
421 422 423 424 425 426 427 428

        if model is not None:
            model_dict = model.state_dict()
        else:
            model_dict = {k: p() for k, p in self._model_state.items()}
            assert all(
                [v is not None for _, v in model_dict.items()]), 'python gc.'

W
wangxinxin08 已提交
429
        for k, v in self.state_dict.items():
W
wangxinxin08 已提交
430 431 432
            v = decay * v + (1 - decay) * model_dict[k]
            v.stop_gradient = True
            self.state_dict[k] = v
W
wangxinxin08 已提交
433 434 435
        self.step += 1

    def apply(self):
436 437
        if self.step == 0:
            return self.state_dict
W
wangxinxin08 已提交
438 439
        state_dict = dict()
        for k, v in self.state_dict.items():
F
Feng Ni 已提交
440 441
            if self.ema_decay_type != 'exponential':
                v = v / (1 - self._decay**self.step)
W
wangxinxin08 已提交
442 443
            v.stop_gradient = True
            state_dict[k] = v
G
Guanghua Yu 已提交
444 445 446 447
        self.epoch += 1
        if self.cycle_epoch > 0 and self.epoch == self.cycle_epoch:
            self.reset()

W
wangxinxin08 已提交
448
        return state_dict