test_imperative_optimizer.py 29.3 KB
Newer Older
M
minqiyang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2018 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.

15
import itertools
M
minqiyang 已提交
16
import unittest
17

M
minqiyang 已提交
18 19
import numpy as np

M
minqiyang 已提交
20
import paddle
M
minqiyang 已提交
21 22
import paddle.fluid as fluid
from paddle.fluid import core
23
from paddle.fluid.optimizer import (
24
    AdadeltaOptimizer,
25
    AdagradOptimizer,
26
    Adam,
27 28
    AdamaxOptimizer,
    DecayedAdagradOptimizer,
29 30
    DpsgdOptimizer,
    ExponentialMovingAverage,
31 32
    FtrlOptimizer,
    LambOptimizer,
33 34
    LarsMomentumOptimizer,
    LookaheadOptimizer,
35
    ModelAverage,
36
    MomentumOptimizer,
37 38
    PipelineOptimizer,
    RecomputeOptimizer,
39 40
    RMSPropOptimizer,
    SGDOptimizer,
41
)
42 43 44 45
from test_imperative_base import new_program_scope
from paddle.fluid.framework import _test_eager_guard

from paddle.distributed.fleet.meta_optimizers import DGCMomentumOptimizer
46

Z
zhongpu 已提交
47 48 49
# Note(wangzhongpu)
# In dygraph, don't support ModelAverage, DGCMomentumOptimizer, ExponentialMovingAverage, PipelineOptimizer, LookaheadOptimizer, RecomputeOptimizer.

50

51
class MLP(fluid.Layer):
52
    def __init__(self, param_attr=None, bias_attr=None):
53
        super().__init__()
M
minqiyang 已提交
54

55 56
        self._fc1 = paddle.nn.Linear(784, 10)
        self._fc2 = paddle.nn.Linear(10, 10)
M
minqiyang 已提交
57

58 59 60 61
    def forward(self, inputs):
        y = self._fc1(inputs)
        y = self._fc2(y)
        return y
62

M
minqiyang 已提交
63

64 65
class TestImperativeOptimizerBase(unittest.TestCase):
    def setUp(self):
M
minqiyang 已提交
66
        self.batch_num = 20
M
minqiyang 已提交
67

68 69 70
    def get_optimizer_dygraph(self, parameter_list):
        raise NotImplementedError()

71
    def get_optimizer(self):
72
        raise NotImplementedError()
M
minqiyang 已提交
73

74 75 76
    def reader_decorator(self, reader):
        def _reader_imple():
            for item in reader():
77
                image = np.array(item[0]).reshape(1, 784)
78 79 80 81 82
                label = np.array(item[1]).astype('int64').reshape(1)
                yield image, label

        return _reader_imple

Z
zhongpu 已提交
83 84 85
    def _check_exception(self, exception_message, place=None):
        seed = 90
        batch_size = 128
86
        if place is None:
87 88 89 90 91
            place = (
                fluid.CUDAPlace(0)
                if core.is_compiled_with_cuda()
                else fluid.CPUPlace()
            )
Z
zhongpu 已提交
92 93 94

        with fluid.dygraph.guard(place):
            try:
C
cnn 已提交
95
                paddle.seed(seed)
L
Leo Chen 已提交
96
                paddle.framework.random._manual_program_seed(seed)
Z
zhongpu 已提交
97 98
                mlp = MLP()
                optimizer = self.get_optimizer_dygraph(
99 100
                    parameter_list=mlp.parameters()
                )
Z
zhongpu 已提交
101 102 103 104
            except Exception as e:
                assert str(e) == exception_message

    def _check_mlp(self, place=None):
M
minqiyang 已提交
105
        seed = 90
106 107
        batch_size = 128

108
        if place is None:
109 110 111 112 113
            place = (
                fluid.CPUPlace()
                if not core.is_compiled_with_cuda()
                else fluid.CUDAPlace(0)
            )
Z
zhongpu 已提交
114 115

        with fluid.dygraph.guard(place):
C
cnn 已提交
116
            paddle.seed(seed)
L
Leo Chen 已提交
117
            paddle.framework.random._manual_program_seed(seed)
M
minqiyang 已提交
118

119 120
            mlp = MLP()
            optimizer = self.get_optimizer_dygraph(
121 122
                parameter_list=mlp.parameters()
            )
123 124 125

            batch_py_reader = fluid.io.PyReader(capacity=1)
            batch_py_reader.decorate_sample_list_generator(
126 127 128 129 130 131 132
                paddle.batch(
                    self.reader_decorator(paddle.dataset.mnist.train()),
                    batch_size=batch_size,
                    drop_last=True,
                ),
                places=fluid.CPUPlace(),
            )
M
minqiyang 已提交
133

M
minqiyang 已提交
134
            dy_param_init_value = {}
135
            for batch_id, data in enumerate(batch_py_reader()):
136
                if batch_id >= self.batch_num:
M
minqiyang 已提交
137 138
                    break

139 140
                img = data[0]
                label = data[1]
141
                label.stop_gradient = True
142

143
                img = paddle.reshape(img, shape=[batch_size, -1])
144 145
                cost = mlp(img)
                avg_loss = fluid.layers.reduce_mean(cost)
L
lujun 已提交
146
                dy_out = avg_loss.numpy()
M
minqiyang 已提交
147

M
minqiyang 已提交
148
                if batch_id == 0:
149
                    for param in mlp.parameters():
L
lujun 已提交
150
                        dy_param_init_value[param.name] = param.numpy()
M
minqiyang 已提交
151

L
lujun 已提交
152
                avg_loss.backward()
M
minqiyang 已提交
153
                optimizer.minimize(avg_loss)
154
                mlp.clear_gradients()
M
minqiyang 已提交
155
                dy_param_value = {}
156
                for param in mlp.parameters():
L
lujun 已提交
157
                    dy_param_value[param.name] = param.numpy()
M
minqiyang 已提交
158

M
minqiyang 已提交
159
        with new_program_scope():
C
cnn 已提交
160
            paddle.seed(seed)
L
Leo Chen 已提交
161
            paddle.framework.random._manual_program_seed(seed)
M
minqiyang 已提交
162

163
            if place is None:
164 165 166 167 168
                place = (
                    fluid.CPUPlace()
                    if not core.is_compiled_with_cuda()
                    else fluid.CUDAPlace(0)
                )
Z
zhongpu 已提交
169 170

            exe = fluid.Executor(place)
M
minqiyang 已提交
171

172
            mlp = MLP()
M
minqiyang 已提交
173
            optimizer = self.get_optimizer()
174 175 176
            train_reader = paddle.batch(
                paddle.dataset.mnist.train(), batch_size=128, drop_last=True
            )
M
minqiyang 已提交
177

178 179 180
            img = fluid.layers.data(
                name='pixel', shape=[1, 28, 28], dtype='float32'
            )
M
minqiyang 已提交
181
            label = fluid.layers.data(name='label', shape=[1], dtype='int64')
182
            img = paddle.reshape(img, shape=[batch_size, 784])
183
            cost = mlp(img)
184
            avg_loss = fluid.layers.reduce_mean(cost)
M
minqiyang 已提交
185
            optimizer.minimize(avg_loss)
M
minqiyang 已提交
186 187 188 189

            # initialize params and fetch them
            static_param_init_value = {}
            static_param_name_list = []
190
            for param in mlp.parameters():
M
minqiyang 已提交
191 192
                static_param_name_list.append(param.name)

193 194 195 196
            out = exe.run(
                fluid.default_startup_program(),
                fetch_list=static_param_name_list,
            )
M
minqiyang 已提交
197 198 199 200

            for i in range(len(static_param_name_list)):
                static_param_init_value[static_param_name_list[i]] = out[i]

M
minqiyang 已提交
201
            for batch_id, data in enumerate(train_reader()):
202
                if batch_id >= self.batch_num:
M
minqiyang 已提交
203 204
                    break

M
minqiyang 已提交
205
                static_x_data = np.array(
206 207 208 209 210 211 212
                    [x[0].reshape(1, 28, 28) for x in data]
                ).astype('float32')
                y_data = (
                    np.array([x[1] for x in data])
                    .astype('int64')
                    .reshape([128, 1])
                )
M
minqiyang 已提交
213

M
minqiyang 已提交
214
                fetch_list = [avg_loss.name]
M
minqiyang 已提交
215
                fetch_list.extend(static_param_name_list)
216 217 218 219 220
                out = exe.run(
                    fluid.default_main_program(),
                    feed={"pixel": static_x_data, "label": y_data},
                    fetch_list=fetch_list,
                )
M
minqiyang 已提交
221 222 223 224 225

                static_param_value = {}
                static_out = out[0]
                for i in range(1, len(out)):
                    static_param_value[static_param_name_list[i - 1]] = out[i]
M
minqiyang 已提交
226

227
        for key, value in static_param_init_value.items():
228 229 230
            np.testing.assert_allclose(
                value, dy_param_init_value[key], rtol=1e-05
            )
M
minqiyang 已提交
231

R
ronnywang 已提交
232
        if core.is_compiled_with_rocm():
233 234 235
            np.testing.assert_allclose(
                static_out, dy_out, rtol=1e-05, atol=0.001
            )
R
ronnywang 已提交
236
        else:
237
            np.testing.assert_allclose(static_out, dy_out, rtol=1e-05)
M
minqiyang 已提交
238

239
        for key, value in static_param_value.items():
R
ronnywang 已提交
240
            if core.is_compiled_with_rocm():
241 242 243
                np.testing.assert_allclose(
                    value, dy_param_value[key], rtol=1e-05, atol=0.001
                )
R
ronnywang 已提交
244
            else:
245 246 247
                np.testing.assert_allclose(
                    value, dy_param_value[key], rtol=1e-05
                )
M
minqiyang 已提交
248 249


250
class TestImperativeOptimizerPiecewiseDecay(TestImperativeOptimizerBase):
251 252
    def get_optimizer_dygraph(self, parameter_list):
        bd = [3, 6, 9]
253 254 255 256 257 258 259
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.piecewise_decay(
                boundaries=bd,
                values=[0.1 * (0.1**i) for i in range(len(bd) + 1)],
            ),
            parameter_list=parameter_list,
        )
260 261
        return optimizer

262 263
    def get_optimizer(self):
        bd = [3, 6, 9]
264 265 266 267 268 269
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.piecewise_decay(
                boundaries=bd,
                values=[0.1 * (0.1**i) for i in range(len(bd) + 1)],
            )
        )
270 271
        return optimizer

272
    def func_test_sgd(self):
273 274
        self._check_mlp()

275 276 277 278 279
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

280 281

class TestImperativeOptimizerNaturalExpDecay(TestImperativeOptimizerBase):
282
    def get_optimizer_dygraph(self, parameter_list):
283 284 285 286 287 288 289 290 291
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.natural_exp_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            ),
            parameter_list=parameter_list,
        )
292 293 294 295
        return optimizer

    def get_optimizer(self):
        optimizer = SGDOptimizer(
296 297 298 299 300 301 302
            learning_rate=fluid.layers.natural_exp_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
303 304
        return optimizer

305
    def func_test_sgd(self):
306 307
        self._check_mlp()

308 309 310 311 312
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

313 314

class TestImperativeOptimizerExponentialDecay(TestImperativeOptimizerBase):
315
    def get_optimizer_dygraph(self, parameter_list):
316 317 318 319 320 321 322 323 324
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            ),
            parameter_list=parameter_list,
        )
325 326 327 328
        return optimizer

    def get_optimizer(self):
        optimizer = SGDOptimizer(
329 330 331 332 333 334 335
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
336 337
        return optimizer

338
    def func_test_sgd(self):
339 340
        self._check_mlp()

341 342 343 344 345
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

346 347

class TestImperativeOptimizerInverseTimeDecay(TestImperativeOptimizerBase):
348
    def get_optimizer_dygraph(self, parameter_list):
349 350 351 352 353 354 355 356 357
        optimizer = Adam(
            learning_rate=fluid.layers.inverse_time_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            ),
            parameter_list=parameter_list,
        )
358 359 360 361
        return optimizer

    def get_optimizer(self):
        optimizer = Adam(
362 363 364 365 366 367 368
            learning_rate=fluid.layers.inverse_time_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
369 370
        return optimizer

371
    def func_test_adam(self):
372 373
        self._check_mlp()

374 375 376 377 378
    def test_adam(self):
        with _test_eager_guard():
            self.func_test_adam()
        self.func_test_adam()

379 380

class TestImperativeOptimizerPolynomialDecay(TestImperativeOptimizerBase):
381
    def get_optimizer_dygraph(self, parameter_list):
382 383 384 385 386 387
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.polynomial_decay(
                learning_rate=0.1, decay_steps=5, cycle=self.cycle
            ),
            parameter_list=parameter_list,
        )
388 389
        return optimizer

390
    def get_optimizer(self):
391 392 393 394 395
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.polynomial_decay(
                learning_rate=0.1, decay_steps=5, cycle=self.cycle
            )
        )
396 397
        return optimizer

398
    def func_test_sgd_cycle(self):
399 400 401
        self.cycle = True
        self._check_mlp()

402 403 404 405 406 407
    def test_sgd_cycle(self):
        with _test_eager_guard():
            self.func_test_sgd_cycle()
        self.func_test_sgd_cycle()

    def func_test_sgd(self):
408 409 410
        self.cycle = False
        self._check_mlp()

411 412 413 414 415
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

416

M
minqiyang 已提交
417
class TestImperativeOptimizerCosineDecay(TestImperativeOptimizerBase):
418
    def get_optimizer_dygraph(self, parameter_list):
419 420 421 422 423 424
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.cosine_decay(
                learning_rate=0.1, step_each_epoch=10000, epochs=120
            ),
            parameter_list=parameter_list,
        )
425 426
        return optimizer

M
minqiyang 已提交
427
    def get_optimizer(self):
428 429 430 431 432
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.cosine_decay(
                learning_rate=0.1, step_each_epoch=10000, epochs=120
            )
        )
M
minqiyang 已提交
433 434
        return optimizer

435
    def func_test_sgd(self):
M
minqiyang 已提交
436 437
        self._check_mlp()

438 439 440 441 442
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

M
minqiyang 已提交
443 444

class TestImperativeOptimizerNoamDecay(TestImperativeOptimizerBase):
445
    def get_optimizer_dygraph(self, parameter_list):
446 447 448 449 450 451
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.noam_decay(
                d_model=512, warmup_steps=8000
            ),
            parameter_list=parameter_list,
        )
452 453
        return optimizer

M
minqiyang 已提交
454
    def get_optimizer(self):
455 456 457 458 459
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.noam_decay(
                d_model=512, warmup_steps=8000
            )
        )
M
minqiyang 已提交
460 461
        return optimizer

462
    def func_test_sgd(self):
M
minqiyang 已提交
463
        self._check_mlp()
M
minqiyang 已提交
464

465 466 467 468 469
    def test_sgd(self):
        with _test_eager_guard():
            self.func_test_sgd()
        self.func_test_sgd()

M
minqiyang 已提交
470

471
class TestOptimizerLearningRate(unittest.TestCase):
472
    def func_test_constant_lr(self):
473 474 475
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

476
            linear = paddle.nn.Linear(10, 10)
477 478 479 480 481 482 483

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

            loss = fluid.layers.reduce_mean(b)

484 485 486
            adam = fluid.optimizer.Adam(
                0.001, parameter_list=linear.parameters()
            )
487

488 489 490
            np.testing.assert_allclose(
                adam.current_step_lr(), 0.001, rtol=1e-06, atol=0.0
            )
491 492 493 494 495

            for i in range(10):
                adam.minimize(loss)
                lr = adam.current_step_lr()

496
                np.testing.assert_allclose(lr, 0.001, rtol=1e-06, atol=0.0)
497

498 499 500 501 502 503
    def test_constant_lr(self):
        with _test_eager_guard():
            self.func_test_constant_lr()
        self.func_test_constant_lr()

    def func_test_lr_decay(self):
504 505 506
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

507
            linear = paddle.nn.Linear(10, 10)
508 509 510 511 512 513 514 515 516 517

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

            loss = fluid.layers.reduce_mean(b)

            bd = [2, 4, 6, 8]
            value = [0.2, 0.4, 0.6, 0.8, 1.0]

518 519 520 521
            adam = fluid.optimizer.Adam(
                fluid.dygraph.PiecewiseDecay(bd, value, 0),
                parameter_list=linear.parameters(),
            )
522

523 524 525
            np.testing.assert_allclose(
                adam.current_step_lr(), 0.2, rtol=1e-06, atol=0.0
            )
526 527 528 529 530 531

            ret = [0.2, 0.2, 0.4, 0.4, 0.6, 0.6, 0.8, 0.8, 1.0, 1.0, 1.0, 1.0]
            for i in range(12):
                adam.minimize(loss)
                lr = adam.current_step_lr()

532
                np.testing.assert_allclose(lr, ret[i], rtol=1e-06, atol=0.0)
533

534 535 536 537 538 539
    def test_lr_decay(self):
        with _test_eager_guard():
            self.func_test_lr_decay()
        self.func_test_lr_decay()

    def func_test_lr_decay_natural_exp(self):
540 541 542
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

543
            linear = paddle.nn.Linear(10, 10)
544 545 546 547 548 549 550 551

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

            loss = fluid.layers.reduce_mean(b)
            base_lr = 1.0

552 553 554 555 556 557 558 559 560
            adam = fluid.optimizer.Adam(
                fluid.dygraph.NaturalExpDecay(
                    learning_rate=base_lr,
                    decay_steps=3,
                    decay_rate=0.5,
                    staircase=True,
                ),
                parameter_list=linear.parameters(),
            )
561

562 563 564
            np.testing.assert_allclose(
                adam.current_step_lr(), 1.0, rtol=1e-06, atol=0.0
            )
565 566 567 568 569 570

            ret = [1.0, 1.0, 1.0, np.exp(-0.5), np.exp(-0.5)]
            for i in range(5):
                adam.minimize(loss)
                lr = adam.current_step_lr()

571
                np.testing.assert_allclose(lr, ret[i], rtol=1e-06, atol=0.0)
572

573 574 575 576 577 578
    def test_lr_decay_natural_exp(self):
        with _test_eager_guard():
            self.func_test_lr_decay_natural_exp()
        self.func_test_lr_decay_natural_exp()

    def func_test_set_lr(self):
579 580 581
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

582
            linear = paddle.nn.Linear(10, 10)
583 584 585 586 587 588 589 590 591 592 593 594 595 596

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

            loss = fluid.layers.reduce_mean(b)

            adam = fluid.optimizer.Adam(0.1, parameter_list=linear.parameters())

            lr_list = [0.2, 0.3, 0.4, 0.5, 0.6]
            for i in range(5):
                adam.set_lr(lr_list[i])
                adam.minimize(loss)
                lr = adam.current_step_lr()
597
                np.testing.assert_allclose(lr, lr_list[i], rtol=1e-06, atol=0.0)
598

599 600 601
            lr_var = fluid.layers.create_global_var(
                shape=[1], value=0.7, dtype='float32'
            )
602 603 604
            adam.set_lr(lr_var)
            adam.minimize(loss)
            lr = adam.current_step_lr()
605
            np.testing.assert_allclose(lr, 0.7, rtol=1e-06, atol=0.0)
606 607

            with self.assertRaises(RuntimeError):
608 609 610 611 612 613 614 615 616
                adam = fluid.optimizer.Adam(
                    fluid.dygraph.NaturalExpDecay(
                        learning_rate=0.1,
                        decay_steps=3,
                        decay_rate=0.5,
                        staircase=True,
                    ),
                    parameter_list=linear.parameters(),
                )
617 618
                adam.set_lr(0.01)

619 620 621 622 623
    def test_set_lr(self):
        with _test_eager_guard():
            self.func_test_set_lr()
        self.func_test_set_lr()

624

Z
zhongpu 已提交
625 626
class TestImperativeMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
627 628 629
        optimizer = MomentumOptimizer(
            learning_rate=0.001, momentum=0.9, parameter_list=parameter_list
        )
Z
zhongpu 已提交
630 631 632 633 634 635
        return optimizer

    def get_optimizer(self):
        optimizer = MomentumOptimizer(learning_rate=0.001, momentum=0.9)
        return optimizer

636
    def func_test_momentum(self):
Z
zhongpu 已提交
637 638
        self._check_mlp()

639 640 641 642 643
    def test_momentum(self):
        with _test_eager_guard():
            self.func_test_momentum()
        self.func_test_momentum()

Z
zhongpu 已提交
644 645 646

class TestImperativeLarsMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
647 648 649
        optimizer = LarsMomentumOptimizer(
            learning_rate=0.001, momentum=0.9, parameter_list=parameter_list
        )
Z
zhongpu 已提交
650 651 652 653 654 655
        return optimizer

    def get_optimizer(self):
        optimizer = LarsMomentumOptimizer(learning_rate=0.001, momentum=0.9)
        return optimizer

656
    def func_test_larsmomentum(self):
Z
zhongpu 已提交
657 658
        self._check_mlp()

659 660 661 662 663
    def test_larsmomentum(self):
        with _test_eager_guard():
            self.func_test_larsmomentum()
        self.func_test_larsmomentum()

Z
zhongpu 已提交
664 665 666

class TestImperativeAdagradOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
667 668 669
        optimizer = AdagradOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
670 671 672 673 674 675
        return optimizer

    def get_optimizer(self):
        optimizer = AdagradOptimizer(learning_rate=0.2)
        return optimizer

676
    def func_test_adagrad(self):
Z
zhongpu 已提交
677 678
        self._check_mlp()

679 680 681 682 683
    def test_adagrad(self):
        with _test_eager_guard():
            self.func_test_adagrad()
        self.func_test_adagrad()

Z
zhongpu 已提交
684 685 686

class TestImperativeAdamaxOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
687 688 689
        optimizer = AdamaxOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
690 691 692 693 694 695
        return optimizer

    def get_optimizer(self):
        optimizer = AdamaxOptimizer(learning_rate=0.2)
        return optimizer

696
    def func_test_adamax(self):
Z
zhongpu 已提交
697 698
        self._check_mlp()

699 700 701 702 703
    def test_adamax(self):
        with _test_eager_guard():
            self.func_test_adamax()
        self.func_test_adamax()

Z
zhongpu 已提交
704 705 706

class TestImperativeDpsgdOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
707 708 709 710 711 712 713
        optimizer = DpsgdOptimizer(
            learning_rate=0.01,
            clip=10.0,
            batch_size=16.0,
            sigma=1.0,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
714 715 716 717
        optimizer._seed = 100
        return optimizer

    def get_optimizer(self):
718 719 720
        optimizer = DpsgdOptimizer(
            learning_rate=0.01, clip=10.0, batch_size=16.0, sigma=1.0
        )
Z
zhongpu 已提交
721 722 723
        optimizer._seed = 100
        return optimizer

724
    def func_test_dpsgd(self):
Z
zhongpu 已提交
725 726
        self._check_mlp(place=fluid.CPUPlace())

727 728 729 730 731
    def test_dpsgd(self):
        with _test_eager_guard():
            self.func_test_dpsgd()
        self.func_test_dpsgd()

Z
zhongpu 已提交
732 733 734

class TestImperativeDecayedAdagradOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
735 736 737
        optimizer = DecayedAdagradOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
738 739 740 741 742 743
        return optimizer

    def get_optimizer(self):
        optimizer = DecayedAdagradOptimizer(learning_rate=0.2)
        return optimizer

744
    def func_test_decayadagrad(self):
Z
zhongpu 已提交
745 746
        self._check_mlp()

747 748 749 750 751
    def test_decayadagrad(self):
        with _test_eager_guard():
            self.func_test_decayadagrad()
        self.func_test_decayadagrad()

Z
zhongpu 已提交
752 753 754

class TestImperativeAdadeltaOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
755 756 757 758 759 760
        optimizer = AdadeltaOptimizer(
            learning_rate=0.0003,
            epsilon=1.0e-6,
            rho=0.95,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
761 762 763
        return optimizer

    def get_optimizer(self):
764 765 766
        optimizer = AdadeltaOptimizer(
            learning_rate=0.0003, epsilon=1.0e-6, rho=0.95
        )
Z
zhongpu 已提交
767 768
        return optimizer

769
    def func_test_adadelta(self):
Z
zhongpu 已提交
770 771
        self._check_mlp()

772 773 774 775 776
    def test_adadelta(self):
        with _test_eager_guard():
            self.func_test_adadelta()
        self.func_test_adadelta()

Z
zhongpu 已提交
777 778 779

class TestImperativeRMSPropOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
780 781 782
        optimizer = RMSPropOptimizer(
            learning_rate=0.1, parameter_list=parameter_list
        )
Z
zhongpu 已提交
783 784 785 786 787 788
        return optimizer

    def get_optimizer(self):
        optimizer = RMSPropOptimizer(learning_rate=0.1)
        return optimizer

789
    def func_test_rmsprop(self):
Z
zhongpu 已提交
790 791
        self._check_mlp()

792 793 794 795 796
    def test_rmsprop(self):
        with _test_eager_guard():
            self.func_test_rmsprop()
        self.func_test_rmsprop()

Z
zhongpu 已提交
797 798 799

class TestImperativeFtrlOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
800 801 802
        optimizer = FtrlOptimizer(
            learning_rate=0.1, parameter_list=parameter_list
        )
Z
zhongpu 已提交
803 804 805 806 807 808
        return optimizer

    def get_optimizer(self):
        optimizer = FtrlOptimizer(learning_rate=0.1)
        return optimizer

809
    def func_test_ftrl(self):
Z
zhongpu 已提交
810 811
        self._check_mlp()

812 813 814 815 816
    def test_ftrl(self):
        with _test_eager_guard():
            self.func_test_ftrl()
        self.func_test_ftrl()

Z
zhongpu 已提交
817 818 819 820 821 822 823

def exclude_fn(param):
    return param.name.endswith('.b_0')


class TestImperativeLambOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
824 825 826 827 828
        optimizer = LambOptimizer(
            learning_rate=0.002,
            exclude_from_weight_decay_fn=exclude_fn,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
829 830 831
        return optimizer

    def get_optimizer(self):
832 833 834
        optimizer = LambOptimizer(
            learning_rate=0.002, exclude_from_weight_decay_fn=exclude_fn
        )
Z
zhongpu 已提交
835 836
        return optimizer

837 838
    # should fix: may fail in CI-windows
    def _test_lamb(self):
Z
zhongpu 已提交
839 840 841 842 843
        self._check_mlp()


class TestImperativeModelAverage(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
844 845 846
        optimizer = ModelAverage(
            0.15, min_average_window=10000, max_average_window=12500
        )
Z
zhongpu 已提交
847 848
        return optimizer

849
    def func_test_modelaverage(self):
Z
zhongpu 已提交
850 851 852
        exception_message = "In dygraph, don't support ModelAverage."
        self._check_exception(exception_message)

853 854 855 856 857
    def test_modelaverage(self):
        with _test_eager_guard():
            self.func_test_modelaverage()
        self.func_test_modelaverage()

Z
zhongpu 已提交
858 859 860

class TestImperativeDGCMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
861 862 863 864 865 866 867
        optimizer = DGCMomentumOptimizer(
            learning_rate=0.0001,
            momentum=0.9,
            rampup_step=1000,
            rampup_begin_step=1252,
            sparsity=[0.999, 0.999],
        )
Z
zhongpu 已提交
868 869
        return optimizer

870
    def func_test_dgcmomentum(self):
Z
zhongpu 已提交
871 872 873
        exception_message = "In dygraph, don't support DGCMomentumOptimizer."
        self._check_exception(exception_message)

874 875 876 877 878
    def test_dgcmomentum(self):
        with _test_eager_guard():
            self.func_test_dgcmomentum()
        self.func_test_dgcmomentum()

Z
zhongpu 已提交
879 880 881 882 883 884

class TestImperativeExponentialMovingAverage(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
        optimizer = ExponentialMovingAverage(0.999)
        return optimizer

885
    def func_test_exponentialmoving(self):
886 887 888
        exception_message = (
            "In dygraph, don't support ExponentialMovingAverage."
        )
Z
zhongpu 已提交
889 890
        self._check_exception(exception_message)

891 892 893 894 895
    def test_exponentialmoving(self):
        with _test_eager_guard():
            self.func_test_exponentialmoving()
        self.func_test_exponentialmoving()

Z
zhongpu 已提交
896 897 898

class TestImperativePipelineOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
899 900 901
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
902 903 904
        optimizer = PipelineOptimizer(optimizer)
        return optimizer

905
    def func_test_pipline(self):
Z
zhongpu 已提交
906 907 908
        exception_message = "In dygraph, don't support PipelineOptimizer."
        self._check_exception(exception_message)

909 910 911 912 913
    def test_pipline(self):
        with _test_eager_guard():
            self.func_test_pipline()
        self.func_test_pipline()

Z
zhongpu 已提交
914 915 916

class TestImperativeLookaheadOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
917 918 919
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
920 921 922
        optimizer = LookaheadOptimizer(optimizer, alpha=0.5, k=5)
        return optimizer

923
    def func_test_lookahead(self):
Z
zhongpu 已提交
924 925 926
        exception_message = "In dygraph, don't support LookaheadOptimizer."
        self._check_exception(exception_message)

927 928 929 930 931
    def test_lookahead(self):
        with _test_eager_guard():
            self.func_test_lookahead()
        self.func_test_lookahead()

Z
zhongpu 已提交
932 933 934

class TestImperativeRecomputeOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
935 936 937
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
938 939 940
        optimizer = RecomputeOptimizer(optimizer)
        return optimizer

941
    def func_test_recompute(self):
Z
zhongpu 已提交
942 943 944
        exception_message = "In dygraph, don't support RecomputeOptimizer."
        self._check_exception(exception_message)

945 946 947 948 949
    def test_recompute(self):
        with _test_eager_guard():
            self.func_test_recompute()
        self.func_test_recompute()

Z
zhongpu 已提交
950

H
hong 已提交
951
class TestImperativeOptimizerList(unittest.TestCase):
952
    def func_test_parameter_list(self):
H
hong 已提交
953
        with fluid.dygraph.guard():
954 955
            linear_1 = paddle.nn.Linear(10, 10)
            linear_2 = paddle.nn.Linear(10, 10)
H
hong 已提交
956

957 958 959 960 961 962
            sgd = SGDOptimizer(
                1.0,
                parameter_list=itertools.chain(
                    linear_1.parameters(), linear_2.parameters()
                ),
            )
H
hong 已提交
963 964 965 966 967 968 969 970 971 972 973

            in_np = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")
            in_data = fluid.dygraph.to_variable(in_np)

            y = linear_1(in_data)
            y = linear_2(y)
            loss = fluid.layers.reduce_mean(y)
            loss.backward()
            sgd.minimize(loss)

            self.assertTrue(
974 975 976
                len(sgd._parameter_list)
                == len(linear_1.parameters() + linear_2.parameters())
            )
H
hong 已提交
977

978 979 980 981 982
    def test_parameter_list(self):
        with _test_eager_guard():
            self.func_test_parameter_list()
        self.func_test_parameter_list()

H
hong 已提交
983

M
minqiyang 已提交
984 985
if __name__ == '__main__':
    unittest.main()