optimizer.py 10.7 KB
Newer Older
W
WuHaobo 已提交
1
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
W
WuHaobo 已提交
2
#
W
WuHaobo 已提交
3 4 5
# 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
W
WuHaobo 已提交
6 7 8
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
W
WuHaobo 已提交
9 10 11 12 13
# 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.
W
WuHaobo 已提交
14 15 16 17 18

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

19
import inspect
littletomatodonkey's avatar
littletomatodonkey 已提交
20

21
from paddle import optimizer as optim
G
gaotingquan 已提交
22 23
from ppcls.utils import logger

littletomatodonkey's avatar
littletomatodonkey 已提交
24

L
lubin 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
class SGD(object):
    """
    Args:
    learning_rate (float|Tensor|LearningRateDecay, optional): The learning rate used to update ``Parameter``.
        It can be a float value, a ``Tensor`` with a float type or a LearningRateDecay. The default value is 0.001.
    parameters (list|tuple, optional): List/Tuple of ``Tensor`` to update to minimize ``loss``. \
        This parameter is required in dygraph mode. \
        The default value is None in static mode, at this time all parameters will be updated.
    weight_decay (float|WeightDecayRegularizer, optional): The strategy of regularization. \
        It canbe a float value as coeff of L2 regularization or \
        :ref:`api_fluid_regularizer_L1Decay`, :ref:`api_fluid_regularizer_L2Decay`.
        If a parameter has set regularizer using :ref:`api_fluid_ParamAttr` already, \
        the regularization setting here in optimizer will be ignored for this parameter. \
        Otherwise, the regularization setting here in optimizer will take effect. \
        Default None, meaning there is no regularization.
    grad_clip (GradientClipBase, optional): Gradient cliping strategy, it's an instance of
        some derived class of ``GradientClipBase`` . There are three cliping strategies
        ( :ref:`api_fluid_clip_GradientClipByGlobalNorm` , :ref:`api_fluid_clip_GradientClipByNorm` ,
        :ref:`api_fluid_clip_GradientClipByValue` ). Default None, meaning there is no gradient clipping.
    name (str, optional): The default value is None. Normally there is no need for user
            to set this property.
    """

    def __init__(self,
                 learning_rate=0.001,
                 weight_decay=None,
                 grad_clip=None,
52
                 multi_precision=False,
L
lubin 已提交
53
                 name=None):
L
lubin 已提交
54 55 56
        self.learning_rate = learning_rate
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
57
        self.multi_precision = multi_precision
L
lubin 已提交
58 59 60 61 62 63
        self.name = name

    def __call__(self, model_list):
        # model_list is None in static graph
        parameters = sum([m.parameters() for m in model_list],
                         []) if model_list else None
64 65 66 67 68 69 70 71 72 73 74 75 76 77
        argspec = inspect.getargspec(optim.SGD.__init__).args
        if 'multi_precision' in argspec:
            opt = optim.SGD(learning_rate=self.learning_rate,
                            parameters=parameters,
                            weight_decay=self.weight_decay,
                            grad_clip=self.grad_clip,
                            multi_precision=self.multi_precision,
                            name=self.name)
        else:
            opt = optim.SGD(learning_rate=self.learning_rate,
                            parameters=parameters,
                            weight_decay=self.weight_decay,
                            grad_clip=self.grad_clip,
                            name=self.name)
L
lubin 已提交
78 79 80
        return opt


littletomatodonkey's avatar
littletomatodonkey 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93
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.
    """

    def __init__(self,
                 learning_rate,
                 momentum,
94
                 weight_decay=None,
littletomatodonkey's avatar
littletomatodonkey 已提交
95
                 grad_clip=None,
Z
zhangbo9674 已提交
96
                 multi_precision=True):
G
gaotingquan 已提交
97
        super().__init__()
littletomatodonkey's avatar
littletomatodonkey 已提交
98 99
        self.learning_rate = learning_rate
        self.momentum = momentum
100 101
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
littletomatodonkey's avatar
littletomatodonkey 已提交
102
        self.multi_precision = multi_precision
littletomatodonkey's avatar
littletomatodonkey 已提交
103

G
gaotingquan 已提交
104
    def __call__(self, model_list):
G
gaotingquan 已提交
105 106 107
        # model_list is None in static graph
        parameters = sum([m.parameters() for m in model_list],
                         []) if model_list else None
108
        opt = optim.Momentum(
littletomatodonkey's avatar
littletomatodonkey 已提交
109 110
            learning_rate=self.learning_rate,
            momentum=self.momentum,
111 112
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
littletomatodonkey's avatar
littletomatodonkey 已提交
113
            multi_precision=self.multi_precision,
114
            parameters=parameters)
Z
zhangbo9674 已提交
115 116 117 118 119 120 121 122
        if hasattr(opt, '_use_multi_tensor'):
            opt = optim.Momentum(
                learning_rate=self.learning_rate,
                momentum=self.momentum,
                weight_decay=self.weight_decay,
                grad_clip=self.grad_clip,
                multi_precision=self.multi_precision,
                parameters=parameters,
Z
zhangbo9674 已提交
123
                use_multi_tensor=True)
124 125 126 127 128 129 130 131 132 133 134 135 136
        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,
littletomatodonkey's avatar
littletomatodonkey 已提交
137 138
                 lazy_mode=False,
                 multi_precision=False):
139 140 141 142 143 144 145 146 147 148
        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
littletomatodonkey's avatar
littletomatodonkey 已提交
149
        self.multi_precision = multi_precision
150

G
gaotingquan 已提交
151
    def __call__(self, model_list):
G
gaotingquan 已提交
152 153 154
        # model_list is None in static graph
        parameters = sum([m.parameters() for m in model_list],
                         []) if model_list else None
155 156 157 158 159 160 161 162 163
        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,
littletomatodonkey's avatar
littletomatodonkey 已提交
164
            multi_precision=self.multi_precision,
165
            parameters=parameters)
littletomatodonkey's avatar
littletomatodonkey 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        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,
183
                 momentum=0.0,
littletomatodonkey's avatar
littletomatodonkey 已提交
184 185
                 rho=0.95,
                 epsilon=1e-6,
186
                 weight_decay=None,
littletomatodonkey's avatar
littletomatodonkey 已提交
187 188
                 grad_clip=None,
                 multi_precision=False):
G
gaotingquan 已提交
189
        super().__init__()
littletomatodonkey's avatar
littletomatodonkey 已提交
190 191 192 193
        self.learning_rate = learning_rate
        self.momentum = momentum
        self.rho = rho
        self.epsilon = epsilon
194 195
        self.weight_decay = weight_decay
        self.grad_clip = grad_clip
littletomatodonkey's avatar
littletomatodonkey 已提交
196

G
gaotingquan 已提交
197
    def __call__(self, model_list):
G
gaotingquan 已提交
198 199 200
        # model_list is None in static graph
        parameters = sum([m.parameters() for m in model_list],
                         []) if model_list else None
201
        opt = optim.RMSProp(
littletomatodonkey's avatar
littletomatodonkey 已提交
202 203 204 205
            learning_rate=self.learning_rate,
            momentum=self.momentum,
            rho=self.rho,
            epsilon=self.epsilon,
206 207 208
            weight_decay=self.weight_decay,
            grad_clip=self.grad_clip,
            parameters=parameters)
littletomatodonkey's avatar
littletomatodonkey 已提交
209
        return opt
G
gaotingquan 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236


class AdamW(object):
    def __init__(self,
                 learning_rate=0.001,
                 beta1=0.9,
                 beta2=0.999,
                 epsilon=1e-8,
                 weight_decay=None,
                 multi_precision=False,
                 grad_clip=None,
                 no_weight_decay_name=None,
                 one_dim_param_no_weight_decay=False,
                 **args):
        super().__init__()
        self.learning_rate = learning_rate
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.grad_clip = grad_clip
        self.weight_decay = weight_decay
        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_list):
G
gaotingquan 已提交
237 238 239
        # model_list is None in static graph
        parameters = sum([m.parameters() for m in model_list],
                         []) if model_list else None
G
gaotingquan 已提交
240

G
gaotingquan 已提交
241
        # TODO(gaotingquan): model_list is None when in static graph, "no_weight_decay" not work.
G
gaotingquan 已提交
242 243 244 245 246 247 248
        if model_list is None:
            if self.one_dim_param_no_weight_decay or len(
                    self.no_weight_decay_name_list) != 0:
                msg = "\"AdamW\" does not support setting \"no_weight_decay\" in static graph. Please use dynamic graph."
                logger.error(Exception(msg))
                raise Exception(msg)

G
gaotingquan 已提交
249 250 251
        self.no_weight_decay_param_name_list = [
            p.name for model in model_list for n, p in model.named_parameters()
            if any(nd in n for nd in self.no_weight_decay_name_list)
G
gaotingquan 已提交
252
        ] if model_list else []
G
gaotingquan 已提交
253 254 255

        if self.one_dim_param_no_weight_decay:
            self.no_weight_decay_param_name_list += [
256 257 258
                p.name
                for model in model_list for n, p in model.named_parameters()
                if len(p.shape) == 1
G
gaotingquan 已提交
259
            ] if model_list else []
G
gaotingquan 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274

        opt = optim.AdamW(
            learning_rate=self.learning_rate,
            beta1=self.beta1,
            beta2=self.beta2,
            epsilon=self.epsilon,
            parameters=parameters,
            weight_decay=self.weight_decay,
            multi_precision=self.multi_precision,
            grad_clip=self.grad_clip,
            apply_decay_param_fun=self._apply_decay_param_fun)
        return opt

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