lr.py 108.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 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.

import math
import warnings
17 18 19

import numpy

D
Difer 已提交
20
import paddle
21
from paddle import Tensor
22
from paddle.fluid import core
D
Difer 已提交
23 24 25 26 27 28 29
from paddle.fluid.data_feeder import check_type
from paddle.fluid.framework import (
    Variable,
    default_main_program,
    in_dygraph_mode,
)
from paddle.fluid.layer_helper import LayerHelper
30

G
guguguzi 已提交
31
__all__ = [  # noqa
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    'LRScheduler',
    'NoamDecay',
    'PiecewiseDecay',
    'NaturalExpDecay',
    'InverseTimeDecay',
    'PolynomialDecay',
    'LinearWarmup',
    'ExponentialDecay',
    'MultiStepDecay',
    'StepDecay',
    'LambdaDecay',
    'ReduceOnPlateau',
    'CosineAnnealingDecay',
    'MultiplicativeDecay',
    'OneCycleLR',
    'CyclicLR',
48 49 50
]


51
class LRScheduler:
52 53 54 55
    """

    LRScheduler Base class. Define the common interface of a learning rate scheduler.

Z
Zhou Wei 已提交
56
    User can import it by ``from paddle.optimizer.lr import LRScheduler`` ,
57 58 59 60 61 62 63 64 65 66 67 68 69 70

    then overload it for your subclass and have a custom implementation of ``get_lr()`` .

    Otherwise, an ``NotImplementedError`` exception will be thrown.

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .

    Returns:
        instance to schedule learning rate.

    Examples:
71
        Here is an example of a simple ``StepDecay`` implementation.
G
guguguzi 已提交
72

73
        .. code-block:: python
G
guguguzi 已提交
74

75
            import paddle
Z
Zhou Wei 已提交
76
            from paddle.optimizer.lr import LRScheduler
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

            class StepDecay(LRScheduler):
                def __init__(self,
                            learning_rate,
                            step_size,
                            gamma=0.1,
                            last_epoch=-1,
                            verbose=False):
                    if not isinstance(step_size, int):
                        raise TypeError(
                            "The type of 'step_size' must be 'int', but received %s." %
                            type(step_size))
                    if gamma >= 1.0:
                        raise ValueError('gamma should be < 1.0.')

                    self.step_size = step_size
                    self.gamma = gamma
94
                    super().__init__(learning_rate, last_epoch, verbose)
95 96 97 98

                def get_lr(self):
                    i = self.last_epoch // self.step_size
                    return self.base_lr * (self.gamma**i)
99 100 101 102 103 104

    """

    def __init__(self, learning_rate=0.1, last_epoch=-1, verbose=False):
        if not isinstance(learning_rate, (float, int)):
            raise TypeError(
105 106 107 108
                "The type of learning rate must be float, but received {}".format(
                    type(learning_rate)
                )
            )
109 110
        if learning_rate < 0:
            raise ValueError(f"Invalid learning rate: {learning_rate}")
111 112 113 114 115 116 117 118 119
        self.base_lr = float(learning_rate)
        self.last_lr = float(learning_rate)
        self.last_epoch = last_epoch
        self.verbose = verbose
        self._var_name = None

        self.step()

    def __call__(self):
G
guguguzi 已提交
120
        """
S
Shuangchi He 已提交
121
        Return latest computed learning rate on current epoch.
122 123 124 125 126
        """
        return self.last_lr

    def step(self, epoch=None):
        """
127

G
guguguzi 已提交
128
        ``step`` should be called after ``optimizer.step`` . It will update the learning rate in optimizer according to current ``epoch`` .
129
        The new learning rate will take effect on next ``optimizer.step`` .
130 131 132 133 134 135

        Args:
            epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1.

        Returns:
            None
136 137 138 139 140 141 142 143 144 145 146 147 148
        Examples:
            .. code-block:: python

                import paddle
                value = paddle.arange(26, dtype='float32')
                a = paddle.reshape(value, [2, 13])
                linear = paddle.nn.Linear(13, 5)
                adadelta = paddle.optimizer.Adadelta(learning_rate=0.0003, epsilon=1e-06, rho=0.95,
                                            parameters = linear.parameters())
                out = linear(a)
                out.backward()
                adadelta.step()
                adadelta.clear_grad()
149

150 151 152 153 154 155 156 157 158 159 160 161
        Examples:
            .. code-block:: python
                import paddle
                value = paddle.arange(26, dtype='float32')
                a = paddle.reshape(value, [2, 13])
                linear = paddle.nn.Linear(13, 5)
                adadelta = paddle.optimizer.Adadelta(learning_rate=0.0003, epsilon=1e-06, rho=0.95,
                                            parameters = linear.parameters())
                out = linear(a)
                out.backward()
                adadelta.step()
                adadelta.clear_grad()
162 163 164 165 166 167 168 169 170 171 172 173
        """
        if epoch is None:
            self.last_epoch += 1
            self.last_lr = self.get_lr()
        else:
            self.last_epoch = epoch
            if hasattr(self, "_get_closed_form_lr"):
                self.last_lr = self._get_closed_form_lr()
            else:
                self.last_lr = self.get_lr()

        if self.verbose:
174 175 176 177 178
            print(
                'Epoch {}: {} set learning rate to {}.'.format(
                    self.last_epoch, self.__class__.__name__, self.last_lr
                )
            )
179 180 181

    def state_dict(self):
        """
182

183 184
        Returns the state of the scheduler as a :class:`dict`.

185
        It is a subset of ``self.__dict__`` .
186
        """
187
        self.state_keys()
188 189 190 191 192 193
        state_dict = {}
        for key in self.keys:
            if key not in self.__dict__:
                continue
            value = self.__dict__[key]
            if isinstance(value, Tensor):
194 195 196 197
                assert (
                    value.size == 1
                ), "numel of Tensor in state_dict must be 1"
                value = float(value)
198 199 200 201
            state_dict[key] = value

        return state_dict

202
    # For those subclass who overload LRScheduler, "last_epoch, last_lr" will be saved by default.
203
    # (Note): you can change it for your subclass.
204
    def state_keys(self):
205
        """
206 207 208 209 210 211 212

        For those subclass who overload ``LRScheduler`` (Base Class). Acquiescently, "last_epoch, last_lr" will be saved by ``self.keys = ['last_epoch', 'last_lr']`` .

        ``last_epoch`` is the current epoch num, and ``last_lr`` is the current learning rate.

        If you want to change the default behavior, you should have a custom implementation of ``_state_keys()`` to redefine ``self.keys`` .

213 214 215
        """
        self.keys = ['last_epoch', 'last_lr']

216
    def set_state_dict(self, state_dict):
217
        """
218

219 220
        Loads the schedulers state.
        """
221
        self.state_keys()
222 223 224 225 226
        for key in self.keys:
            if key in state_dict:
                self.__dict__[key] = state_dict[key]
            else:
                raise RuntimeError(
227 228 229 230
                    "Please check whether state_dict is correct for optimizer. Can't find [ {} ] in state_dict".format(
                        key
                    )
                )
231 232 233 234 235
        if len(state_dict) > len(self.keys):
            warnings.warn(
                "There are some unused values in state_dict. Maybe the optimizer have different 'LearningRateDecay' when invoking state_dict and set_dict"
            )

236 237
    # alias for set_state_dict
    set_dict = set_state_dict
238 239

    def get_lr(self):
240
        """
G
guguguzi 已提交
241

242 243 244 245
        For those subclass who overload ``LRScheduler`` (Base Class), User should have a custom implementation of ``get_lr()`` .

        Otherwise, an ``NotImplementedError`` exception will be thrown.
        """
246 247 248 249
        # calculate by python float
        raise NotImplementedError


250
class NoamDecay(LRScheduler):
251
    r"""
252

G
guguguzi 已提交
253
    Applies Noam Decay to the initial learning rate.
254 255 256 257 258 259 260

    The algorithm can be described as following.

    .. math::

        new\_learning\_rate = learning\_rate * d_{model}^{-0.5} * min(epoch^{-0.5}, epoch * warmup\_steps^{-1.5})

G
guguguzi 已提交
261
    Please reference `attention is all you need <https://arxiv.org/pdf/1706.03762.pdf>`_
262 263 264 265 266 267 268


    Args:
        d$_{model}$(int): The dimensionality of input and output feature vector of model. It is a python int number.
        warmup_steps(int): The number of warmup steps. A super parameter. It is a python int number
        learning_rate (float): The initial learning rate. It is a python float number. Default: 1.0.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
269
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
270 271

    Returns:
272
        ``NoamDecay`` instance to schedule learning rate.
273 274 275

    Examples:
        .. code-block:: python
276
            :name: code-example1
277

278
            # Example1: train on default dynamic graph mode
279 280 281
            import paddle
            import numpy as np

282
            # train on default dynamic graph mode
283
            linear = paddle.nn.Linear(10, 10)
284 285
            scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
286
            for epoch in range(20):
Z
Zhou Wei 已提交
287
                for batch_id in range(5):
288
                    x = paddle.uniform([10, 10])
289
                    out = linear(x)
C
chentianyu03 已提交
290
                    loss = paddle.mean(out)
291
                    loss.backward()
292 293
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
294 295
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
296

297 298 299 300 301 302
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
303 304 305 306
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
307 308
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
309 310
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
311
                scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True)
312 313 314 315 316 317
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
318
                for batch_id in range(5):
319 320 321 322 323 324
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
325
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
326 327
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
328 329 330

    """

331 332 333 334 335 336 337 338
    def __init__(
        self,
        d_model,
        warmup_steps,
        learning_rate=1.0,
        last_epoch=-1,
        verbose=False,
    ):
339 340 341
        if d_model <= 0:
            raise ValueError("d_model should be grater than 0")

342 343
        self.d_model = d_model
        self.warmup_steps = warmup_steps
344
        super().__init__(learning_rate, last_epoch, verbose)
345 346 347 348 349 350 351 352 353 354

    def get_lr(self):
        if self.last_epoch == 0:
            a = 1
        else:
            a = self.last_epoch**-0.5
        b = self.warmup_steps**-1.5 * self.last_epoch
        return self.base_lr * (self.d_model**-0.5) * min(a, b)


355
class PiecewiseDecay(LRScheduler):
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    """

    Piecewise learning rate scheduler.

    The algorithm can be described as the code below:

    .. code-block:: text

        boundaries = [100, 200]
        values = [1.0, 0.5, 0.1]
        if epoch < 100:
            learning_rate = 1.0
        elif 100 <= global_step < 200:
            learning_rate = 0.5
        else:
            learning_rate = 0.1

    Args:
G
guguguzi 已提交
374 375
        boundaries(list|tuple): A list/tuple of steps numbers. The type of element in the list is python int.
        values(list|tuple): A list/tuple of learning rate values that will be picked during different epoch boundaries.
376
            The type of element in the list is python float. The ``values`` have one more element than ``boundaries``.
377
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
378
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
379 380

    Returns:
381
        ``PiecewiseDecay`` instance to schedule learning rate.
382 383

    Examples:
G
guguguzi 已提交
384

385
        .. code-block:: python
386
            :name: code-example1
387

388
            # Example1: train on default dynamic graph mode
389 390 391
            import paddle
            import numpy as np

392
            # train on default dynamic graph mode
393
            linear = paddle.nn.Linear(10, 10)
394 395
            scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries=[3, 6, 9], values=[0.1, 0.2, 0.3, 0.4], verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
396
            for epoch in range(20):
Z
Zhou Wei 已提交
397
                for batch_id in range(5):
398
                    x = paddle.uniform([10, 10])
399
                    out = linear(x)
C
chentianyu03 已提交
400
                    loss = paddle.mean(out)
401
                    loss.backward()
402 403
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
404 405
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
406

407 408 409 410 411 412
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
413 414 415 416
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
417 418
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
419 420
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
421
                scheduler = paddle.optimizer.lr.PiecewiseDecay(boundaries=[3, 6, 9], values=[0.1, 0.2, 0.3, 0.4], verbose=True)
422 423 424 425 426 427
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
428
                for batch_id in range(5):
429 430 431 432 433 434
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
435
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
436 437
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
438 439 440
    """

    def __init__(self, boundaries, values, last_epoch=-1, verbose=False):
441 442 443 444 445 446 447 448
        if len(boundaries) == 0:
            raise ValueError('The boundaries cannot be empty.')

        if len(values) <= len(boundaries):
            raise ValueError(
                f'The values have one more element than boundaries, but received len(values) [{len(values)}] < len(boundaries) + 1 [{len(boundaries) + 1}].'
            )

449 450
        self.boundaries = boundaries
        self.values = values
451
        super().__init__(last_epoch=last_epoch, verbose=verbose)
452 453 454 455 456 457 458 459

    def get_lr(self):
        for i in range(len(self.boundaries)):
            if self.last_epoch < self.boundaries[i]:
                return self.values[i]
        return self.values[len(self.values) - 1]


460
class NaturalExpDecay(LRScheduler):
461
    r"""
462 463

    Applies natural exponential decay to the initial learning rate.
G
guguguzi 已提交
464

465 466 467 468
    The algorithm can be described as following:

    .. math::

469
        new\_learning\_rate = learning\_rate * e^{- gamma * epoch}
470 471 472

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
473
        gamma (float, optional): A Ratio to update the learning rate, should greater than 0.0 to make learning rate decay. Default: 0.1.
474
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
475
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
476 477

    Returns:
478
        ``NaturalExpDecay`` instance to schedule learning rate.
479 480

    Examples:
G
guguguzi 已提交
481

482
        .. code-block:: python
483
            :name: code-example1
484

485
            # Example1: train on default dynamic graph mode
486 487 488
            import paddle
            import numpy as np
            linear = paddle.nn.Linear(10, 10)
489 490
            scheduler = paddle.optimizer.lr.NaturalExpDecay(learning_rate=0.5, gamma=0.1, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
491
            for epoch in range(20):
Z
Zhou Wei 已提交
492
                for batch_id in range(5):
493
                    x = paddle.uniform([10, 10])
494
                    out = linear(x)
C
chentianyu03 已提交
495
                    loss = paddle.mean(out)
496
                    loss.backward()
497 498
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
499 500
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
501

502 503 504 505 506 507
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
508 509 510 511
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
512 513
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
514 515
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
516
                scheduler = paddle.optimizer.lr.NaturalExpDecay(learning_rate=0.5, gamma=0.1, verbose=True)
517 518 519 520 521 522
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
523
                for batch_id in range(5):
524 525 526 527 528 529
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
530
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
531 532
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
533 534 535
    """

    def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False):
536 537 538
        assert (
            gamma > 0.0
        ), " 'gamma' must be a positive number so that the learning rate will decay."
539
        self.gamma = gamma
540
        super().__init__(learning_rate, last_epoch, verbose)
541 542 543 544 545

    def get_lr(self):
        return self.base_lr * math.exp(-1 * self.gamma * self.last_epoch)


546
class InverseTimeDecay(LRScheduler):
547
    r"""
548 549 550 551 552 553 554

    Applies inverse time decay to the initial learning rate.

    The algorithm can be described as following:

    .. math::

555
        new\_learning\_rate = \frac{learning\_rate}{1 + gamma * epoch}
556 557 558

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
G
guguguzi 已提交
559
        gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
560 561
            It should be less than 1.0. Default: 0.1.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
562
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
563 564

    Returns:
565
        ``InverseTimeDecay`` instance to schedule learning rate.
566 567

    Examples:
G
guguguzi 已提交
568

569
        .. code-block:: python
570
            :name: code-example1
571

572
            # Example1: train on default dynamic graph mode
573 574 575
            import paddle
            import numpy as np

576
            # train on default dynamic graph mode
577
            linear = paddle.nn.Linear(10, 10)
578 579
            scheduler = paddle.optimizer.lr.InverseTimeDecay(learning_rate=0.5, gamma=0.1, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
580
            for epoch in range(20):
Z
Zhou Wei 已提交
581
                for batch_id in range(5):
582
                    x = paddle.uniform([10, 10])
583
                    out = linear(x)
C
chentianyu03 已提交
584
                    loss = paddle.mean(out)
585
                    loss.backward()
586 587
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
588 589
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
590

591 592 593 594 595 596
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
597 598 599 600
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
601 602
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
603 604
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
605
                scheduler = paddle.optimizer.lr.InverseTimeDecay(learning_rate=0.5, gamma=0.1, verbose=True)
606 607 608 609 610 611
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
612
                for batch_id in range(5):
613 614 615 616 617 618
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
619
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
620 621
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
622 623 624 625 626

    """

    def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False):
        self.gamma = gamma
627
        super().__init__(learning_rate, last_epoch, verbose)
628 629 630 631 632

    def get_lr(self):
        return self.base_lr / (1 + self.gamma * self.last_epoch)


633
class PolynomialDecay(LRScheduler):
634
    r"""
635 636 637 638 639 640 641 642 643

    Applies polynomial decay to the initial learning rate.

    The algorithm can be described as following.

    If cycle is set to True, then:

    .. math::

G
guguguzi 已提交
644
        decay\_steps & = decay\_steps * math.ceil(\frac{epoch}{decay\_steps})
645

646
        new\_learning\_rate & = (learning\_rate-end\_lr)*(1-\frac{epoch}{decay\_steps})^{power}+end\_lr
647 648 649 650 651

    If cycle is set to False, then:

    .. math::

G
guguguzi 已提交
652
        epoch & = min(epoch, decay\_steps)
653

654
        new\_learning\_rate & = (learning\_rate-end\_lr)*(1-\frac{epoch}{decay\_steps})^{power}+end\_lr
655 656 657 658


    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
659
        decay_steps(int): The decay step size. It determines the decay cycle. It must be a positive integer.
660
        end_lr(float, optional): The minimum final learning rate. Default: 0.0001.
661
        power(float, optional): Power of polynomial, should greater than 0.0 to get learning rate decay. Default: 1.0.
G
guguguzi 已提交
662
        cycle(bool, optional): Whether the learning rate rises again. If True, then the learning rate will rise when it decrease
663 664
            to ``end_lr`` .  If False, the learning rate is monotone decreasing. Default: False.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
665
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
666 667

    Returns:
668
        ``PolynomialDecay`` instance to schedule learning rate.
669 670

    Examples:
G
guguguzi 已提交
671

672
        .. code-block:: python
673
            :name: code-example1
674

675
            # Example1: train on default dynamic graph mode
676 677 678
            import paddle
            import numpy as np

679
            # train on default dynamic graph mode
680
            linear = paddle.nn.Linear(10, 10)
681 682
            scheduler = paddle.optimizer.lr.PolynomialDecay(learning_rate=0.5, decay_steps=20, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
683
            for epoch in range(20):
Z
Zhou Wei 已提交
684
                for batch_id in range(5):
685
                    x = paddle.uniform([10, 10])
686
                    out = linear(x)
C
chentianyu03 已提交
687
                    loss = paddle.mean(out)
688
                    loss.backward()
689 690
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
691 692
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
693

694 695 696 697 698 699
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
700 701 702 703
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
704 705
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
706 707
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
708
                scheduler = paddle.optimizer.lr.PolynomialDecay(learning_rate=0.5, decay_steps=20, verbose=True)
709 710 711 712 713 714
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
715
                for batch_id in range(5):
716 717 718 719 720 721
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
722
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
723 724
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
725 726
    """

727 728 729 730 731 732 733 734 735 736
    def __init__(
        self,
        learning_rate,
        decay_steps,
        end_lr=0.0001,
        power=1.0,
        cycle=False,
        last_epoch=-1,
        verbose=False,
    ):
737
        assert decay_steps > 0 and isinstance(
738 739
            decay_steps, int
        ), " 'decay_steps' must be a positive integer."
740 741
        self.decay_steps = decay_steps
        self.end_lr = end_lr
742 743 744
        assert (
            power > 0.0
        ), " 'power' must be greater than 0.0 so that the learning rate will decay."
745 746
        self.power = power
        self.cycle = cycle
747
        super().__init__(learning_rate, last_epoch, verbose)
748 749 750 751 752 753

    def get_lr(self):
        tmp_epoch_num = self.last_epoch
        tmp_decay_steps = self.decay_steps
        if self.cycle:
            div_res = math.ceil(
754 755
                float(self.last_epoch) / float(self.decay_steps)
            )
756 757 758 759 760 761 762 763

            if self.last_epoch == 0:
                div_res = 1
            tmp_decay_steps = self.decay_steps * div_res
        else:
            tmp_epoch_num = min(self.last_epoch, self.decay_steps)

        return (self.base_lr - self.end_lr) * (
764 765
            (1 - float(tmp_epoch_num) / float(tmp_decay_steps)) ** self.power
        ) + self.end_lr
766 767


768
class LinearWarmup(LRScheduler):
769
    r"""
770 771 772

    Linear learning rate warm up strategy. Update the learning rate preliminarily before the normal learning rate scheduler.
    For more information, please refer to `Bag of Tricks for Image Classification with Convolutional Neural Networks <https://arxiv.org/abs/1812.01187>`_
G
guguguzi 已提交
773

774
    When epoch < warmup_steps, learning rate is updated as:
G
guguguzi 已提交
775

776
    .. math::
G
guguguzi 已提交
777

778
            lr = start\_lr + (end\_lr - start\_lr) * \frac{epoch}{warmup\_steps}
G
guguguzi 已提交
779

780
    where start_lr is the initial learning rate, and end_lr is the final learning rate;
G
guguguzi 已提交
781

782
    When epoch >= warmup_steps, learning rate is updated as:
G
guguguzi 已提交
783

784
    .. math::
G
guguguzi 已提交
785

786
            lr = learning_rate
G
guguguzi 已提交
787

788
    where ``learning_rate`` is float or any subclass of ``LRScheduler`` .
789 790

    Args:
791
        learning_rate (float|LRScheduler): The learning rate after warm-up. It is a python float number or any subclass of ``LRScheduler`` .
792
        warmup_steps (int): total steps of warm up. It must be a positive integer.
793 794 795
        start_lr (float): Initial learning rate of warm up.
        end_lr (float): Final learning rate of warm up.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
796
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
797 798

    Returns:
799
        ``LinearWarmup`` instance to schedule learning rate.
800 801

    Examples:
G
guguguzi 已提交
802

803
        .. code-block:: python
804
            :name: code-example1
805

806
            # Example1: train on default dynamic graph mode
807 808 809
            import paddle
            import numpy as np

810
            # train on default dynamic graph mode
811
            linear = paddle.nn.Linear(10, 10)
812
            scheduler = paddle.optimizer.lr.LinearWarmup(
813
                    learning_rate=0.5, warmup_steps=20, start_lr=0, end_lr=0.5, verbose=True)
814
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
815
            for epoch in range(20):
Z
Zhou Wei 已提交
816
                for batch_id in range(5):
817
                    x = paddle.uniform([10, 10])
818
                    out = linear(x)
C
chentianyu03 已提交
819
                    loss = paddle.mean(out)
820
                    loss.backward()
821 822
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
823 824
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
825

826 827 828 829 830 831
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
832 833 834 835
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
836 837
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
838 839
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
840
                scheduler = paddle.optimizer.lr.LinearWarmup(
841 842 843 844 845 846 847
                    learning_rate=0.5, warmup_steps=20, start_lr=0, end_lr=0.5, verbose=True)
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
848
                for batch_id in range(5):
849 850 851 852 853 854
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
855
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
856 857
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
858 859
    """

860 861 862 863 864 865 866 867 868
    def __init__(
        self,
        learning_rate,
        warmup_steps,
        start_lr,
        end_lr,
        last_epoch=-1,
        verbose=False,
    ):
869
        type_check = isinstance(learning_rate, (float, int, LRScheduler))
870 871
        if not type_check:
            raise TypeError(
872 873 874 875
                "the type of learning_rate should be [int, float or LRScheduler], the current type is {}".format(
                    learning_rate
                )
            )
876
        self.learning_rate = learning_rate
877
        assert warmup_steps > 0 and isinstance(
878 879
            warmup_steps, int
        ), " 'warmup_steps' must be a positive integer."
880 881 882
        self.warmup_steps = warmup_steps
        self.start_lr = start_lr
        self.end_lr = end_lr
883 884
        assert (
            end_lr > start_lr
885
        ), f"end_lr {end_lr} must be greater than start_lr {start_lr}"
886
        super().__init__(start_lr, last_epoch, verbose)
887

888 889 890 891 892 893
    def state_dict(self):
        """
        Returns the state of the LinearWarmup scheduler as a :class:`dict`.

        It is a subset of ``self.__dict__`` .
        """
894
        state_dict = super().state_dict()
895 896 897 898 899 900 901 902
        if isinstance(self.learning_rate, LRScheduler):
            state_dict["LinearWarmup_LR"] = self.learning_rate.state_dict()
        return state_dict

    def set_state_dict(self, state_dict):
        """
        Loads state_dict for LinearWarmup scheduler.
        """
903
        super().set_state_dict(state_dict)
904 905 906
        if isinstance(self.learning_rate, LRScheduler):
            self.learning_rate.set_state_dict(state_dict["LinearWarmup_LR"])

907 908 909
    def get_lr(self):
        if self.last_epoch < self.warmup_steps:
            return (self.end_lr - self.start_lr) * float(
910 911
                self.last_epoch
            ) / float(self.warmup_steps) + self.start_lr
912
        else:
913
            if isinstance(self.learning_rate, LRScheduler):
914 915
                self.learning_rate.step(self.last_epoch - self.warmup_steps)
                return self.learning_rate()
916 917 918 919

            return self.learning_rate


920
class ExponentialDecay(LRScheduler):
921
    r"""
922

923
    Update learning rate by `gamma` each epoch.
924 925

    The algorithm can be described as following.
G
guguguzi 已提交
926

927 928 929 930 931 932
    .. math::

        new\_learning\_rate = last\_learning\_rate * gamma

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
G
guguguzi 已提交
933
        gamma (float): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
934
            It should be in interval (0.0, 1.0).
935
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
936
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
937 938

    Returns:
939
        ``ExponentialDecay`` instance to schedule learning rate.
940 941

    Examples:
G
guguguzi 已提交
942

943
        .. code-block:: python
944
            :name: code-example1
945

946
            # Example1: train on default dynamic graph mode
947 948 949
            import paddle
            import numpy as np

950
            # train on default dynamic graph mode
951
            linear = paddle.nn.Linear(10, 10)
952 953
            scheduler = paddle.optimizer.lr.ExponentialDecay(learning_rate=0.5, gamma=0.9, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
954
            for epoch in range(20):
Z
Zhou Wei 已提交
955
                for batch_id in range(5):
956
                    x = paddle.uniform([10, 10])
957
                    out = linear(x)
C
chentianyu03 已提交
958
                    loss = paddle.mean(out)
959
                    loss.backward()
960 961
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
962 963
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
964

965 966 967 968 969 970
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
971 972 973 974
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
975 976
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
977 978
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
979
                scheduler = paddle.optimizer.lr.ExponentialDecay(learning_rate=0.5, gamma=0.9, verbose=True)
980 981 982 983 984 985
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
986
                for batch_id in range(5):
987 988 989 990 991 992
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
993
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
994 995
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
996 997 998
    """

    def __init__(self, learning_rate, gamma, last_epoch=-1, verbose=False):
999 1000 1001
        assert (
            gamma > 0.0 and gamma < 1.0
        ), " 'gamma' must be in interval (0.0, 1.0) so that the learning rate will decay."
1002
        self.gamma = gamma
1003
        super().__init__(learning_rate, last_epoch, verbose)
1004 1005 1006 1007 1008

    def get_lr(self):
        return self.base_lr * (self.gamma**self.last_epoch)


1009
class MultiStepDecay(LRScheduler):
1010
    """
1011
    Update the learning rate by ``gamma`` once ``epoch`` reaches one of the milestones.
1012

G
guguguzi 已提交
1013
    The algorithm can be described as the code below.
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029

    .. code-block:: text

        learning_rate = 0.5
        milestones = [30, 50]
        gamma = 0.1
        if epoch < 30:
            learning_rate = 0.5
        elif epoch < 50:
            learning_rate = 0.05
        else:
            learning_rate = 0.005

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
        milestones (tuple|list): List or tuple of each boundaries. Must be increasing.
G
guguguzi 已提交
1030
        gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
1031 1032
            It should be less than 1.0. Default: 0.1.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
1033
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
G
guguguzi 已提交
1034

1035 1036

    Returns:
1037
        ``MultiStepDecay`` instance to schedule learning rate.
1038 1039

    Examples:
G
guguguzi 已提交
1040

1041
        .. code-block:: python
1042
            :name: code-example1
1043

1044
            # Example1: train on default dynamic graph mode
1045 1046 1047
            import paddle
            import numpy as np

1048
            # train on default dynamic graph mode
1049
            linear = paddle.nn.Linear(10, 10)
1050 1051
            scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
1052
            for epoch in range(20):
Z
Zhou Wei 已提交
1053
                for batch_id in range(5):
1054
                    x = paddle.uniform([10, 10])
1055
                    out = linear(x)
C
chentianyu03 已提交
1056
                    loss = paddle.mean(out)
1057
                    loss.backward()
1058 1059
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
1060 1061
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1062

1063 1064 1065 1066 1067 1068
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1069 1070 1071 1072
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
1073 1074
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
1075 1076
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
1077
                scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
1078 1079 1080 1081 1082 1083
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
1084
                for batch_id in range(5):
1085 1086 1087 1088 1089 1090
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
1091
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
1092 1093
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1094 1095
    """

1096 1097 1098
    def __init__(
        self, learning_rate, milestones, gamma=0.1, last_epoch=-1, verbose=False
    ):
1099 1100 1101
        if not isinstance(milestones, (tuple, list)):
            raise TypeError(
                "The type of 'milestones' in 'MultiStepDecay' must be 'tuple, list', but received %s."
1102 1103
                % type(milestones)
            )
1104

1105
        if not all(
1106 1107
            milestones[i] < milestones[i + 1]
            for i in range(len(milestones) - 1)
1108
        ):
1109 1110 1111 1112 1113 1114
            raise ValueError('The elements of milestones must be incremented')
        if gamma >= 1.0:
            raise ValueError('gamma should be < 1.0.')

        self.milestones = milestones
        self.gamma = gamma
1115
        super().__init__(learning_rate, last_epoch, verbose)
1116 1117 1118 1119 1120

    def get_lr(self):
        for i in range(len(self.milestones)):
            if self.last_epoch < self.milestones[i]:
                return self.base_lr * (self.gamma**i)
1121
        return self.base_lr * (self.gamma ** len(self.milestones))
1122 1123


1124
class StepDecay(LRScheduler):
1125 1126 1127
    """
    Update the learning rate of ``optimizer`` by ``gamma`` every ``step_size`` number of epoch.

G
guguguzi 已提交
1128
    The algorithm can be described as the code below.
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

    .. code-block:: text

        learning_rate = 0.5
        step_size = 30
        gamma = 0.1

        learning_rate = 0.5     if epoch < 30
        learning_rate = 0.05    if 30 <= epoch < 60
        learning_rate = 0.005   if 60 <= epoch < 90
        ...

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
1143
        step_size (int): the interval to update. It must be a positive integer.
G
guguguzi 已提交
1144
        gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
1145 1146
            It should be less than 1.0. Default: 0.1.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
1147
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
1148 1149

    Returns:
1150
        ``StepDecay`` instance to schedule learning rate.
1151 1152 1153


    Examples:
G
guguguzi 已提交
1154

1155
        .. code-block:: python
1156
            :name: code-example1
1157

1158
            # Example1: train on default dynamic graph mode
1159 1160 1161
            import paddle
            import numpy as np

1162
            # train on default dynamic graph mode
1163
            linear = paddle.nn.Linear(10, 10)
1164 1165
            scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=5, gamma=0.8, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
1166
            for epoch in range(20):
Z
Zhou Wei 已提交
1167
                for batch_id in range(5):
1168
                    x = paddle.uniform([10, 10])
1169
                    out = linear(x)
C
chentianyu03 已提交
1170
                    loss = paddle.mean(out)
1171
                    loss.backward()
1172 1173
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
1174 1175
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1176

1177 1178 1179 1180 1181 1182
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1183 1184 1185 1186
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
1187 1188
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
1189 1190
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
1191
                scheduler = paddle.optimizer.lr.StepDecay(learning_rate=0.5, step_size=5, gamma=0.8, verbose=True)
1192 1193 1194 1195 1196 1197
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
1198
                for batch_id in range(5):
1199 1200 1201 1202 1203 1204
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
1205
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
1206 1207
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1208 1209
    """

1210 1211 1212
    def __init__(
        self, learning_rate, step_size, gamma=0.1, last_epoch=-1, verbose=False
    ):
1213 1214
        if not isinstance(step_size, int):
            raise TypeError(
1215 1216 1217
                "The type of 'step_size' must be 'int', but received %s."
                % type(step_size)
            )
1218 1219 1220
        if gamma >= 1.0:
            raise ValueError('gamma should be < 1.0.')

1221
        assert step_size > 0 and isinstance(
1222 1223
            step_size, int
        ), " 'step_size' must be a positive integer."
1224 1225
        self.step_size = step_size
        self.gamma = gamma
1226
        super().__init__(learning_rate, last_epoch, verbose)
1227 1228 1229 1230 1231 1232

    def get_lr(self):
        i = self.last_epoch // self.step_size
        return self.base_lr * (self.gamma**i)


1233
class LambdaDecay(LRScheduler):
1234
    """
C
co63oc 已提交
1235
    Sets the learning rate of ``optimizer`` by function ``lr_lambda`` . ``lr_lambda`` is function which receives ``epoch`` .
1236

G
guguguzi 已提交
1237
    The algorithm can be described as the code below.
1238 1239 1240 1241 1242 1243

    .. code-block:: text

        learning_rate = 0.5        # init learning_rate
        lr_lambda = lambda epoch: 0.95 ** epoch

1244 1245 1246
        learning_rate = 0.5        # epoch 0, 0.5*0.95**0
        learning_rate = 0.475      # epoch 1, 0.5*0.95**1
        learning_rate = 0.45125    # epoch 2, 0.5*0.95**2
1247 1248 1249 1250 1251

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
        lr_lambda (function): A function which computes a factor by ``epoch`` , and then multiply the initial learning rate by this factor.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
1252
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
G
guguguzi 已提交
1253

1254
    Returns:
1255
        ``LambdaDecay`` instance to schedule learning rate.
1256 1257

    Examples:
G
guguguzi 已提交
1258

1259
        .. code-block:: python
1260
            :name: code-example1
1261

1262
            # Example1: train on default dynamic graph mode
1263 1264 1265
            import paddle
            import numpy as np

1266
            # train on default dynamic graph mode
1267
            linear = paddle.nn.Linear(10, 10)
1268 1269
            scheduler = paddle.optimizer.lr.LambdaDecay(learning_rate=0.5, lr_lambda=lambda x:0.95**x, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
1270
            for epoch in range(20):
Z
Zhou Wei 已提交
1271
                for batch_id in range(5):
1272
                    x = paddle.uniform([10, 10])
1273
                    out = linear(x)
C
chentianyu03 已提交
1274
                    loss = paddle.mean(out)
1275
                    loss.backward()
1276 1277
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
1278 1279
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1280

1281 1282 1283 1284 1285 1286
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1287 1288 1289 1290
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
1291 1292
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
1293 1294
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
1295
                scheduler = paddle.optimizer.lr.LambdaDecay(learning_rate=0.5, lr_lambda=lambda x:0.95**x, verbose=True)
1296 1297 1298 1299 1300 1301
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
1302
                for batch_id in range(5):
1303 1304 1305 1306 1307 1308
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
1309
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
1310 1311
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1312 1313 1314 1315 1316 1317

    """

    def __init__(self, learning_rate, lr_lambda, last_epoch=-1, verbose=False):
        if not callable(lr_lambda):
            raise TypeError(
1318
                "The type of 'lr_lambda' in 'LambdaDecay' must be 'function', but received %s."
1319 1320
                % type(lr_lambda)
            )
1321 1322

        self.lr_lambda = lr_lambda
1323
        super().__init__(learning_rate, last_epoch, verbose)
1324 1325 1326 1327 1328

    def get_lr(self):
        return self.base_lr * self.lr_lambda(self.last_epoch)


1329
class ReduceOnPlateau(LRScheduler):
1330
    """
G
guguguzi 已提交
1331
    Reduce learning rate when ``metrics`` has stopped descending. Models often benefit from reducing the learning rate
1332 1333
    by 2 to 10 times once model performance has no longer improvement.

1334
    The ``metrics`` is the one which has been pass into ``step`` , it's shape must [] or [1]. When ``metrics``
G
guguguzi 已提交
1335 1336
    stop descending for a ``patience`` number of epochs, the learning rate will be reduced to ``learning_rate * factor`` .
    (Specially, ``mode`` can also be set to ``'max`` , in this case, when ``metrics`` stop ascending for a ``patience``
1337 1338 1339 1340 1341 1342
    number of epochs, the learning rate will be reduced.)

    In addition, After each reduction, it will wait a ``cooldown`` number of epochs before resuming above operation.

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
G
guguguzi 已提交
1343 1344
        mode (str, optional): ``'min'`` or ``'max'`` can be selected. Normally, it is ``'min'`` , which means that the
            learning rate will reduce when ``loss`` stops descending. Specially, if it's set to ``'max'`` ,  the learning
1345
            rate will reduce when ``loss`` stops ascending. Default: ``'min'`` .
G
guguguzi 已提交
1346
        factor (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * factor`` .
1347
            It should be less than 1.0. Default: 0.1.
G
guguguzi 已提交
1348
        patience (int, optional): When ``loss`` doesn't improve for this number of epochs, learing rate will be reduced.
1349
            Default: 10.
G
guguguzi 已提交
1350
        threshold (float, optional): ``threshold`` and ``threshold_mode`` will determine the minimum change of ``loss`` .
1351 1352
            This make tiny changes of ``loss`` will be ignored. Default: 1e-4.
        threshold_mode (str, optional): ``'rel'`` or ``'abs'`` can be selected. In ``'rel'`` mode, the minimum change of ``loss``
G
guguguzi 已提交
1353
            is ``last_loss * threshold`` , where ``last_loss`` is ``loss`` in last epoch. In ``'abs'`` mode, the minimum
1354 1355 1356
            change of ``loss`` is ``threshold`` . Default: ``'rel'`` .
        cooldown (int, optional): The number of epochs to wait before resuming normal operation. Default: 0.
        min_lr (float, optional): The lower bound of the learning rate after reduction. Default: 0.
G
guguguzi 已提交
1357
        epsilon (float, optional): Minimal decay applied to lr. If the difference between new and old lr is smaller than epsilon,
1358
            the update is ignored. Default: 1e-8.
1359 1360
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False``.

G
guguguzi 已提交
1361

1362
    Returns:
1363
        ``ReduceOnPlateau`` instance to schedule learning rate.
1364 1365 1366 1367


    Examples:
        .. code-block:: python
1368
            :name: code-example1
1369

1370
            # Example1: train on default dynamic graph mode
1371 1372 1373
            import paddle
            import numpy as np

1374
            # train on default dynamic graph mode
1375
            linear = paddle.nn.Linear(10, 10)
1376 1377
            scheduler = paddle.optimizer.lr.ReduceOnPlateau(learning_rate=1.0, factor=0.5, patience=5, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
1378
            for epoch in range(20):
Z
Zhou Wei 已提交
1379
                for batch_id in range(5):
1380
                    x = paddle.uniform([10, 10])
1381
                    out = linear(x)
C
chentianyu03 已提交
1382
                    loss = paddle.mean(out)
1383
                    loss.backward()
1384 1385
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
1386 1387
                    scheduler.step(loss)    # If you update learning rate each step
              # scheduler.step(loss)        # If you update learning rate each epoch
1388

1389 1390 1391 1392 1393 1394
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1395 1396 1397 1398
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
1399 1400
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
1401 1402
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
1403
                scheduler = paddle.optimizer.lr.ReduceOnPlateau(learning_rate=1.0, factor=0.5, patience=5, verbose=True)
1404 1405 1406 1407 1408 1409
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
1410
                for batch_id in range(5):
1411 1412 1413 1414 1415 1416
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
1417
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
1418 1419
                    scheduler.step(out[0])    # If you update learning rate each step
              # scheduler.step(out[0])        # If you update learning rate each epoch
1420 1421 1422

    """

1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    def __init__(
        self,
        learning_rate,
        mode='min',
        factor=0.1,
        patience=10,
        threshold=1e-4,
        threshold_mode='rel',
        cooldown=0,
        min_lr=0,
        epsilon=1e-8,
        verbose=False,
    ):
1436 1437 1438 1439 1440 1441 1442
        mode = mode.lower()
        if mode not in ['min', 'max']:
            raise ValueError('mode: ' + mode + ' is unknown!')
        self.mode = mode

        if factor >= 1.0:
            raise ValueError(
1443 1444
                'new_lr = origin_lr * gamma and gamma should be < 1.0.'
            )
1445 1446 1447 1448
        self.factor = factor

        threshold_mode = threshold_mode.lower()
        if threshold_mode not in ['rel', 'abs']:
1449 1450 1451
            raise ValueError(
                'threshold mode: ' + threshold_mode + ' is unknown!'
            )
1452 1453 1454
        self.threshold_mode = threshold_mode
        if not isinstance(learning_rate, (float, int)):
            raise TypeError(
1455
                "The type of 'learning_rate' in 'ReduceOnPlateau' must be 'float', but received %s."
1456 1457
                % type(learning_rate)
            )
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477

        self.patience = patience
        self.threshold = threshold
        self.threshold_mode = threshold_mode
        self.cooldown = cooldown
        self.min_lr = min_lr
        self.epsilon = epsilon

        self.cooldown_counter = 0
        self.best = None
        self.num_bad_epochs = 0

        # Can not call Parent __init__, so implement here.
        self.base_lr = float(learning_rate)
        self.last_lr = float(learning_rate)
        self.last_epoch = 0
        self.verbose = verbose
        self._var_name = None

    # "cooldown_counter / best / num_bad_epochs / last_epoch / last_lr" will be stored.
1478
    def state_keys(self):
1479
        self.keys = [
1480 1481 1482 1483 1484
            'cooldown_counter',
            'best',
            'num_bad_epochs',
            'last_epoch',
            'last_lr',
1485 1486 1487 1488
        ]

    def step(self, metrics, epoch=None):
        """
G
guguguzi 已提交
1489
        step should be called after `optimizer.step()` . It will update the learning rate in optimizer according to ``metrics`` .
1490 1491 1492
        The new learning rate will take effect on next epoch.

        Args:
G
guguguzi 已提交
1493
            metrics (Tensor|numpy.ndarray|float): Which will be monitored to determine whether the learning rate will reduce.
1494
                If it stop descending for a ``patience`` number of epochs, the learning rate will reduce. If it's 'Tensor' or
1495
                'numpy.ndarray', its numel must be 1.
1496 1497 1498 1499
            epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1.

        Returns:
            None
G
guguguzi 已提交
1500

1501
        Examples:
1502
            Please refer to the example of current LRScheduler.
1503 1504 1505 1506 1507 1508
        """
        if epoch is None:
            self.last_epoch = self.last_epoch + 1
        else:
            self.last_epoch = epoch

1509
        # loss must be float, numpy.ndarray or 1-D Tensor with numel 1
1510
        if isinstance(metrics, (core.eager.Tensor, numpy.ndarray)):
1511 1512
            assert metrics.size == 1, (
                "the size of metrics must be 1, but the current metrics.size is {}. Maybe that "
1513
                "you should call paddle.mean to process it first.".format(
1514
                    metrics.size
1515 1516 1517 1518 1519
                )
            )
        elif not isinstance(
            metrics, (int, float, numpy.float32, numpy.float64)
        ):
1520
            raise TypeError(
1521
                "metrics must be 'int', 'float', 'np.float64', 'numpy.ndarray' or 'paddle.Tensor', but receive {}".format(
1522 1523 1524
                    type(metrics)
                )
            )
1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541

        if self.cooldown_counter > 0:
            self.cooldown_counter -= 1
        else:
            if self.best is None or self._is_better(metrics, self.best):
                self.best = metrics
                self.num_bad_epochs = 0
            else:
                self.num_bad_epochs += 1

            if self.num_bad_epochs > self.patience:
                self.cooldown_counter = self.cooldown
                self.num_bad_epochs = 0
                new_lr = max(self.last_lr * self.factor, self.min_lr)
                if self.last_lr - new_lr > self.epsilon:
                    self.last_lr = new_lr
                    if self.verbose:
1542 1543 1544 1545 1546 1547 1548
                        print(
                            'Epoch {}: {} set learning rate to {}.'.format(
                                self.last_epoch,
                                self.__class__.__name__,
                                self.last_lr,
                            )
                        )
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563

    def _is_better(self, current, best):
        if self.mode == 'min' and self.threshold_mode == 'rel':
            return current < best - best * self.threshold

        elif self.mode == 'min' and self.threshold_mode == 'abs':
            return current < best - self.threshold

        elif self.mode == 'max' and self.threshold_mode == 'rel':
            return current > best + best * self.threshold

        else:
            return current > best + self.threshold


1564
class CosineAnnealingDecay(LRScheduler):
1565
    r"""
1566

G
guguguzi 已提交
1567 1568
    Set the learning rate using a cosine annealing schedule, where :math:`\eta_{max}` is set to
    the initial learning_rate. :math:`T_{cur}` is the number of epochs since the last restart in
1569
    SGDR.
1570 1571 1572 1573

    The algorithm can be described as following.

    .. math::
1574

1575 1576
        \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1
        + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right),
G
guguguzi 已提交
1577
        & T_{cur} \neq (2k+1)T_{max};
1578 1579 1580 1581

        \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min})
        \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right),
        & T_{cur} = (2k+1)T_{max}.
G
guguguzi 已提交
1582 1583

    It has been proposed in `SGDR: Stochastic Gradient Descent with Warm Restarts <https://arxiv.org/abs/1608.03983>`_.
1584
    Note that this only implements the cosine annealing part of SGDR, and not the restarts.
G
guguguzi 已提交
1585

1586 1587
    Args:
        learning_rate (float): The initial learning rate, that is :math:`\eta_{max}` . It can be set to python float or int number.
1588
        T_max (int): Maximum number of iterations. It is half of the decay cycle of learning rate. It must be a positive integer.
1589 1590
        eta_min (float|int, optional): Minimum learning rate, that is :math:`\eta_{min}` . Default: 0.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
1591
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
1592 1593

    Returns:
1594
        ``CosineAnnealingDecay`` instance to schedule learning rate.
1595 1596

    Examples:
G
guguguzi 已提交
1597

1598
        .. code-block:: python
1599
            :name: code-example1
1600

1601
            # Example1: train on default dynamic graph mode
1602 1603 1604
            import paddle
            import numpy as np

1605
            # train on default dynamic graph mode
1606
            linear = paddle.nn.Linear(10, 10)
1607 1608
            scheduler = paddle.optimizer.lr.CosineAnnealingDecay(learning_rate=0.5, T_max=10, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
1609
            for epoch in range(20):
Z
Zhou Wei 已提交
1610
                for batch_id in range(5):
1611
                    x = paddle.uniform([10, 10])
1612
                    out = linear(x)
C
chentianyu03 已提交
1613
                    loss = paddle.mean(out)
1614
                    loss.backward()
1615 1616
                    sgd.step()
                    sgd.clear_gradients()
Z
Zhou Wei 已提交
1617 1618
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1619

1620 1621 1622 1623 1624 1625
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1626 1627 1628 1629
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
1630 1631
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
1632 1633
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
1634
                scheduler = paddle.optimizer.lr.CosineAnnealingDecay(learning_rate=0.5, T_max=10, verbose=True)
1635 1636 1637 1638 1639 1640
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(20):
Z
Zhou Wei 已提交
1641
                for batch_id in range(5):
1642 1643 1644 1645 1646 1647
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
1648
                        fetch_list=loss.name)
Z
Zhou Wei 已提交
1649 1650
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch
1651 1652
    """

1653 1654 1655
    def __init__(
        self, learning_rate, T_max, eta_min=0, last_epoch=-1, verbose=False
    ):
1656 1657
        if not isinstance(T_max, int):
            raise TypeError(
1658
                "The type of 'T_max' in 'CosineAnnealingDecay' must be 'int', but received %s."
1659 1660
                % type(T_max)
            )
1661 1662
        if not isinstance(eta_min, (float, int)):
            raise TypeError(
1663
                "The type of 'eta_min' in 'CosineAnnealingDecay' must be 'float, int', but received %s."
1664 1665
                % type(eta_min)
            )
1666
        assert T_max > 0 and isinstance(
1667 1668
            T_max, int
        ), " 'T_max' must be a positive integer."
1669 1670
        self.T_max = T_max
        self.eta_min = float(eta_min)
1671
        super().__init__(learning_rate, last_epoch, verbose)
1672 1673 1674 1675 1676

    def get_lr(self):
        if self.last_epoch == 0:
            return self.base_lr
        elif (self.last_epoch - 1 - self.T_max) % (2 * self.T_max) == 0:
1677 1678 1679 1680 1681 1682
            return (
                self.last_lr
                + (self.base_lr - self.eta_min)
                * (1 - math.cos(math.pi / self.T_max))
                / 2
            )
1683 1684

        return (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / (
1685 1686
            1 + math.cos(math.pi * (self.last_epoch - 1) / self.T_max)
        ) * (self.last_lr - self.eta_min) + self.eta_min
1687 1688

    def _get_closed_form_lr(self):
1689 1690 1691 1692 1693 1694
        return (
            self.eta_min
            + (self.base_lr - self.eta_min)
            * (1 + math.cos(math.pi * self.last_epoch / self.T_max))
            / 2
        )
G
guguguzi 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747


class MultiplicativeDecay(LRScheduler):
    """
    Multiply the learning rate of ``optimizer`` by the factor given in function ``lr_lambda`` .

    The algorithm can be described as the code below.

    .. code-block:: text

        learning_rate = 0.5        # init learning_rate
        lr_lambda = lambda epoch: 0.95

        learning_rate = 0.5        # epoch 0,
        learning_rate = 0.475      # epoch 1, 0.5*0.95
        learning_rate = 0.45125    # epoch 2, 0.475*0.95

    Args:
        learning_rate (float): The initial learning rate. It is a python float number.
        lr_lambda (function): A function which computes a factor by ``epoch`` , and then multiply the last learning rate by this factor.
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .

    Returns:
        ``MultiplicativeDecay`` instance to schedule learning rate.

    Examples:

        .. code-block:: python

            import paddle

            # train on default dynamic graph mode
            linear = paddle.nn.Linear(10, 10)
            scheduler = paddle.optimizer.lr.MultiplicativeDecay(learning_rate=0.5, lr_lambda=lambda x:0.95, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
            for epoch in range(20):
                for batch_id in range(5):
                    x = paddle.uniform([10, 10])
                    out = linear(x)
                    loss = paddle.mean(out)
                    loss.backward()
                    sgd.step()
                    sgd.clear_gradients()
                    scheduler.step()    # If you update learning rate each step
              # scheduler.step()        # If you update learning rate each epoch

    """

    def __init__(self, learning_rate, lr_lambda, last_epoch=-1, verbose=False):
        if not callable(lr_lambda):
            raise TypeError(
                "The type of 'lr_lambda' in 'MultiplicativeDecay' must be 'function', but received %s."
1748 1749
                % type(lr_lambda)
            )
G
guguguzi 已提交
1750 1751

        self.lr_lambda = lr_lambda
1752
        super().__init__(learning_rate, last_epoch, verbose)
G
guguguzi 已提交
1753 1754

    def get_lr(self):
1755 1756 1757 1758
        cur_lr = self.base_lr
        for epoch in range(1, self.last_epoch + 1):
            cur_lr = cur_lr * self.lr_lambda(epoch)
        return cur_lr
1759 1760 1761 1762


class OneCycleLR(LRScheduler):
    r"""
1763

1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    Sets the learning rate according to the one cycle learning rate scheduler.
    The scheduler adjusts the learning rate from an initial learning rate to the maximum learning rate and then
    from that maximum learning rate to the minimum learning rate, which is much less than the initial learning rate.

    It has been proposed in `Super-Convergence: Very Fast Training of Neural Networks Using Large Learning Rates <https://arxiv.org/abs/1708.07120>`_.

    Please note that the default behaviour of this scheduler follows the fastai implementation of one cycle,
    which claims that “unpublished work has shown even better results by using only two phases”.
    If you want the behaviour of this scheduler to be consistent with the paper, please set ``three_phase=True`` .

    Also note that you should update learning rate each step.

    Args:
1777
        max_learning_rate (float): The maximum learning rate. It is a python float number. Functionally, it defines the initial learning rate by ``divide_factor`` .
1778
        total_steps (int): Number of total training steps.
1779
        divide_factor (float, optional): Initial learning rate will be determined by initial_learning_rate = max_learning_rate / divide_factor. Default: 25.
1780 1781
        end_learning_rate (float, optional): The minimum learning rate during training, it should be much less than initial learning rate.
        phase_pct (float): The percentage of total steps which used to increasing learning rate. Default: 0.3.
1782
        anneal_strategy (str, optional): Strategy of adjusting learning rate.'cos' for cosine annealing, 'linear' for linear annealing. Default: 'cos'.
1783
        three_phase (bool, optional): Whether to use three phase.
1784

1785
            If ``True``:
1786

1787 1788 1789
                1. The learning rate will first increase from initial learning rate to maximum learning rate.
                2. Then it will decrease to initial learning rate. Number of step in this phase is the same as the one in first phase.
                3. Finally, it will decrease to minimum learning rate which is much less than initial learning rate.
1790

1791
            If ``False``:
1792

1793 1794
                1. The learning rate will increase to maximum learning rate.
                2. Then it will directly decrease to minimum learning rate.
1795

1796 1797 1798 1799 1800 1801 1802 1803
        last_epoch (int, optional):  The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
        verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .

    Returns:
        ``OneCycleLR`` instance to schedule learning rate.

    Examples:
        .. code-block:: python
1804
            :name: code-example1
1805

1806
            # Example1: train on default dynamic graph mode
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
            import paddle
            import numpy as np

            # train on default dynamic graph mode
            linear = paddle.nn.Linear(10, 10)
            scheduler = paddle.optimizer.lr.OneCycleLR(max_learning_rate=1.0, total_steps=100, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
            for epoch in range(5):
                for batch_id in range(20):
                    x = paddle.uniform([10, 10])
                    out = linear(x)
                    loss = paddle.mean(out)
                    loss.backward()
                    sgd.step()
                    sgd.clear_gradients()
                    scheduler.step()        # You should update learning rate each step

1824 1825 1826 1827 1828 1829
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
                scheduler = paddle.optimizer.lr.OneCycleLR(max_learning_rate=1.0, total_steps=100, verbose=True)
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(5):
                for batch_id in range(20):
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
                        fetch_list=loss.name)
                    scheduler.step()    # You should update learning rate each step
1854

1855 1856
    """

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    def __init__(
        self,
        max_learning_rate,
        total_steps,
        divide_factor=25.0,
        end_learning_rate=0.0001,
        phase_pct=0.3,
        anneal_strategy='cos',
        three_phase=False,
        last_epoch=-1,
        verbose=False,
    ):
1869 1870 1871
        # Check type and value of max_learning_rate
        if not isinstance(max_learning_rate, (float, int)):
            raise TypeError(
1872 1873 1874 1875
                "'max_learning_rate' must be 'float' or 'int', but received {}".format(
                    type(max_learning_rate)
                )
            )
1876 1877 1878 1879 1880 1881
        if max_learning_rate < 0:
            raise ValueError("'max_learning_rate' must be a positive integer.")

        # Check type and value of end_learning_rate
        if not isinstance(end_learning_rate, (float, int)):
            raise TypeError(
1882 1883 1884 1885
                "'end_learning_rate' must be 'float' or 'int', but received {}".format(
                    type(end_learning_rate)
                )
            )
1886 1887 1888 1889 1890
        if end_learning_rate < 0:
            raise ValueError("'end_learning_rate' must be a positive integer.")

        # Check type and value of total_steps
        if not isinstance(total_steps, int):
1891 1892
            raise TypeError(
                "'total_step' must be 'int', but received {}".format(
1893 1894 1895
                    type(total_steps)
                )
            )
1896 1897 1898 1899 1900 1901
        if total_steps <= 0:
            raise ValueError("'total_step' must be a positive integer.")
        self.total_steps = total_steps

        # Check type and value of pac_start
        if not isinstance(phase_pct, float):
1902 1903
            raise TypeError(
                "'phase_pct' must be 'float', but received {}".format(
1904 1905 1906
                    type(phase_pct)
                )
            )
1907 1908 1909
        if phase_pct < 0 or phase_pct > 1:
            raise ValueError(
                "'phase_pct' must be between 0 and 1, but received {}".format(
1910 1911 1912
                    phase_pct
                )
            )
1913 1914 1915 1916

        # Check type and value of divide_factor
        if not isinstance(divide_factor, (float, int)):
            raise TypeError(
1917 1918 1919 1920
                "'divide_factor' must be 'float' or 'int', but received {}".format(
                    type(divide_factor)
                )
            )
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

        initial_lr = max_learning_rate / float(divide_factor)
        min_lr = float(end_learning_rate)

        if three_phase:
            if phase_pct >= 0.5:
                raise ValueError(
                    "When three_phase is True, 'phase_pct' must be less than 0.5"
                )
            # start step and end step of each phase.
            self._step_config = [
                0,
                phase_pct * self.total_steps - 1,
                2 * phase_pct * self.total_steps - 2,
                self.total_steps - 1,
                self.total_steps - 1,  # for the last step.
            ]
            # step size of each phase.
            self._steps_size = [
                self._step_config[1] - self._step_config[0],
                self._step_config[2] - self._step_config[1],
                self._step_config[3] - self._step_config[2],
1943 1944
                self._step_config[3]
                - self._step_config[2],  # for the last step.
1945 1946 1947
            ]
            # start lr and end lr of each phase.
            self._lr_config = [
1948 1949 1950 1951
                initial_lr,
                max_learning_rate,
                initial_lr,
                min_lr,
1952 1953 1954
            ]
        else:
            self._step_config = [
1955 1956 1957 1958
                0,
                phase_pct * self.total_steps - 1,
                self.total_steps - 1,
                self.total_steps - 1,
1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
            ]
            self._steps_size = [
                self._step_config[1] - self._step_config[0],
                self._step_config[2] - self._step_config[1],
                self._step_config[2] - self._step_config[1],
            ]
            self._lr_config = [initial_lr, max_learning_rate, min_lr]

        # Check anneal_strategy
        if anneal_strategy == 'cos':
            self.anneal_func = self._cos_annealing
        elif anneal_strategy == 'linear':
            self.anneal_func = self._linear_annealing
        else:
            raise ValueError(
1974 1975 1976 1977
                "'anneal_strategy' must by one of 'cos' or 'linear', but received {}".format(
                    anneal_strategy
                )
            )
1978
        super().__init__(initial_lr, last_epoch, verbose)
1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991

    def _cos_annealing(self, start_lr, end_lr, pct):
        cos_out = math.cos(math.pi * pct) + 1
        return end_lr + (start_lr - end_lr) / 2.0 * cos_out

    def _linear_annealing(self, start_lr, end_lr, pct):
        return (end_lr - start_lr) * pct + start_lr

    def get_lr(self):
        current_step = self.last_epoch

        if current_step > self.total_steps:
            raise ValueError(
1992 1993 1994 1995
                "Tried to step {} times. However the number of total steps is {}".format(
                    current_step, self.total_steps
                )
            )
1996

1997
        for i, (end_step, step_size) in enumerate(
1998 1999
            zip(self._step_config[1:], self._steps_size)
        ):
2000 2001 2002 2003
            # i == len(self._lr_config) - 2 catch the last step, otherwise it will return None.
            if current_step <= end_step or i == len(self._lr_config) - 2:
                # self._step_config[i] means start step of a phase.
                percentage = (current_step - self._step_config[i]) / step_size
2004 2005 2006
                return self.anneal_func(
                    self._lr_config[i], self._lr_config[i + 1], percentage
                )
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049


class CyclicLR(LRScheduler):
    r"""
    Set the learning rate according to the cyclic learning rate (CLR) scheduler.
    The scheduler regards the process of learning rate adjustment as one cycle after another.
    It cycles the learning rate between two boundaries with a constant frequency.
    The distance between the two boundaries can be scaled on a per-iteration or per-cycle basis.

    It has been proposed in `Cyclic Learning Rates for Training Neural Networks <https://arxiv.org/abs/1506.01186>`_.

    According to the paper, the cyclic learning rate schedule has three build-in scale methods:

    * "triangular": A basic triangular cycle without any amplitude scaling.
    * "triangular2": A basic triangular cycle that reduce initial amplitude by half each cycle.
    * "exp_range": A cycle that scales initial amplitude by scale function which is defined as :math:`gamma^{iterations}` .

    The initial amplitude is defined as max_learning_rate - base_learning_rate.
    Also note that you should update learning rate each step.

    Args:
        base_learning_rate (float): Initial learning rate, which is the lower boundary in the cycle. The paper recommends
            that set the base_learning_rate to 1/3 or 1/4 of max_learning_rate.
        max_learning_rate (float): Maximum learning rate in the cycle. It defines the cycle amplitude as above.
            Since there is some scaling operation during process of learning rate adjustment,
            max_learning_rate may not actually be reached.
        step_size_up (int): Number of training steps, which is used to increase learning rate in a cycle.
            The step size of one cycle will be defined by step_size_up + step_size_down. According to the paper, step
            size should be set as at least 3 or 4 times steps in one epoch.
        step_size_down (int, optional): Number of training steps, which is used to decrease learning rate in a cycle.
            If not specified, it's value will initialize to `` step_size_up `` . Default: None
        mode (str, optional): one of 'triangular', 'triangular2' or 'exp_range'.
            If scale_fn is specified, this argument will be ignored. Default: 'triangular'
        exp_gamma (float): Constant in 'exp_range' scaling function: exp_gamma**iterations. Used only when mode = 'exp_range'. Default: 1.0
        scale_fn (function, optional): A custom scaling function, which is used to replace three build-in methods.
            It should only have one argument. For all x >= 0, 0 <= scale_fn(x) <= 1.
            If specified, then 'mode' will be ignored. Default: None
        scale_mode (str, optional): One of 'cycle' or 'iterations'. Defines whether scale_fn is evaluated on cycle
            number or cycle iterations (total iterations since start of training). Default: 'cycle'
        last_epoch (int, optional): The index of last epoch. Can be set to restart training.Default: -1, means initial learning rate.
        verbose: (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .

    Returns:
2050
        ``CyclicLR`` instance to schedule learning rate.
2051 2052 2053

    Examples:
        .. code-block:: python
2054
            :name: code-example1
2055

2056
            # Example1: train on default dynamic graph mode
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
            import paddle
            import numpy as np

            # train on default dynamic graph mode
            linear = paddle.nn.Linear(10, 10)
            scheduler = paddle.optimizer.lr.CyclicLR(base_learning_rate=0.5, max_learning_rate=1.0, step_size_up=15, step_size_down=5, verbose=True)
            sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
            for epoch in range(5):
                for batch_id in range(20):
                    x = paddle.uniform([10, 10])
                    out = linear(x)
                    loss = paddle.mean(out)
                    loss.backward()
                    sgd.step()
                    sgd.clear_gradients()
                    scheduler.step()        # You should update learning rate each step

2074 2075 2076 2077 2078 2079
        .. code-block:: python
            :name: code-example2

            # Example2: train on static graph mode
            import paddle
            import numpy as np
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
            paddle.enable_static()
            main_prog = paddle.static.Program()
            start_prog = paddle.static.Program()
            with paddle.static.program_guard(main_prog, start_prog):
                x = paddle.static.data(name='x', shape=[None, 4, 5])
                y = paddle.static.data(name='y', shape=[None, 4, 5])
                z = paddle.static.nn.fc(x, 100)
                loss = paddle.mean(z)
                scheduler = paddle.optimizer.lr.CyclicLR(base_learning_rate=0.5,
                    max_learning_rate=1.0, step_size_up=15, step_size_down=5, verbose=True)
                sgd = paddle.optimizer.SGD(learning_rate=scheduler)
                sgd.minimize(loss)

            exe = paddle.static.Executor()
            exe.run(start_prog)
            for epoch in range(5):
                for batch_id in range(20):
                    out = exe.run(
                        main_prog,
                        feed={
                            'x': np.random.randn(3, 4, 5).astype('float32'),
                            'y': np.random.randn(3, 4, 5).astype('float32')
                        },
                        fetch_list=loss.name)
                    scheduler.step()    # You should update learning rate each step
    """

2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
    def __init__(
        self,
        base_learning_rate,
        max_learning_rate,
        step_size_up,
        step_size_down=None,
        mode='triangular',
        exp_gamma=1.0,
        scale_fn=None,
        scale_mode='cycle',
        last_epoch=-1,
        verbose=False,
    ):
2120 2121 2122
        # check type and value of max_learning_rate
        if not isinstance(max_learning_rate, (float, int)):
            raise TypeError(
2123 2124 2125 2126
                "'max_learning_rate' must be 'float' or 'int', but received {}".format(
                    type(max_learning_rate)
                )
            )
2127 2128
        if max_learning_rate < 0:
            raise ValueError(
2129 2130 2131 2132
                "'max_learning_rate' must be a positive integer, but received {}".format(
                    max_learning_rate
                )
            )
2133 2134 2135 2136

        # check type and value of step_size_up
        if not isinstance(step_size_up, int):
            raise TypeError(
2137 2138 2139 2140
                "The type of 'step_size_up' must be int, but received {}".format(
                    type(step_size_up)
                )
            )
2141 2142
        if step_size_up <= 0:
            raise ValueError(
2143 2144 2145 2146
                "'step_size_up' must be a positive integer, but received {}".format(
                    step_size_up
                )
            )
2147 2148 2149 2150 2151

        # check type and value of step_size_down
        if step_size_down is not None:
            if not isinstance(step_size_down, int):
                raise TypeError(
2152 2153 2154 2155
                    "The type of 'step_size_down' must be int, but received {}".format(
                        type(step_size_down)
                    )
                )
2156 2157
            if step_size_down <= 0:
                raise ValueError(
2158 2159 2160 2161
                    "'step_size_down' must be a positive integer, but received {}".format(
                        step_size_down
                    )
                )
2162 2163 2164 2165 2166

        # check type of exp_gamma
        if not isinstance(exp_gamma, float):
            raise TypeError(
                "The type of 'exp_gamma' must be float, but received {}".format(
2167 2168 2169
                    type(exp_gamma)
                )
            )
2170 2171

        step_size_up = float(step_size_up)
2172 2173 2174 2175 2176
        step_size_down = (
            float(step_size_down)
            if step_size_down is not None
            else step_size_up
        )
2177 2178 2179 2180 2181 2182

        self.cycle_size = step_size_up + step_size_down
        self.step_up_pct = step_size_up / self.cycle_size
        self.max_lr = float(max_learning_rate)
        self.amplitude = self.max_lr - base_learning_rate

2183 2184 2185 2186
        if (
            mode not in ['triangular', 'triangular2', 'exp_range']
            and scale_fn is None
        ):
2187 2188 2189 2190 2191
            raise ValueError(
                "'mode' is invalid and 'scale_fn' is not specified, make sure one of 'mode' or 'scale_fn' is valid"
            )
        if scale_mode not in ['cycle', 'iterations']:
            raise ValueError(
2192 2193
                "'scale_mode' must be one of 'cycle' or 'iterations"
            )
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213

        self.mode = mode
        self.gamma = exp_gamma  # only for exp_range mode

        if scale_fn is None:
            if self.mode == 'triangular':
                self.scale_fn = self._triangular_scale_fn
                self.scale_mode = 'cycle'
            elif self.mode == 'triangular2':
                self.scale_fn = self._triangular2_scale_fn
                self.scale_mode = 'cycle'
            elif self.mode == 'exp_range':
                self.scale_fn = self._exp_range_scale_fn
                self.scale_mode = 'iterations'
        else:
            self.scale_fn = scale_fn
            self.scale_mode = scale_mode
        super().__init__(base_learning_rate, last_epoch, verbose)

    def _triangular_scale_fn(self, x):
2214
        return 1.0
2215 2216

    def _triangular2_scale_fn(self, x):
2217
        return 1 / (2.0 ** (x - 1))
2218 2219 2220 2221 2222 2223 2224 2225

    def _exp_range_scale_fn(self, x):
        return self.gamma**x

    def get_lr(self):
        iterations = self.last_epoch

        cycle = 1 + iterations // self.cycle_size
2226
        pct_per_cycle = 1.0 + iterations / self.cycle_size - cycle
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237

        if pct_per_cycle <= self.step_up_pct:
            scale_factor = pct_per_cycle / self.step_up_pct
        else:
            scale_factor = (1 - pct_per_cycle) / (1 - self.step_up_pct)

        base_height = self.amplitude * scale_factor

        lr = self.base_lr + base_height * self.scale_fn(eval(self.scale_mode))

        return lr
D
Difer 已提交
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833


def autoincreased_step_counter(counter_name=None, begin=1, step=1):
    """
    :api_attr: Static Graph

    Create an auto-increase variable. which will be automatically increased
    by 1 in every iteration. By default, the first return of this counter is 1,
    and the step size is 1.

    Args:
        counter_name(str, optional): The counter name. Default '@STEP_COUNTER@'.
        begin(int, optional): The first return value of this counter. Default 1.
        step(int, optional): The step size. Default 1.

    Returns:
        Variable: The auto-increased Variable with data type int64.

    Examples:
        .. code-block:: python

           import paddle
           paddle.enable_static()
           global_step = paddle.optimizer.lr.autoincreased_step_counter(
               counter_name='@LR_DECAY_COUNTER@', begin=0, step=1)
    """
    helper = LayerHelper('global_step_counter')
    if counter_name is None:
        counter_name = '@STEP_COUNTER@'
    counter, is_new_var = helper.create_or_get_global_variable(
        name=counter_name,
        dtype='int64',
        shape=[1],
        persistable=True,
        belong_to_optimizer=True,
    )
    if is_new_var:
        helper.set_variable_initializer(
            counter,
            initializer=paddle.nn.initializer.ConstantInitializer(
                value=begin - 1, force_cpu=True
            ),
        )
        helper.main_program.global_block()._prepend_op(
            type='increment',
            inputs={'X': [counter]},
            outputs={'Out': [counter]},
            attrs={'step': float(step)},
        )
        counter.stop_gradient = True

    return counter


def _decay_step_counter(begin=0):
    # the first global step is zero in learning rate decay
    global_step = autoincreased_step_counter(
        counter_name='@LR_DECAY_COUNTER@', begin=begin, step=1
    )
    global_step = paddle.cast(global_step, 'float32')
    return global_step


def noam_decay(d_model, warmup_steps, learning_rate=1.0):
    """

    Noam decay method. The numpy implementation of noam decay as follows.

    .. code-block:: python

      import paddle.fluid as fluid
      import numpy as np
      # set hyper parameters
      base_lr = 0.01
      d_model = 2
      current_steps = 20
      warmup_steps = 200
      # compute
      lr_value = base_lr * np.power(d_model, -0.5) * np.min([
                              np.power(current_steps, -0.5),
                              np.power(warmup_steps, -1.5) * current_steps])

    Please reference `attention is all you need
    <https://arxiv.org/pdf/1706.03762.pdf>`_.

    Args:
        d_model(Variable): The dimensionality of input and output of model.

        warmup_steps(Variable): A super parameter.

        learning_rate(Variable|float|int): The initial learning rate. If the type
            is Variable, it's a tensor with shape [1], the data type can be
            float32 or float64. It also can be set to python int number. Default 1.0

    Returns:
        The decayed learning rate.
    Examples:
        .. code-block:: python

          import paddle
          warmup_steps = 100
          learning_rate = 0.01
          lr = paddle.optimizer.lr.noam_decay(
                         1/(warmup_steps *(learning_rate ** 2)),
                         warmup_steps,
                         learning_rate)
    """
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = paddle.optimizer.lr.NoamDecay(
                d_model, warmup_steps, learning_rate=learning_rate
            )
            return decay
        else:
            global_step = _decay_step_counter(1)

            a = global_step**-0.5
            b = (warmup_steps**-1.5) * global_step
            lr_value = learning_rate * (d_model**-0.5) * paddle.minimum(a, b)

            return lr_value


def exponential_decay(learning_rate, decay_steps, decay_rate, staircase=False):
    """

    Applies exponential decay to the learning rate.

    When training a model, it is often recommended to lower the learning rate as the
    training progresses. By using this function, the learning rate will be decayed by
    'decay_rate' every 'decay_steps' steps.

    Decayed learning rate calculates as follows:

    >>> if staircase == True:
    >>>     decayed_learning_rate = learning_rate * decay_rate ^ floor(global_step / decay_steps)
    >>> else:
    >>>     decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)

    Args:
        learning_rate(Variable|float): The initial learning rate. It should be a Variable
                                       or a float
        decay_steps(int): The learning rate decay steps. See the decay computation above.
        decay_rate(float): The learning rate decay rate. See the decay computation above.
        staircase(bool): If True, decay the learning rate at discrete intervals, which
                         means the learning rate will be decayed by `decay_rate` every
                         `decay_steps`. If False, learning rate will be decayed continuously
                         and following the formula above. Default: False

    Returns:
        Variable: The decayed learning rate. The data type is float32.

    Examples:
        .. code-block:: python

          import paddle

          paddle.enable_static()
          base_lr = 0.1
          sgd_optimizer = fluid.optimizer.SGD(
              learning_rate=paddle.optimizer.lr.exponential_decay(
                    learning_rate=base_lr,
                    decay_steps=10000,
                    decay_rate=0.5,
                    staircase=True))

    """
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = ExponentialDecay(learning_rate, decay_rate)
            return decay
        else:
            global_step = _decay_step_counter()

            div_res = global_step / decay_steps
            if staircase:
                div_res = paddle.floor(div_res)
            decayed_lr = learning_rate * (decay_rate**div_res)

            return decayed_lr


def natural_exp_decay(learning_rate, decay_steps, decay_rate, staircase=False):
    """

    Applies natural exponential decay to the initial learning rate.

        When training a model, it is often recommended to lower the learning rate as the
        training progresses. By using this function, the learning rate will be decayed by
        natural exponential power 'decay_rate' every 'decay_steps' steps.

        Decayed learning rate calculates as follows:

        >>> if not staircase:
        >>>     decayed_learning_rate = learning_rate * exp(- decay_rate * (global_step / decay_steps))
        >>> else:
        >>>     decayed_learning_rate = learning_rate * exp(- decay_rate * floor(global_step / decay_steps))

        Args:
            learning_rate(Variable|float): The initial learning rate. It should be a Variable
                                           or a float
            decay_steps(int): The learning rate decay steps. See the decay computation above.
            decay_rate(float): The learning rate decay rate. See the decay computation above.
            staircase(bool): If True, decay the learning rate at discrete intervals, which
                             means the learning rate will be decayed by natural exponential power
                             `decay_rate` every `decay_steps`. If False, learning rate will be
                             decayed continuously and following the formula above. Default: False

        Returns:
            The decayed learning rate. The data type is float32.

        Examples:
            .. code-block:: python

              import paddle.fluid as fluid
              import paddle

              paddle.enable_static()
              base_lr = 0.1
              sgd_optimizer = fluid.optimizer.SGD(
                  learning_rate=paddle.optimizer.lr.natural_exp_decay(
                        learning_rate=base_lr,
                        decay_steps=10000,
                        decay_rate=0.5,
                        staircase=True))

    """
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = NaturalExpDecay(learning_rate, decay_rate)
            return decay
        else:
            global_step = _decay_step_counter()

            div_res = global_step / decay_steps
            if staircase:
                div_res = paddle.floor(div_res)
            decayed_lr = learning_rate * paddle.exp(-1 * decay_rate * div_res)

            return decayed_lr


def inverse_time_decay(learning_rate, decay_steps, decay_rate, staircase=False):
    """

    Applies inverse time decay to the initial learning rate.

    When training a model, it is often recommended to lower the learning rate as the
    training progresses. By using this function, an inverse decay function will be
    applied to the initial learning rate.

    Decayed learning rate calculates as follows:

    >>> if staircase == True:
    >>>     decayed_learning_rate = learning_rate / (1 + decay_rate * floor(global_step / decay_step))
    >>> else:
    >>>     decayed_learning_rate = learning_rate / (1 + decay_rate * global_step / decay_step)

    Args:
        learning_rate(Variable|float): The initial learning rate. It should be a Variable
                                       or a float
        decay_steps(int): The learning rate decay steps. See the decay computation above.
        decay_rate(float): The learning rate decay rate. See the decay computation above.
        staircase(bool): If True, decay the learning rate at discrete intervals, which
                         means the learning rate will be decayed by `decay_rate` times
                         every `decay_steps`. If False, learning rate will be decayed
                         continuously and following the formula above. Default: False

    Returns:
        Variable: The decayed learning rate. The data type is float32.

    Examples:
        .. code-block:: python

          import paddle.fluid as fluid
          import paddle
          paddle.enable_static()
          base_lr = 0.1
          sgd_optimizer = fluid.optimizer.SGD(
              learning_rate=paddle.optimizer.lr.inverse_time_decay(
                    learning_rate=base_lr,
                    decay_steps=10000,
                    decay_rate=0.5,
                    staircase=True))
    """
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = InverseTimeDecay(learning_rate, decay_rate)
            return decay
        else:
            global_step = _decay_step_counter()

            div_res = global_step / decay_steps
            if staircase:
                div_res = paddle.floor(div_res)

            decayed_lr = learning_rate / (1 + decay_rate * div_res)

            return decayed_lr


def polynomial_decay(
    learning_rate, decay_steps, end_learning_rate=0.0001, power=1.0, cycle=False
):
    """
    Applies polynomial decay to the initial learning rate.

    .. code-block:: text

     if cycle:
       decay_steps = decay_steps * ceil(global_step / decay_steps)
     else:
       global_step = min(global_step, decay_steps)
       decayed_learning_rate = (learning_rate - end_learning_rate) *
            (1 - global_step / decay_steps) ^ power + end_learning_rate

    Args:
        learning_rate(Variable|float32): A scalar float32 value or a Variable. This
          will be the initial learning rate during training.
        decay_steps(int32): A Python `int32` number.
        end_learning_rate(float): A Python `float` number.
        power(float): A Python `float` number.
        cycle(bool): If set true, decay the learning rate every decay_steps.

    Returns:
        Variable: The decayed learning rate

    Examples:
        .. code-block:: python

          import paddle
          start_lr = 0.01
          total_step = 5000
          end_lr = 0
          lr = paddle.optimizer.lr.polynomial_decay(
              start_lr, total_step, end_lr, power=1)

    """
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = PolynomialDecay(
                learning_rate, decay_steps, end_learning_rate, power, cycle
            )
            return decay
        else:
            global_step = _decay_step_counter()

            if cycle:
                div_res = paddle.ceil(global_step / decay_steps)
                zero_var = paddle.tensor.fill_constant(
                    shape=[1], dtype='float32', value=0.0
                )
                one_var = paddle.tensor.fill_constant(
                    shape=[1], dtype='float32', value=1.0
                )

                div_val = paddle.static.nn.cond(
                    global_step == zero_var, lambda: one_var, lambda: div_res
                )
                paddle.assign(div_val, output=div_res)

                decay_steps = decay_steps * div_res
            else:
                decay_steps_var = paddle.tensor.fill_constant(
                    shape=[1], dtype='float32', value=float(decay_steps)
                )
                global_step = paddle.minimum(x=global_step, y=decay_steps_var)

            decayed_lr = (learning_rate - end_learning_rate) * (
                (1 - global_step / decay_steps) ** power
            ) + end_learning_rate
            return decayed_lr


def piecewise_decay(boundaries, values):
    """

    Applies piecewise decay to the initial learning rate.

        The algorithm can be described as the code below.

        .. code-block:: text

          boundaries = [10000, 20000]
          values = [1.0, 0.5, 0.1]
          if step < 10000:
              learning_rate = 1.0
          elif 10000 <= step < 20000:
              learning_rate = 0.5
          else:
              learning_rate = 0.1
        Args:
            boundaries: A list of steps numbers.
            values: A list of learning rate values that will be picked during
                different step boundaries.

        Returns:
            The decayed learning rate.

        Examples:
            .. code-block:: python

              import paddle
              paddle.enable_static()
              boundaries = [10000, 20000]
              values = [1.0, 0.5, 0.1]
              optimizer = paddle.optimizer.Momentum(
                  momentum=0.9,
                  learning_rate=paddle.optimizer.lr.PiecewiseDecay(boundaries, values),
                  weight_decay=paddle.regularizer.L2Decay(1e-4))


    """
    with default_main_program()._lr_schedule_guard():
        if len(values) - len(boundaries) != 1:
            raise ValueError("len(values) - len(boundaries) should be 1")

        if in_dygraph_mode():
            decay = PiecewiseDecay(boundaries, values)
            return decay
        else:
            global_step = _decay_step_counter()

            lr = paddle.static.create_global_var(
                shape=[1],
                value=0.0,
                dtype='float32',
                persistable=True,
                name="learning_rate",
            )
            with paddle.static.nn.control_flow.Switch() as switch:
                for i in range(len(boundaries)):
                    boundary_val = paddle.tensor.fill_constant(
                        shape=[1],
                        dtype='float32',
                        value=float(boundaries[i]),
                        force_cpu=True,
                    )
                    with switch.case(global_step < boundary_val):
                        paddle.tensor.fill_constant(
                            shape=[1],
                            dtype="float32",
                            value=float(values[i]),
                            out=lr,
                        )
                with switch.default():
                    paddle.tensor.fill_constant(
                        shape=[1],
                        dtype="float32",
                        value=float(values[len(values) - 1]),
                        out=lr,
                    )
            return lr


def cosine_decay(learning_rate, step_each_epoch, epochs):
    r"""

    Applies cosine decay to the learning rate.

    when training a model, it is often recommended to lower the learning rate as the
    training progresses. By using this function, the learning rate will be decayed by
    following cosine decay strategy.

    .. math::

        decayed\_lr = learning\_rate * 0.5 * (math.cos * (epoch * \\frac{math.pi}{epochs} ) + 1)

    Args:
        learning_rate(Variable|float): The initial learning rate.
        step_each_epoch(int): the number of steps in an epoch.
        epochs(int): the number of epochs.

    Returns:
        Variable: The decayed learning rate.

    Examples:
        .. code-block:: python

            import paddle
            base_lr = 0.1
            lr = paddle.optimizer.lr.cosine_decay(
            learning_rate = base_lr, step_each_epoch=10000, epochs=120)
    """
    check_type(
        learning_rate, 'learning_rate', (float, Variable), 'cosine_decay'
    )

    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            decay = CosineAnnealingDecay(learning_rate, epochs)
            return decay
        else:
            global_step = _decay_step_counter()

            cur_epoch = paddle.floor(global_step / step_each_epoch)
            decayed_lr = (
                learning_rate
                * 0.5
                * (paddle.cos(cur_epoch * math.pi / epochs) + 1)
            )
            return decayed_lr


def linear_lr_warmup(learning_rate, warmup_steps, start_lr, end_lr):
    """

    This operator use the linear learning rate warm up strategy to adjust the learning rate preliminarily before the normal learning rate scheduling.
    For more information, please refer to `Bag of Tricks for Image Classification with Convolutional Neural Networks <https://arxiv.org/abs/1812.01187>`_

    When global_step < warmup_steps, learning rate is updated as:

    .. code-block:: text

            linear_step = end_lr - start_lr
            lr = start_lr + linear_step * (global_step / warmup_steps)

    where start_lr is the initial learning rate, and end_lr is the final learning rate;

    When global_step >= warmup_steps, learning rate is updated as:

    .. code-block:: text

            lr = learning_rate

    where lr is the learning_rate after warm-up.

    Args:
        learning_rate (Variable|float): Learning_rate after warm-up, it could be 1D-Tensor or single value with the data type of float32.
        warmup_steps (int): Steps for warm up.
        start_lr (float): Initial learning rate of warm up.
        end_lr (float): Final learning rate of warm up.

    Returns:
        Variable: Warm-up learning rate with the same data type as learning_rate.


    Examples:

    .. code-block:: python

        import paddle.fluid as fluid

        boundaries = [100, 200]
        lr_steps = [0.1, 0.01, 0.001]
        learning_rate = fluid.layers.piecewise_decay(boundaries, lr_steps) #case1, 1D-Tensor
        #learning_rate = 0.1  #case2, single-value
        warmup_steps = 50
        start_lr = 1. / 3.
        end_lr = 0.1
        decayed_lr = fluid.layers.linear_lr_warmup(learning_rate,
            warmup_steps, start_lr, end_lr)

        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())
        out, = exe.run(fetch_list=[decayed_lr.name])
        print(out)
        # case1: [0.33333334]
        # case2: [0.33333334]
    """
    dtype = 'float32'
    if isinstance(learning_rate, Variable):
        dtype = learning_rate.dtype

    linear_step = float(end_lr) - float(start_lr)
    with default_main_program()._lr_schedule_guard():
        if in_dygraph_mode():
            lr = LinearWarmup(learning_rate, warmup_steps, start_lr, end_lr)
            return lr
        else:
            lr = paddle.static.create_global_var(
                shape=[1],
                value=0.0,
                dtype=dtype,
                persistable=True,
                name="learning_rate_warmup",
            )

            global_step = _decay_step_counter()
            if not isinstance(learning_rate, Variable):
                learning_rate = paddle.tensor.fill_constant(
                    shape=[1], dtype=dtype, value=float(learning_rate)
                )
            lr_val = paddle.static.nn.case(
                pred_fn_pairs=[
                    (
                        global_step < warmup_steps,
                        lambda: start_lr
                        + linear_step * (global_step / float(warmup_steps)),
                    )
                ],
                default=lambda: learning_rate,
            )
            paddle.assign(lr_val, lr)
            return lr