optimization.py 7.4 KB
Newer Older
M
Meiyim 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
T
tianxin04 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
C
chenxuyi 已提交
18 19 20
from __future__ import unicode_literals
from __future__ import absolute_import

M
Meiyim 已提交
21 22
import logging
import re
T
tianxin04 已提交
23 24

import numpy as np
M
Meiyim 已提交
25 26 27
import paddle.fluid as F
import paddle.fluid.layers as L
import paddle.fluid.dygraph as D
T
tianxin04 已提交
28

M
Meiyim 已提交
29
log = logging.getLogger(__name__)
T
tianxin04 已提交
30 31 32

def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps):
    """ Applies linear warmup of learning rate from 0 and decay to 0."""
M
Meiyim 已提交
33 34
    with F.default_main_program()._lr_schedule_guard():
        lr = L.tensor.create_global_var(
T
tianxin04 已提交
35 36 37 38 39 40
            shape=[1],
            value=0.0,
            dtype='float32',
            persistable=True,
            name="scheduled_learning_rate")

M
Meiyim 已提交
41 42 43
        global_step = L.learning_rate_scheduler._decay_step_counter()
        
        warmup_lr = learning_rate * (global_step / warmup_steps)
T
tianxin04 已提交
44

M
Meiyim 已提交
45 46 47 48 49 50 51 52 53
        poly_decay_lr = L.learning_rate_scheduler.polynomial_decay(
            learning_rate=learning_rate,
            decay_steps=num_train_steps,
            end_learning_rate=0.0,
            power=1.0,
            cycle=False)
#
        decayed_lr = L.elementwise_min(warmup_lr, poly_decay_lr)
        L.assign(decayed_lr, lr)
T
tianxin04 已提交
54 55 56 57 58 59 60 61 62 63 64 65
        return lr


def optimization(loss,
                 warmup_steps,
                 num_train_steps,
                 learning_rate,
                 train_program,
                 startup_prog,
                 weight_decay,
                 scheduler='linear_warmup_decay',
                 use_fp16=False,
M
Meiyim 已提交
66
                 init_loss_scaling=128,
T
tianxin 已提交
67 68 69 70
                 incr_every_n_steps=1000,
                 decr_every_n_nan_or_inf=2,
                 incr_ratio=2.0,
                 decr_ratio=0.8):
M
Meiyim 已提交
71 72 73 74 75 76 77 78 79 80 81 82
    """do backword for static"""

    def exclude_from_weight_decay(param):
        name = param.name.rstrip('.master')
        if name.find("layer_norm") > -1:
            return True
        bias_suffix = ["_bias", "_b", ".b_0"]
        for suffix in bias_suffix:
            if name.endswith(suffix):
                return True
        return False

T
tianxin04 已提交
83 84
    if warmup_steps > 0:
        if scheduler == 'noam_decay':
M
Meiyim 已提交
85
            scheduled_lr = L.learning_rate_scheduler\
T
tianxin04 已提交
86 87 88 89 90 91 92 93
             .noam_decay(1/(warmup_steps *(learning_rate ** 2)),
                         warmup_steps)
        elif scheduler == 'linear_warmup_decay':
            scheduled_lr = linear_warmup_decay(learning_rate, warmup_steps,
                                               num_train_steps)
        else:
            raise ValueError("Unkown learning rate scheduler, should be "
                             "'noam_decay' or 'linear_warmup_decay'")
M
Meiyim 已提交
94 95
        log.debug('using Adam')
        optimizer = F.optimizer.Adam(learning_rate=scheduled_lr)
T
tianxin04 已提交
96
    else:
M
Meiyim 已提交
97 98
        scheduled_lr = L.create_global_var(
            name=F.unique_name.generate("learning_rate"),
T
tianxin 已提交
99 100 101 102
            shape=[1],
            value=learning_rate,
            dtype='float32',
            persistable=True)
M
Meiyim 已提交
103 104 105 106
        log.debug('using Adam')

        optimizer = F.optimizer.Adam(learning_rate=scheduled_lr)
        optimizer._learning_rate_map[F.default_main_program(
T
tianxin 已提交
107 108
        )] = scheduled_lr

M
Meiyim 已提交
109 110 111 112 113 114 115 116 117 118
    if use_fp16:
        log.info('AMP activated')
        optimizer = F.contrib.mixed_precision.decorate(optimizer, 
            amp_lists=F.contrib.mixed_precision.AutoMixedPrecisionLists(custom_black_varnames={"loss"}, custom_black_list={'layer_norm', 'arg_max', 'argmax'}),
            init_loss_scaling=init_loss_scaling,
            use_dynamic_loss_scaling=True,
        )
        loss_scaling = optimizer.get_loss_scaling()
    else:
        loss_scaling = None
T
tianxin04 已提交
119

M
Meiyim 已提交
120 121
    F.clip.set_gradient_clip(
        clip=F.clip.GradientClipByGlobalNorm(clip_norm=1.0))
T
tianxin04 已提交
122

M
Meiyim 已提交
123
    param_list = {}
T
tianxin 已提交
124

M
Meiyim 已提交
125 126 127
    for param in train_program.global_block().all_parameters():
        param_list[param.name] = param * 1.0
        param_list[param.name].stop_gradient = True
T
tianxin 已提交
128

M
Meiyim 已提交
129
    _, param_grads = optimizer.minimize(loss)
T
tianxin04 已提交
130

M
Meiyim 已提交
131 132 133 134 135 136 137 138 139
    if weight_decay > 0:
        for param, grad in param_grads:
            if exclude_from_weight_decay(param):
                continue
            with param.block.program._optimized_guard(
                [param, grad]), F.framework.name_scope("weight_decay"):
                updated_param = param - param_list[
                    param.name] * weight_decay * scheduled_lr
                L.assign(output=param, input=updated_param)
T
tianxin04 已提交
140

M
Meiyim 已提交
141
    return scheduled_lr, loss_scaling
T
tianxin 已提交
142

T
tianxin04 已提交
143

M
Meiyim 已提交
144 145 146 147 148 149 150 151
class AdamW(F.optimizer.AdamOptimizer):
    """AdamW object for dygraph"""
    def __init__(self, *args, **kwargs):
        weight_decay = kwargs.pop('weight_decay', None) 
        var_name_to_exclude = kwargs.pop('var_name_to_exclude', '.*layer_norm_scale|.*layer_norm_bias|.*b_0')
        super(AdamW, self).__init__(*args, **kwargs)
        self.wd = weight_decay
        self.pat = re.compile(var_name_to_exclude)
T
tianxin04 已提交
152

M
Meiyim 已提交
153 154 155 156 157 158 159
    def apply_optimize(self, loss, startup_program, params_grads):
        super(AdamW, self).apply_optimize(loss, startup_program, params_grads)
        for p, g in params_grads:
            #log.debug(L.reduce_mean(p))
            if not self.pat.match(p.name):
                L.assign(p * (1. - self.wd * self.current_step_lr()), p)
            #log.debug(L.reduce_mean(p))
T
tianxin04 已提交
160 161


M
Meiyim 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
class LinearDecay(D.learning_rate_scheduler.LearningRateDecay):
    def __init__(self,
                 learning_rate,
                 warmup_steps,
                 decay_steps,
                 end_learning_rate=0,
                 power=1.0,
                 cycle=False,
                 begin=0,
                 step=1,
                 dtype='float32'):
        super(LinearDecay, self).__init__(begin, step, dtype)
        self.learning_rate = learning_rate
        self.warmup_steps = warmup_steps
        self.decay_steps = decay_steps
        self.end_learning_rate = end_learning_rate
        self.power = power
        self.cycle = cycle

    def step(self):
        if self.step_num < self.warmup_steps:
            decayed_lr = self.learning_rate * (self.step_num /
                                               self.warmup_steps)
            decayed_lr = self.create_lr_var(decayed_lr)
        else:
            tmp_step_num = self.step_num
            tmp_decay_steps = self.decay_steps
            if self.cycle:
                div_res = fluid.layers.ceil(
                    self.create_lr_var(tmp_step_num / float(self.decay_steps)))
                if tmp_step_num == 0:
                    div_res = self.create_lr_var(1.0)
                tmp_decay_steps = self.decay_steps * div_res
            else:
                tmp_step_num = self.create_lr_var(
                    tmp_step_num
                    if tmp_step_num < self.decay_steps else self.decay_steps)
                decayed_lr = (self.learning_rate - self.end_learning_rate) * \
                    ((1 - tmp_step_num / tmp_decay_steps) ** self.power) + self.end_learning_rate

        return decayed_lr