optimizer.py 9.8 KB
Newer Older
W
WenmuZhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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
from __future__ import unicode_literals

from paddle import optimizer as optim


class Momentum(object):
    """
    Simple Momentum optimizer with velocity state.
    Args:
        learning_rate (float|Variable) - The learning rate used to update parameters.
            Can be a float value or a Variable with one float value as data element.
        momentum (float) - Momentum factor.
        regularization (WeightDecayRegularizer, optional) - The strategy of regularization.
    """

Z
zhoujun 已提交
33 34 35 36 37 38
    def __init__(self,
                 learning_rate,
                 momentum,
                 weight_decay=None,
                 grad_clip=None,
                 **args):
W
WenmuZhou 已提交
39 40 41 42
        super(Momentum, self).__init__()
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.weight_decay = weight_decay
Z
zhoujun 已提交
43
        self.grad_clip = grad_clip
W
WenmuZhou 已提交
44

T
Topdu 已提交
45
    def __call__(self, model):
46 47 48
        train_params = [
            param for param in model.parameters() if param.trainable is True
        ]
W
WenmuZhou 已提交
49 50 51
        opt = optim.Momentum(
            learning_rate=self.learning_rate,
            momentum=self.momentum,
Z
zhoujun 已提交
52 53
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
54
            parameters=train_params)
W
WenmuZhou 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        return opt


class Adam(object):
    def __init__(self,
                 learning_rate=0.001,
                 beta1=0.9,
                 beta2=0.999,
                 epsilon=1e-08,
                 parameter_list=None,
                 weight_decay=None,
                 grad_clip=None,
                 name=None,
                 lazy_mode=False,
                 **kwargs):
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.parameter_list = parameter_list
        self.learning_rate = learning_rate
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
        self.name = name
        self.lazy_mode = lazy_mode
A
add vl  
andyjpaddle 已提交
80 81
        self.group_lr = kwargs.get('group_lr', False)
        self.training_step = kwargs.get('training_step', None)
W
WenmuZhou 已提交
82

T
Topdu 已提交
83
    def __call__(self, model):
A
add vl  
andyjpaddle 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        if self.group_lr:
            if self.training_step == 'LF_2':
                import paddle
                if isinstance(model, paddle.fluid.dygraph.parallel.
                              DataParallel):  # multi gpu
                    mlm = model._layers.head.MLM_VRM.MLM.parameters()
                    pre_mlm_pp = model._layers.head.MLM_VRM.Prediction.pp_share.parameters(
                    )
                    pre_mlm_w = model._layers.head.MLM_VRM.Prediction.w_share.parameters(
                    )
                else:  # single gpu
                    mlm = model.head.MLM_VRM.MLM.parameters()
                    pre_mlm_pp = model.head.MLM_VRM.Prediction.pp_share.parameters(
                    )
                    pre_mlm_w = model.head.MLM_VRM.Prediction.w_share.parameters(
                    )

                total = []
                for param in mlm:
                    total.append(id(param))
                for param in pre_mlm_pp:
                    total.append(id(param))
                for param in pre_mlm_w:
                    total.append(id(param))

                group_base_params = [
                    param for param in model.parameters() if id(param) in total
                ]
                group_small_params = [
                    param for param in model.parameters()
                    if id(param) not in total
                ]
                train_params = [{
                    'params': group_base_params
                }, {
                    'params': group_small_params,
                    'learning_rate': self.learning_rate.values[0] * 0.1
                }]

            else:
                print(
                    'group lr currently only support VisionLAN in LF_2 training step'
                )
                train_params = [
                    param for param in model.parameters()
                    if param.trainable is True
                ]
        else:
            train_params = [
                param for param in model.parameters() if param.trainable is True
            ]

W
WenmuZhou 已提交
136 137 138 139 140 141 142 143 144
        opt = optim.Adam(
            learning_rate=self.learning_rate,
            beta1=self.beta1,
            beta2=self.beta2,
            epsilon=self.epsilon,
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
            name=self.name,
            lazy_mode=self.lazy_mode,
145
            parameters=train_params)
W
WenmuZhou 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
        return opt


class RMSProp(object):
    """
    Root Mean Squared Propagation (RMSProp) is an unpublished, adaptive learning rate method.
    Args:
        learning_rate (float|Variable) - The learning rate used to update parameters.
            Can be a float value or a Variable with one float value as data element.
        momentum (float) - Momentum factor.
        rho (float) - rho value in equation.
        epsilon (float) - avoid division by zero, default is 1e-6.
        regularization (WeightDecayRegularizer, optional) - The strategy of regularization.
    """

    def __init__(self,
                 learning_rate,
Z
zhoujun 已提交
163
                 momentum=0.0,
W
WenmuZhou 已提交
164 165 166
                 rho=0.95,
                 epsilon=1e-6,
                 weight_decay=None,
Z
zhoujun 已提交
167
                 grad_clip=None,
W
WenmuZhou 已提交
168 169 170 171 172 173 174
                 **args):
        super(RMSProp, self).__init__()
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.rho = rho
        self.epsilon = epsilon
        self.weight_decay = weight_decay
Z
zhoujun 已提交
175
        self.grad_clip = grad_clip
W
WenmuZhou 已提交
176

T
Topdu 已提交
177
    def __call__(self, model):
178 179 180
        train_params = [
            param for param in model.parameters() if param.trainable is True
        ]
W
WenmuZhou 已提交
181 182 183 184 185 186
        opt = optim.RMSProp(
            learning_rate=self.learning_rate,
            momentum=self.momentum,
            rho=self.rho,
            epsilon=self.epsilon,
            weight_decay=self.weight_decay,
Z
zhoujun 已提交
187
            grad_clip=self.grad_clip,
188
            parameters=train_params)
W
WenmuZhou 已提交
189
        return opt
T
tink2123 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210


class Adadelta(object):
    def __init__(self,
                 learning_rate=0.001,
                 epsilon=1e-08,
                 rho=0.95,
                 parameter_list=None,
                 weight_decay=None,
                 grad_clip=None,
                 name=None,
                 **kwargs):
        self.learning_rate = learning_rate
        self.epsilon = epsilon
        self.rho = rho
        self.parameter_list = parameter_list
        self.learning_rate = learning_rate
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
        self.name = name

T
Topdu 已提交
211
    def __call__(self, model):
212 213 214
        train_params = [
            param for param in model.parameters() if param.trainable is True
        ]
T
tink2123 已提交
215 216 217 218 219 220 221
        opt = optim.Adadelta(
            learning_rate=self.learning_rate,
            epsilon=self.epsilon,
            rho=self.rho,
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
            name=self.name,
222
            parameters=train_params)
T
tink2123 已提交
223
        return opt
224 225 226 227 228 229 230


class AdamW(object):
    def __init__(self,
                 learning_rate=0.001,
                 beta1=0.9,
                 beta2=0.999,
T
Topdu 已提交
231
                 epsilon=1e-8,
232
                 weight_decay=0.01,
T
Topdu 已提交
233
                 multi_precision=False,
234
                 grad_clip=None,
T
Topdu 已提交
235 236
                 no_weight_decay_name=None,
                 one_dim_param_no_weight_decay=False,
237 238
                 name=None,
                 lazy_mode=False,
T
Topdu 已提交
239 240
                 **args):
        super().__init__()
241 242 243 244
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
T
Topdu 已提交
245
        self.grad_clip = grad_clip
246 247 248 249
        self.weight_decay = 0.01 if weight_decay is None else weight_decay
        self.grad_clip = grad_clip
        self.name = name
        self.lazy_mode = lazy_mode
T
Topdu 已提交
250 251 252 253 254 255
        self.multi_precision = multi_precision
        self.no_weight_decay_name_list = no_weight_decay_name.split(
        ) if no_weight_decay_name else []
        self.one_dim_param_no_weight_decay = one_dim_param_no_weight_decay

    def __call__(self, model):
256 257 258
        parameters = [
            param for param in model.parameters() if param.trainable is True
        ]
T
Topdu 已提交
259 260

        self.no_weight_decay_param_name_list = [
261 262
            p.name for n, p in model.named_parameters()
            if any(nd in n for nd in self.no_weight_decay_name_list)
T
Topdu 已提交
263 264 265 266
        ]

        if self.one_dim_param_no_weight_decay:
            self.no_weight_decay_param_name_list += [
267
                p.name for n, p in model.named_parameters() if len(p.shape) == 1
T
Topdu 已提交
268
            ]
269

270 271 272 273 274
        opt = optim.AdamW(
            learning_rate=self.learning_rate,
            beta1=self.beta1,
            beta2=self.beta2,
            epsilon=self.epsilon,
T
Topdu 已提交
275
            parameters=parameters,
276
            weight_decay=self.weight_decay,
T
Topdu 已提交
277
            multi_precision=self.multi_precision,
278 279 280
            grad_clip=self.grad_clip,
            name=self.name,
            lazy_mode=self.lazy_mode,
T
Topdu 已提交
281
            apply_decay_param_fun=self._apply_decay_param_fun)
282
        return opt
T
Topdu 已提交
283 284

    def _apply_decay_param_fun(self, name):
285
        return name not in self.no_weight_decay_param_name_list