Add learning rate decay (#7892)
* add basic interface for learning rate decay * add exponential_decay * add natural_exp_decay * add inverse_time_decayemailweixu-patch-1
parent
80eff2662b
commit
be801d6c05
@ -0,0 +1,37 @@
|
|||||||
|
/* Copyright (c) 2018 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. */
|
||||||
|
|
||||||
|
#include "paddle/operators/elementwise_pow_op.h"
|
||||||
|
#include "paddle/operators/elementwise_op.h"
|
||||||
|
|
||||||
|
namespace paddle {
|
||||||
|
namespace operators {
|
||||||
|
class ElementwisePowOpMaker : public ElementwiseOpMaker {
|
||||||
|
public:
|
||||||
|
ElementwisePowOpMaker(OpProto* proto, OpAttrChecker* op_checker)
|
||||||
|
: ElementwiseOpMaker(proto, op_checker) {
|
||||||
|
SetComment("Pow", "Out = X ^ Y");
|
||||||
|
AddComment(comment_);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace operators
|
||||||
|
} // namespace paddle
|
||||||
|
|
||||||
|
namespace ops = paddle::operators;
|
||||||
|
REGISTER_OP_WITHOUT_GRADIENT(elementwise_pow, ops::ElementwiseOp,
|
||||||
|
ops::ElementwisePowOpMaker);
|
||||||
|
REGISTER_OP_CPU_KERNEL(
|
||||||
|
elementwise_pow,
|
||||||
|
ops::ElementwisePowKernel<paddle::platform::CPUDeviceContext, float>,
|
||||||
|
ops::ElementwisePowKernel<paddle::platform::CPUDeviceContext, double>);
|
@ -0,0 +1,20 @@
|
|||||||
|
/* Copyright (c) 2018 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. */
|
||||||
|
|
||||||
|
#define EIGEN_USE_GPU
|
||||||
|
#include "paddle/operators/elementwise_pow_op.h"
|
||||||
|
|
||||||
|
namespace ops = paddle::operators;
|
||||||
|
|
||||||
|
REGISTER_OP_CUDA_KERNEL(
|
||||||
|
elementwise_pow,
|
||||||
|
ops::ElementwisePowKernel<paddle::platform::CUDADeviceContext, float>,
|
||||||
|
ops::ElementwisePowKernel<paddle::platform::CUDADeviceContext, double>);
|
@ -0,0 +1,37 @@
|
|||||||
|
/* Copyright (c) 2018 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. */
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cmath>
|
||||||
|
#include "paddle/operators/elementwise_op_function.h"
|
||||||
|
|
||||||
|
namespace paddle {
|
||||||
|
namespace operators {
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct PowFunctor {
|
||||||
|
inline HOSTDEVICE T operator()(T a, T b) const { return std::pow(a, b); }
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename DeviceContext, typename T>
|
||||||
|
class ElementwisePowKernel : public framework::OpKernel<T> {
|
||||||
|
public:
|
||||||
|
void Compute(const framework::ExecutionContext& ctx) const override {
|
||||||
|
ElementwiseComputeEx<PowFunctor<T>, DeviceContext, T>(ctx);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace operators
|
||||||
|
} // namespace paddle
|
@ -0,0 +1,125 @@
|
|||||||
|
# Copyright (c) 2016 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 layers
|
||||||
|
from framework import Variable
|
||||||
|
|
||||||
|
__all__ = ['exponential_decay', 'natural_exp_decay', 'inverse_time_decay']
|
||||||
|
"""
|
||||||
|
When training a model, it's often useful to decay the
|
||||||
|
learning rate during training process, this is called
|
||||||
|
learning_rate_decay. There are many strategies to do
|
||||||
|
this, this module will provide some classical method.
|
||||||
|
User can also implement their own learning_rate_decay
|
||||||
|
strategy according to this module.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def exponential_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
"""Applies exponential decay to the learning rate.
|
||||||
|
|
||||||
|
```python
|
||||||
|
decayed_learning_rate = learning_rate *
|
||||||
|
decay_rate ^ (global_step / decay_steps)
|
||||||
|
```
|
||||||
|
Args:
|
||||||
|
learning_rate: A scalar float32 value or a Variable. This
|
||||||
|
will be the initial learning rate during training
|
||||||
|
global_step: A Variable that record the training step.
|
||||||
|
decay_steps: A Python `int32` number.
|
||||||
|
decay_rate: A Python `float` number.
|
||||||
|
staircase: Boolean. If set true, decay the learning rate every decay_steps.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The decayed learning rate
|
||||||
|
"""
|
||||||
|
if not isinstance(global_step, Variable):
|
||||||
|
raise ValueError("global_step is required for exponential_decay.")
|
||||||
|
|
||||||
|
# update learning_rate
|
||||||
|
div_res = global_step / decay_steps
|
||||||
|
if staircase:
|
||||||
|
div_res = layers.floor(x=div_res)
|
||||||
|
return learning_rate * (decay_rate**div_res)
|
||||||
|
|
||||||
|
|
||||||
|
def natural_exp_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
"""Applies natural exponential decay to the initial learning rate.
|
||||||
|
|
||||||
|
```python
|
||||||
|
if not staircase:
|
||||||
|
decayed_learning_rate = learning_rate * exp(- decay_rate * (global_step / decay_steps))
|
||||||
|
else:
|
||||||
|
decayed_learning_rate = learning_rate * exp(- decay_rate * (global_step / decay_steps))
|
||||||
|
```
|
||||||
|
Args:
|
||||||
|
learning_rate: A scalar float32 value or a Variable. This
|
||||||
|
will be the initial learning rate during training
|
||||||
|
global_step: A Variable that record the training step.
|
||||||
|
decay_steps: A Python `int32` number.
|
||||||
|
decay_rate: A Python `float` number.
|
||||||
|
staircase: Boolean. If set true, decay the learning rate every decay_steps.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The decayed learning rate
|
||||||
|
"""
|
||||||
|
if not isinstance(global_step, Variable):
|
||||||
|
raise ValueError("global_step is required for natural_exp_decay.")
|
||||||
|
|
||||||
|
div_res = global_step / decay_steps
|
||||||
|
if staircase:
|
||||||
|
div_res = layers.floor(x=div_res)
|
||||||
|
return learning_rate * layers.exp(x=(-1 * decay_rate * div_res))
|
||||||
|
|
||||||
|
|
||||||
|
def inverse_time_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
"""Applies inverse time decay to the initial learning rate.
|
||||||
|
|
||||||
|
```python
|
||||||
|
if staircase:
|
||||||
|
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: A scalar float32 value or a Variable. This
|
||||||
|
will be the initial learning rate during training
|
||||||
|
global_step: A Variable that record the training step.
|
||||||
|
decay_steps: A Python `int32` number.
|
||||||
|
decay_rate: A Python `float` number.
|
||||||
|
staircase: Boolean. If set true, decay the learning rate every decay_steps.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The decayed learning rate
|
||||||
|
"""
|
||||||
|
if not isinstance(global_step, Variable):
|
||||||
|
raise ValueError("global_step is required for inverse_time_decay.")
|
||||||
|
|
||||||
|
div_res = global_step / decay_steps
|
||||||
|
if staircase:
|
||||||
|
div_res = layers.floor(x=div_res)
|
||||||
|
|
||||||
|
return learning_rate / (1 + decay_rate * div_res)
|
@ -0,0 +1,43 @@
|
|||||||
|
# Copyright (c) 2018 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.
|
||||||
|
import unittest
|
||||||
|
import numpy as np
|
||||||
|
from op_test import OpTest
|
||||||
|
|
||||||
|
|
||||||
|
class TestElementwisePowOp(OpTest):
|
||||||
|
def setUp(self):
|
||||||
|
self.op_type = "elementwise_pow"
|
||||||
|
self.inputs = {
|
||||||
|
'X': np.random.uniform(0.1, 1, [13, 17]).astype("float32"),
|
||||||
|
'Y': np.random.uniform(0.1, 1, [13, 17]).astype("float32")
|
||||||
|
}
|
||||||
|
self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}
|
||||||
|
|
||||||
|
def test_check_output(self):
|
||||||
|
self.check_output()
|
||||||
|
|
||||||
|
|
||||||
|
class TestElementwisePowOp_scalar(TestElementwisePowOp):
|
||||||
|
def setUp(self):
|
||||||
|
self.op_type = "elementwise_pow"
|
||||||
|
self.inputs = {
|
||||||
|
'X': np.random.rand(2, 3, 4).astype('float32'),
|
||||||
|
'Y': np.random.rand(1).astype('float32')
|
||||||
|
}
|
||||||
|
self.outputs = {'Out': np.power(self.inputs['X'], self.inputs['Y'])}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
@ -0,0 +1,110 @@
|
|||||||
|
# Copyright (c) 2016 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 unittest
|
||||||
|
|
||||||
|
import math
|
||||||
|
import paddle.v2.fluid.framework as framework
|
||||||
|
import paddle.v2.fluid as fluid
|
||||||
|
import paddle.v2.fluid.layers as layers
|
||||||
|
import paddle.v2.fluid.learning_rate_decay as lr_decay
|
||||||
|
|
||||||
|
|
||||||
|
def exponential_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
exponent = float(global_step) / float(decay_steps)
|
||||||
|
if staircase:
|
||||||
|
exponent = math.floor(exponent)
|
||||||
|
return learning_rate * decay_rate**exponent
|
||||||
|
|
||||||
|
|
||||||
|
def natural_exp_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
exponent = float(global_step) / float(decay_steps)
|
||||||
|
if staircase:
|
||||||
|
exponent = math.floor(exponent)
|
||||||
|
return learning_rate * math.exp(-1 * decay_rate * exponent)
|
||||||
|
|
||||||
|
|
||||||
|
def inverse_time_decay(learning_rate,
|
||||||
|
global_step,
|
||||||
|
decay_steps,
|
||||||
|
decay_rate,
|
||||||
|
staircase=False):
|
||||||
|
temp = float(global_step) / float(decay_steps)
|
||||||
|
if staircase:
|
||||||
|
temp = math.floor(temp)
|
||||||
|
return learning_rate / (1 + decay_rate * temp)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLearningRateDecay(unittest.TestCase):
|
||||||
|
def check_decay(self, python_decay_fn, fluid_decay_fn, staircase):
|
||||||
|
init_lr = 1.0
|
||||||
|
decay_steps = 5
|
||||||
|
decay_rate = 0.5
|
||||||
|
|
||||||
|
global_step = layers.create_global_var(
|
||||||
|
shape=[1], value=0.0, dtype='float32', persistable=True)
|
||||||
|
|
||||||
|
decayed_lr = fluid_decay_fn(
|
||||||
|
learning_rate=init_lr,
|
||||||
|
global_step=global_step,
|
||||||
|
decay_steps=decay_steps,
|
||||||
|
decay_rate=decay_rate,
|
||||||
|
staircase=staircase)
|
||||||
|
layers.increment(global_step, 1.0)
|
||||||
|
|
||||||
|
place = fluid.CPUPlace()
|
||||||
|
exe = fluid.Executor(place)
|
||||||
|
|
||||||
|
exe.run(fluid.default_startup_program())
|
||||||
|
for step in range(10):
|
||||||
|
step_val, lr_val = exe.run(fluid.default_main_program(),
|
||||||
|
feed=[],
|
||||||
|
fetch_list=[global_step, decayed_lr])
|
||||||
|
python_decayed_lr = python_decay_fn(
|
||||||
|
learning_rate=init_lr,
|
||||||
|
global_step=step,
|
||||||
|
decay_steps=decay_steps,
|
||||||
|
decay_rate=decay_rate,
|
||||||
|
staircase=staircase)
|
||||||
|
self.assertAlmostEqual(python_decayed_lr, lr_val[0])
|
||||||
|
|
||||||
|
def test_decay(self):
|
||||||
|
decay_fns = [
|
||||||
|
(exponential_decay, lr_decay.exponential_decay, True),
|
||||||
|
(exponential_decay, lr_decay.exponential_decay, False),
|
||||||
|
(natural_exp_decay, lr_decay.natural_exp_decay, True),
|
||||||
|
(natural_exp_decay, lr_decay.natural_exp_decay, False),
|
||||||
|
(inverse_time_decay, lr_decay.inverse_time_decay, True),
|
||||||
|
(inverse_time_decay, lr_decay.inverse_time_decay, False),
|
||||||
|
]
|
||||||
|
|
||||||
|
for py_decay_fn, fluid_decay_fn, staircase in decay_fns:
|
||||||
|
print("decay_fn=" + str(py_decay_fn) + " staircase=" + str(
|
||||||
|
staircase))
|
||||||
|
main_program = framework.Program()
|
||||||
|
startup_program = framework.Program()
|
||||||
|
with framework.program_guard(main_program, startup_program):
|
||||||
|
self.check_decay(py_decay_fn, fluid_decay_fn, staircase)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
Loading…
Reference in new issue