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

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

import numpy as np
import paddle.fluid as fluid
X
xixiaoyao 已提交
23
from paddlepalm.optimizer.base_optimizer import BaseOptimizer
X
xixiaoyao 已提交
24

X
xixiaoyao 已提交
25
class Adam(BaseOptimizer):
X
xixiaoyao 已提交
26

X
xixiaoyao 已提交
27
    def __init__(self, loss_var, lr, lr_schedualer=None):
X
xixiaoyao 已提交
28

X
xixiaoyao 已提交
29
        BaseOptimizer.__init__(self, loss_var, lr, lr_schedualer=None)
X
xixiaoyao 已提交
30

X
xixiaoyao 已提交
31
        self._loss = loss_var
X
xixiaoyao 已提交
32
        self._lr = lr
X
xixiaoyao 已提交
33 34 35
        self._lr_schedualer = lr_schedualer
    
    def build(self, grad_clip=None):
X
xixiaoyao 已提交
36

X
xixiaoyao 已提交
37 38
        if self._lr_schedualer is not None:
            self._lr = self._lr_schedualer.build(self._lr)
X
xixiaoyao 已提交
39

X
xixiaoyao 已提交
40
        optimizer = fluid.optimizer.Adam(learning_rate=self._lr)
X
xixiaoyao 已提交
41

X
xixiaoyao 已提交
42 43 44 45 46 47
        if grad_clip is not None:
            clip_norm_thres = grad_clip
            # When using mixed precision training, scale the gradient clip threshold
            # by loss_scaling
            fluid.clip.set_gradient_clip(
                clip=fluid.clip.GradientClipByGlobalNorm(clip_norm=clip_norm_thres))
X
xixiaoyao 已提交
48

X
xixiaoyao 已提交
49 50
        _, param_grads = optimizer.minimize(self._loss)
        return param_grads
X
xixiaoyao 已提交
51

X
xixiaoyao 已提交
52 53
    def get_cur_learning_rate(self):
        return self._lr
X
xixiaoyao 已提交
54

X
xixiaoyao 已提交
55