Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adadelta Optimizer #26590

Merged
merged 47 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 34 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
e45dcff
add doc; notest
MRXLT Aug 14, 2020
85b3f92
fix doc; notest
MRXLT Aug 14, 2020
cbcd950
update doc; notest
MRXLT Aug 14, 2020
9661a54
refine optimizer && adam
MRXLT Aug 14, 2020
f542d77
fix conflict
MRXLT Aug 17, 2020
73baac0
refine optimizer; notest
MRXLT Aug 18, 2020
5a55869
add adam
MRXLT Aug 18, 2020
fd34fbd
fix doc
MRXLT Aug 18, 2020
f5e6881
Merge remote-tracking branch 'upstream/develop' into 2.0-op
MRXLT Aug 18, 2020
a715c46
Merge remote-tracking branch 'upstream/develop' into 2.0-op
MRXLT Aug 19, 2020
e67cd86
fix doc && add adamw; notest
MRXLT Aug 19, 2020
da4025d
add error message
MRXLT Aug 19, 2020
f3699cb
bug fix
MRXLT Aug 19, 2020
6f00384
refine rmsprop && adamax
MRXLT Aug 19, 2020
654377d
fix ci
MRXLT Aug 19, 2020
fa7ccb1
buf fix
MRXLT Aug 19, 2020
9aaf899
update comment
MRXLT Aug 19, 2020
b727dad
unify arguments place; notest
MRXLT Aug 20, 2020
9cf4c3b
fix ut, test=develop
mapingshuo Aug 20, 2020
2e8d253
bug fix
MRXLT Aug 20, 2020
00c38fc
fix conflicts, test=develop
mapingshuo Aug 20, 2020
b75ab16
add examples code
MRXLT Aug 20, 2020
84205ce
Merge remote-tracking branch 'origin/2.0-op' into 2.0-op
MRXLT Aug 20, 2020
b6fa771
bug fix
MRXLT Aug 20, 2020
9cd1838
fix comments
MRXLT Aug 20, 2020
95310f5
fix sample code
MRXLT Aug 20, 2020
ce31795
add sample code for Optimizer
MRXLT Aug 20, 2020
0780b9c
add adamax ut, test=develop
mapingshuo Aug 21, 2020
87a7f56
fix rmsprop ut, test=develop
mapingshuo Aug 21, 2020
06f3c73
add ut for optimizer.py and adamw.py
MRXLT Aug 21, 2020
fd67080
Merge branch '2.0-op' of https://github.com/MRXLT/Paddle into 2.0-op
MRXLT Aug 21, 2020
27d498d
first commit of adadelta optimizer
bjjwwang Aug 21, 2020
e758d2d
fix learning rate
bjjwwang Aug 21, 2020
5252ba7
merge with develop
bjjwwang Aug 24, 2020
0674403
fix adadelta doc and add sgd momentum
bjjwwang Aug 24, 2020
fecb57e
Merge branch 'develop' into 2.0-adadelta
bjjwwang Aug 25, 2020
a140fa7
remove unused fluid
bjjwwang Aug 25, 2020
093abc9
Merge branch '2.0-adadelta' of https://github.com/wangjiawei04/Paddle…
bjjwwang Aug 25, 2020
47d0af1
fix codestyle
bjjwwang Aug 25, 2020
55877dd
Update test_adam_op.py
bjjwwang Aug 25, 2020
bf7d4a0
Update test_adam_op.py
bjjwwang Aug 25, 2020
d1e4ce4
fix SGD in 2 unittests
bjjwwang Aug 25, 2020
c154a07
Merge branch '2.0-adadelta' of https://github.com/wangjiawei04/Paddle…
bjjwwang Aug 25, 2020
aedaf12
fix SGD in 2 unittests
bjjwwang Aug 25, 2020
1de492d
merge with develop zhouwei new lr 0830
bjjwwang Aug 28, 2020
2f01874
fix ci
MRXLT Aug 28, 2020
a44ef94
fix ut
MRXLT Aug 28, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 52 additions & 32 deletions paddle/fluid/operators/optimizers/adadelta_op.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,49 +24,69 @@ class AdadeltaOp : public framework::OperatorWithKernel {
using framework::OperatorWithKernel::OperatorWithKernel;

void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("Param"),
"Input(Param) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("Grad"),
"Input(Grad) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("AvgSquaredGrad"),
"Input(AvgSquaredGrad) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(ctx->HasInput("AvgSquaredUpdate"),
"Input(AvgSquaredUpdate) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(
PADDLE_ENFORCE_EQ(ctx->HasInput("Param"), true,
platform::errors::InvalidArgument(
"Input(Param) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->HasInput("Grad"), true,
platform::errors::InvalidArgument(
"Input(Grad) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("AvgSquaredGrad"), true,
platform::errors::InvalidArgument(
"Input(AvgSquaredGrad) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasInput("AvgSquaredUpdate"), true,
platform::errors::InvalidArgument(
"Input(AvgSquaredUpdate) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->GetInputsVarType("Param").front() ==
framework::proto::VarType::LOD_TENSOR,
"The input var's type should be LoDTensor, but the received is %s",
ctx->Inputs("Param").front(), ctx->GetInputsVarType("Param").front());
PADDLE_ENFORCE(
true,
platform::errors::InvalidArgument(
"The input var's type should be LoDTensor, but the received is %s",
ctx->Inputs("Param").front(),
ctx->GetInputsVarType("Param").front()));
PADDLE_ENFORCE_EQ(
ctx->GetInputsVarType("Grad").front() ==
framework::proto::VarType::LOD_TENSOR,
"The input var's type should be LoDTensor, but the received is %s",
ctx->Inputs("Grad").front(), ctx->GetInputsVarType("Grad").front());

PADDLE_ENFORCE(ctx->HasOutput("ParamOut"),
"Output(ParamOut) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("AvgSquaredGradOut"),
"Output(AvgSquaredGradOut) of AdadeltaOp should not be null.");
PADDLE_ENFORCE(
ctx->HasOutput("AvgSquaredUpdateOut"),
"Output(AvgSquaredUpdateOut) of AdadeltaOp should not be null.");
true,
platform::errors::InvalidArgument(
"The input var's type should be LoDTensor, but the received is %s",
ctx->Inputs("Grad").front(),
ctx->GetInputsVarType("Grad").front()));

PADDLE_ENFORCE_EQ(
ctx->HasOutput("ParamOut"), true,
platform::errors::InvalidArgument(
"Output(ParamOut) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("AvgSquaredGradOut"), true,
platform::errors::InvalidArgument(
"Output(AvgSquaredGradOut) of AdadeltaOp should not be null."));
PADDLE_ENFORCE_EQ(
ctx->HasOutput("AvgSquaredUpdateOut"), true,
platform::errors::InvalidArgument(
"Output(AvgSquaredUpdateOut) of AdadeltaOp should not be null."));

auto param_dim = ctx->GetInputDim("Param");
PADDLE_ENFORCE_EQ(
param_dim, ctx->GetInputDim("Grad"),
"param and grad input of AdadeltaOp should have same dimension");
PADDLE_ENFORCE_NE(framework::product(ctx->GetInputDim("AvgSquaredGrad")), 0,
"Maybe the Input variable AvgSquaredGrad has not "
"been initialized. You may need to confirm if you put "
"exe.run(startup_program) after optimizer.minimize "
"function.");
PADDLE_ENFORCE_NE(
framework::product(ctx->GetInputDim("AvgSquaredGrad")), 0,
platform::errors::InvalidArgument(
"Maybe the Input variable AvgSquaredGrad has not "
"been initialized. You may need to confirm if you put "
"exe.run(startup_program) after optimizer.minimize "
"function."));
PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("AvgSquaredGrad"),
"Param and AvgSquaredGrad input of AdadeltaOp "
"should have same dimension");
platform::errors::InvalidArgument(
"Param and AvgSquaredGrad input of AdadeltaOp "
"should have same dimension"));
PADDLE_ENFORCE_EQ(param_dim, ctx->GetInputDim("AvgSquaredUpdate"),
"Param and AvgSquaredUpdate input of AdadeltaOp "
"should have same dimension");
platform::errors::InvalidArgument(
"Param and AvgSquaredUpdate input of AdadeltaOp "
"should have same dimension"));

ctx->SetOutputDim("ParamOut", param_dim);
ctx->SetOutputDim("AvgSquaredGradOut", param_dim);
Expand Down
22 changes: 12 additions & 10 deletions paddle/fluid/operators/optimizers/adadelta_op.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,19 @@ class AdadeltaOpKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
const auto* param_var = ctx.InputVar("Param");
PADDLE_ENFORCE(param_var->IsType<framework::LoDTensor>(),
"The Var(%s)'s type should be LoDTensor, "
"but the received is %s",
ctx.InputNames("Param").front(),
framework::ToTypeName(param_var->Type()));
PADDLE_ENFORCE_EQ(param_var->IsType<framework::LoDTensor>(), true,
platform::errors::InvalidArgument(
"The Var(%s)'s type should be LoDTensor, "
"but the received is %s",
ctx.InputNames("Param").front(),
framework::ToTypeName(param_var->Type())));
const auto* grad_var = ctx.InputVar("Grad");
PADDLE_ENFORCE(grad_var->IsType<framework::LoDTensor>(),
"The Var(%s)'s type should be LoDTensor, "
"but the received is %s",
ctx.InputNames("Grad").front(),
framework::ToTypeName(grad_var->Type()));
PADDLE_ENFORCE_EQ(grad_var->IsType<framework::LoDTensor>(), true,
platform::errors::InvalidArgument(
"The Var(%s)'s type should be LoDTensor, "
"but the received is %s",
ctx.InputNames("Grad").front(),
framework::ToTypeName(grad_var->Type())));

auto param_out_tensor = ctx.Output<framework::Tensor>("ParamOut");
auto avg_squared_grad_out_tensor =
Expand Down
23 changes: 14 additions & 9 deletions paddle/fluid/operators/top_k_op.cc
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,27 @@ class TopkOp : public framework::OperatorWithKernel {
using framework::OperatorWithKernel::OperatorWithKernel;

void InferShape(framework::InferShapeContext* ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of TopkOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of TopkOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Indices"),
"Output(Indices) of TopkOp should not be null.");
PADDLE_ENFORCE_EQ(ctx->HasInput("X"), true,
platform::errors::InvalidArgument(
"Input(X) of TopkOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true,
platform::errors::InvalidArgument(
"Output(Out) of TopkOp should not be null."));
PADDLE_ENFORCE_EQ(ctx->HasOutput("Indices"), true,
platform::errors::InvalidArgument(
"Output(Indices) of TopkOp should not be null."));

auto input_dims = ctx->GetInputDim("X");
const int k = static_cast<int>(ctx->Attrs().Get<int>("k"));

PADDLE_ENFORCE_GE(k, 1, "k must >= 1");
PADDLE_ENFORCE_GE(input_dims.size(), 1, "input must have >= 1d shape");
PADDLE_ENFORCE_GE(input_dims.size(), 1, platform::errors::InvalidArgument(
"input must have >= 1d shape"));

if (ctx->IsRuntime()) {
PADDLE_ENFORCE_GE(input_dims[input_dims.size() - 1], k,
"input must have >= k columns");
PADDLE_ENFORCE_GE(
input_dims[input_dims.size() - 1], k,
platform::errors::InvalidArgument("input must have >= k columns"));
}

framework::DDim dims = input_dims;
Expand Down
5 changes: 3 additions & 2 deletions paddle/fluid/operators/top_k_op.cu
Original file line number Diff line number Diff line change
Expand Up @@ -496,8 +496,9 @@ template <typename DeviceContext, typename T>
class TopkOpCUDAKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(platform::is_gpu_place(ctx.GetPlace()),
"It must use CUDAPlace.");
PADDLE_ENFORCE_EQ(
platform::is_gpu_place(ctx.GetPlace()), true,
platform::errors::InvalidArgument("It must use CUDAPlace."));
auto* input = ctx.Input<Tensor>("X");
auto* output = ctx.Output<Tensor>("Out");
auto* indices = ctx.Output<Tensor>("Indices");
Expand Down
51 changes: 51 additions & 0 deletions python/paddle/fluid/tests/unittests/test_adadelta_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
import unittest
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid as fluid


class TestAdadeltaOp1(OpTest):
Expand Down Expand Up @@ -108,5 +110,54 @@ def test_check_output(self):
self.check_output()


class TestAdadeltaPropV2(unittest.TestCase):
def test_adadelta_dygraph(self):
paddle.disable_static()
value = np.arange(26).reshape(2, 13).astype("float32")
a = paddle.to_tensor(value)
linear = paddle.nn.Linear(13, 5, dtype="float32")
# This can be any optimizer supported by dygraph.
adam = paddle.optimizer.Adadelta(
learning_rate=0.01,
parameters=linear.parameters(),
weight_decay=0.01)
out = linear(a)
out.backward()
adam.step()
adam.clear_gradients()

def test_adadelta(self):
place = fluid.CPUPlace()
main = fluid.Program()
with fluid.program_guard(main):
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
y_predict = fluid.layers.fc(input=x, size=1, act=None)
cost = fluid.layers.square_error_cost(input=y_predict, label=y)
avg_cost = fluid.layers.mean(cost)

rms_optimizer = paddle.optimizer.Adadelta(learning_rate=0.1)
rms_optimizer.minimize(avg_cost)

fetch_list = [avg_cost]
train_reader = paddle.batch(
paddle.dataset.uci_housing.train(), batch_size=1)
feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
for data in train_reader():
exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)

def test_raise_error(self):
self.assertRaises(ValueError, paddle.optimizer.Adadelta, None)
self.assertRaises(
ValueError, paddle.optimizer.Adadelta, learning_rate=0.1, rho=None)
self.assertRaises(
ValueError,
paddle.optimizer.Adadelta,
learning_rate=0.1,
epsilon=None)


if __name__ == "__main__":
unittest.main()
85 changes: 85 additions & 0 deletions python/paddle/fluid/tests/unittests/test_adam_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,5 +509,90 @@ def test_adam_op_with_set_lr(self):
adam.set_lr(lr)


class TestAdamOpV2(unittest.TestCase):
def test_adam_op(self):
place = fluid.CPUPlace()
shape = [2, 3, 8, 8]
exe = fluid.Executor(place)
train_prog = fluid.Program()
startup = fluid.Program()
with fluid.program_guard(train_prog, startup):
with fluid.unique_name.guard():
data = fluid.data(name="data", shape=shape)
conv = fluid.layers.conv2d(data, 8, 3)
loss = fluid.layers.reduce_mean(conv)

beta1 = fluid.layers.create_global_var(
shape=[1], value=0.85, dtype='float32', persistable=True)
beta2 = fluid.layers.create_global_var(
shape=[1], value=0.95, dtype='float32', persistable=True)
betas = [beta1, beta2]
opt = paddle.optimizer.Adam(
learning_rate=1e-5,
beta1=beta1,
beta2=beta2,
weight_decay=0.01,
epsilon=1e-8)
opt.minimize(loss)

exe.run(startup)
data_np = np.random.random(shape).astype('float32')
rets = exe.run(train_prog, feed={"data": data_np}, fetch_list=[loss])
assert rets[0] is not None

def test_adam_op_dygraph(self):
paddle.disable_static()
value = np.arange(26).reshape(2, 13).astype("float32")
a = fluid.dygraph.to_variable(value)
linear = fluid.Linear(13, 5, dtype="float32")

adam = paddle.optimizer.Adam(
learning_rate=0.01, parameters=linear.parameters())
out = linear(a)
out.backward()
adam.step()
adam.clear_gradients()

def test_adam_op_with_state_dict(self):

import paddle
paddle.disable_static()
emb = paddle.nn.Embedding([10, 10])

adam = paddle.optimizer.Adam(0.001, parameters=emb.parameters())
state_dict = adam.state_dict()

adam.set_state_dict(state_dict)

#learning_rate is Decay
from paddle.fluid.regularizer import L2Decay
adam = paddle.optimizer.Adam(
learning_rate=0.01,
weight_decay=L2Decay(0.001),
parameters=emb.parameters())

state_dict = adam.state_dict()
adam.set_state_dict(state_dict)

params = adam.get_opti_var_name_list()
assert (params is not None)

def test_adam_op_with_set_lr(self):
import paddle
paddle.disable_static()
linear = paddle.nn.Linear(10, 10)
adam = paddle.optimizer.Adam(0.1, parameters=linear.parameters())

lr = 0.01
adam.set_lr(lr)
cur_lr = adam.current_step_lr()
assert (lr == cur_lr)

lr_var = paddle.create_global_var(shape=[1], value=lr, dtype='float32')
adam.set_lr(lr_var)
cur_lr = adam.current_step_lr()
assert (np.float32(lr) == cur_lr)


if __name__ == "__main__":
unittest.main()
3 changes: 2 additions & 1 deletion python/paddle/optimizer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@


from ..fluid.optimizer import SGD, Momentum, Adagrad, Dpsgd, DecayedAdagrad, \
Ftrl, Adadelta, \
Ftrl, \
SGDOptimizer, MomentumOptimizer, AdagradOptimizer,DpsgdOptimizer,\
DecayedAdagradOptimizer,FtrlOptimizer,AdadeltaOptimizer, \
ModelAverage, LarsMomentum, DGCMomentumOptimizer, LambOptimizer,\
Expand All @@ -36,3 +36,4 @@
from .adamw import AdamW
from .adamax import Adamax
from .rmsprop import RMSProp
from .adadelta import Adadelta
Loading