test_imperative_optimizer.py 25.4 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
import numpy as np
19
from test_imperative_base import new_program_scope
M
minqiyang 已提交
20

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

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

48

49
class MLP(paddle.nn.Layer):
50
    def __init__(self, param_attr=None, bias_attr=None):
51
        super().__init__()
M
minqiyang 已提交
52

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

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

M
minqiyang 已提交
61

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

66 67 68
    def get_optimizer_dygraph(self, parameter_list):
        raise NotImplementedError()

69
    def get_optimizer(self):
70
        raise NotImplementedError()
M
minqiyang 已提交
71

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

        return _reader_imple

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

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

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

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

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

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

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

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

137 138
                img = data[0]
                label = data[1]
139
                label.stop_gradient = True
140

141
                img = paddle.reshape(img, shape=[batch_size, -1])
142
                cost = mlp(img)
143
                avg_loss = paddle.mean(cost)
L
lujun 已提交
144
                dy_out = avg_loss.numpy()
M
minqiyang 已提交
145

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

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

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

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

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

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

G
GGBond8488 已提交
176 177 178 179 180
            img = paddle.static.data(
                name='pixel', shape=[-1, 1, 28, 28], dtype='float32'
            )
            label = paddle.static.data(
                name='label', shape=[-1, 1], dtype='int64'
181
            )
182
            img = paddle.reshape(img, shape=[batch_size, 784])
183
            cost = mlp(img)
184
            avg_loss = paddle.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 test_sgd(self):
273
        self._check_mlp()
274

275 276

class TestImperativeOptimizerNaturalExpDecay(TestImperativeOptimizerBase):
277
    def get_optimizer_dygraph(self, parameter_list):
278 279 280 281 282 283 284 285 286
        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,
        )
287 288 289 290
        return optimizer

    def get_optimizer(self):
        optimizer = SGDOptimizer(
291 292 293 294 295 296 297
            learning_rate=fluid.layers.natural_exp_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
298 299
        return optimizer

300
    def test_sgd(self):
301
        self._check_mlp()
302

303 304

class TestImperativeOptimizerExponentialDecay(TestImperativeOptimizerBase):
305
    def get_optimizer_dygraph(self, parameter_list):
306 307 308 309 310 311 312 313 314
        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,
        )
315 316 317 318
        return optimizer

    def get_optimizer(self):
        optimizer = SGDOptimizer(
319 320 321 322 323 324 325
            learning_rate=fluid.layers.exponential_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
326 327
        return optimizer

328
    def test_sgd(self):
329
        self._check_mlp()
330

331 332

class TestImperativeOptimizerInverseTimeDecay(TestImperativeOptimizerBase):
333
    def get_optimizer_dygraph(self, parameter_list):
334 335 336 337 338 339 340 341 342
        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,
        )
343 344 345 346
        return optimizer

    def get_optimizer(self):
        optimizer = Adam(
347 348 349 350 351 352 353
            learning_rate=fluid.layers.inverse_time_decay(
                learning_rate=0.1,
                decay_steps=10000,
                decay_rate=0.5,
                staircase=True,
            )
        )
354 355
        return optimizer

356
    def test_adam(self):
357
        self._check_mlp()
358

359 360

class TestImperativeOptimizerPolynomialDecay(TestImperativeOptimizerBase):
361
    def get_optimizer_dygraph(self, parameter_list):
362 363 364 365 366 367
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.polynomial_decay(
                learning_rate=0.1, decay_steps=5, cycle=self.cycle
            ),
            parameter_list=parameter_list,
        )
368 369
        return optimizer

370
    def get_optimizer(self):
371 372 373 374 375
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.polynomial_decay(
                learning_rate=0.1, decay_steps=5, cycle=self.cycle
            )
        )
376 377
        return optimizer

378
    def test_sgd_cycle(self):
379 380 381
        self.cycle = True
        self._check_mlp()

382
    def test_sgd(self):
383 384 385 386
        self.cycle = False
        self._check_mlp()


M
minqiyang 已提交
387
class TestImperativeOptimizerCosineDecay(TestImperativeOptimizerBase):
388
    def get_optimizer_dygraph(self, parameter_list):
389 390 391 392 393 394
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.cosine_decay(
                learning_rate=0.1, step_each_epoch=10000, epochs=120
            ),
            parameter_list=parameter_list,
        )
395 396
        return optimizer

M
minqiyang 已提交
397
    def get_optimizer(self):
398 399 400 401 402
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.cosine_decay(
                learning_rate=0.1, step_each_epoch=10000, epochs=120
            )
        )
M
minqiyang 已提交
403 404
        return optimizer

405
    def test_sgd(self):
406
        self._check_mlp()
407

M
minqiyang 已提交
408 409

class TestImperativeOptimizerNoamDecay(TestImperativeOptimizerBase):
410
    def get_optimizer_dygraph(self, parameter_list):
411 412 413 414 415 416
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.noam_decay(
                d_model=512, warmup_steps=8000
            ),
            parameter_list=parameter_list,
        )
417 418
        return optimizer

M
minqiyang 已提交
419
    def get_optimizer(self):
420 421 422 423 424
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.noam_decay(
                d_model=512, warmup_steps=8000
            )
        )
M
minqiyang 已提交
425 426
        return optimizer

427
    def test_sgd(self):
428
        self._check_mlp()
429

M
minqiyang 已提交
430

431
class TestOptimizerLearningRate(unittest.TestCase):
432
    def test_constant_lr(self):
433 434 435
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

436
            linear = paddle.nn.Linear(10, 10)
437 438 439 440 441

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

442
            loss = paddle.mean(b)
443

444 445 446
            adam = fluid.optimizer.Adam(
                0.001, parameter_list=linear.parameters()
            )
447

448 449 450
            np.testing.assert_allclose(
                adam.current_step_lr(), 0.001, rtol=1e-06, atol=0.0
            )
451 452 453 454 455

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

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

458
    def test_lr_decay(self):
459 460 461
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

462
            linear = paddle.nn.Linear(10, 10)
463 464 465 466 467

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

468
            loss = paddle.mean(b)
469 470 471 472

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

473 474 475 476
            adam = fluid.optimizer.Adam(
                fluid.dygraph.PiecewiseDecay(bd, value, 0),
                parameter_list=linear.parameters(),
            )
477

478 479 480
            np.testing.assert_allclose(
                adam.current_step_lr(), 0.2, rtol=1e-06, atol=0.0
            )
481 482 483 484 485 486

            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()

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

489
    def test_lr_decay_natural_exp(self):
490 491 492
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

493
            linear = paddle.nn.Linear(10, 10)
494 495 496 497 498

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

499
            loss = paddle.mean(b)
500 501
            base_lr = 1.0

502 503 504
            scheduler = paddle.optimizer.lr.NaturalExpDecay(
                learning_rate=base_lr,
                gamma=0.5,
505
            )
506 507 508
            adam = paddle.optimizer.Adam(
                learning_rate=scheduler,
                parameters=linear.parameters(),
509
            )
510

511 512
            np.testing.assert_allclose(adam.get_lr(), 1.0, rtol=1e-06, atol=0.0)

513
            ret = [1.0, 1.0, 1.0, np.exp(-0.5), np.exp(-0.5)]
514
            counter = 0
515 516
            for i in range(5):
                adam.minimize(loss)
517 518 519 520 521
                lr = adam.get_lr()
                counter += 1
                if counter % 3 == 0:
                    adam.step()
                    scheduler.step()
522
                np.testing.assert_allclose(lr, ret[i], rtol=1e-06, atol=0.0)
523

524
    def test_set_lr(self):
525 526 527
        with fluid.dygraph.guard():
            a = np.random.uniform(-0.1, 0.1, [10, 10]).astype("float32")

528
            linear = paddle.nn.Linear(10, 10)
529 530 531 532 533

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

534
            loss = paddle.mean(b)
535 536 537 538 539 540 541 542

            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()
543
                np.testing.assert_allclose(lr, lr_list[i], rtol=1e-06, atol=0.0)
544

545
            lr_var = paddle.static.create_global_var(
546 547
                shape=[1], value=0.7, dtype='float32'
            )
548 549 550
            adam.set_lr(lr_var)
            adam.minimize(loss)
            lr = adam.current_step_lr()
551
            np.testing.assert_allclose(lr, 0.7, rtol=1e-06, atol=0.0)
552 553

            with self.assertRaises(RuntimeError):
554 555
                adam = paddle.optimizer.Adam(
                    paddle.optimizer.lr.NaturalExpDecay(
556
                        learning_rate=0.1,
557
                        gamma=0.5,
558
                    ),
559
                    parameters=linear.parameters(),
560
                )
561 562
                adam.set_lr(0.01)

563

Z
zhongpu 已提交
564 565
class TestImperativeMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
566 567 568
        optimizer = MomentumOptimizer(
            learning_rate=0.001, momentum=0.9, parameter_list=parameter_list
        )
Z
zhongpu 已提交
569 570 571 572 573 574
        return optimizer

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

575
    def test_momentum(self):
576
        self._check_mlp()
577

Z
zhongpu 已提交
578 579 580

class TestImperativeLarsMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
581 582 583
        optimizer = LarsMomentumOptimizer(
            learning_rate=0.001, momentum=0.9, parameter_list=parameter_list
        )
Z
zhongpu 已提交
584 585 586 587 588 589
        return optimizer

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

590
    def test_larsmomentum(self):
591
        self._check_mlp()
592

Z
zhongpu 已提交
593 594 595

class TestImperativeAdagradOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
596 597 598
        optimizer = AdagradOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
599 600 601 602 603 604
        return optimizer

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

605
    def test_adagrad(self):
606
        self._check_mlp()
607

Z
zhongpu 已提交
608 609 610

class TestImperativeAdamaxOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
611 612 613
        optimizer = AdamaxOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
614 615 616 617 618 619
        return optimizer

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

620
    def test_adamax(self):
621
        self._check_mlp()
622

Z
zhongpu 已提交
623 624 625

class TestImperativeDpsgdOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
626 627 628 629 630 631 632
        optimizer = DpsgdOptimizer(
            learning_rate=0.01,
            clip=10.0,
            batch_size=16.0,
            sigma=1.0,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
633 634 635 636
        optimizer._seed = 100
        return optimizer

    def get_optimizer(self):
637 638 639
        optimizer = DpsgdOptimizer(
            learning_rate=0.01, clip=10.0, batch_size=16.0, sigma=1.0
        )
Z
zhongpu 已提交
640 641 642
        optimizer._seed = 100
        return optimizer

643
    def test_dpsgd(self):
644
        self._check_mlp(place=fluid.CPUPlace())
645

Z
zhongpu 已提交
646 647 648

class TestImperativeDecayedAdagradOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
649 650 651
        optimizer = DecayedAdagradOptimizer(
            learning_rate=0.2, parameter_list=parameter_list
        )
Z
zhongpu 已提交
652 653 654 655 656 657
        return optimizer

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

658
    def test_decayadagrad(self):
659
        self._check_mlp()
660

Z
zhongpu 已提交
661 662 663

class TestImperativeAdadeltaOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
664 665 666 667 668 669
        optimizer = AdadeltaOptimizer(
            learning_rate=0.0003,
            epsilon=1.0e-6,
            rho=0.95,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
670 671 672
        return optimizer

    def get_optimizer(self):
673 674 675
        optimizer = AdadeltaOptimizer(
            learning_rate=0.0003, epsilon=1.0e-6, rho=0.95
        )
Z
zhongpu 已提交
676 677
        return optimizer

678
    def test_adadelta(self):
679
        self._check_mlp()
680

Z
zhongpu 已提交
681 682 683

class TestImperativeRMSPropOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
684 685 686
        optimizer = RMSPropOptimizer(
            learning_rate=0.1, parameter_list=parameter_list
        )
Z
zhongpu 已提交
687 688 689 690 691 692
        return optimizer

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

693
    def test_rmsprop(self):
694
        self._check_mlp()
695

Z
zhongpu 已提交
696 697 698

class TestImperativeFtrlOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
699 700 701
        optimizer = FtrlOptimizer(
            learning_rate=0.1, parameter_list=parameter_list
        )
Z
zhongpu 已提交
702 703 704 705 706 707
        return optimizer

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

708
    def test_ftrl(self):
709
        self._check_mlp()
710

Z
zhongpu 已提交
711 712 713 714 715 716 717

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


class TestImperativeLambOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
718 719 720 721 722
        optimizer = LambOptimizer(
            learning_rate=0.002,
            exclude_from_weight_decay_fn=exclude_fn,
            parameter_list=parameter_list,
        )
Z
zhongpu 已提交
723 724 725
        return optimizer

    def get_optimizer(self):
726 727 728
        optimizer = LambOptimizer(
            learning_rate=0.002, exclude_from_weight_decay_fn=exclude_fn
        )
Z
zhongpu 已提交
729 730
        return optimizer

731 732
    # should fix: may fail in CI-windows
    def _test_lamb(self):
Z
zhongpu 已提交
733 734 735 736 737
        self._check_mlp()


class TestImperativeModelAverage(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
738 739 740
        optimizer = ModelAverage(
            0.15, min_average_window=10000, max_average_window=12500
        )
Z
zhongpu 已提交
741 742
        return optimizer

743
    def test_modelaverage(self):
Z
zhongpu 已提交
744 745 746 747 748 749
        exception_message = "In dygraph, don't support ModelAverage."
        self._check_exception(exception_message)


class TestImperativeDGCMomentumOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
750 751 752 753 754 755 756
        optimizer = DGCMomentumOptimizer(
            learning_rate=0.0001,
            momentum=0.9,
            rampup_step=1000,
            rampup_begin_step=1252,
            sparsity=[0.999, 0.999],
        )
Z
zhongpu 已提交
757 758
        return optimizer

759
    def test_dgcmomentum(self):
Z
zhongpu 已提交
760 761 762 763 764 765 766 767 768
        exception_message = "In dygraph, don't support DGCMomentumOptimizer."
        self._check_exception(exception_message)


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

769
    def test_exponentialmoving(self):
770 771 772
        exception_message = (
            "In dygraph, don't support ExponentialMovingAverage."
        )
Z
zhongpu 已提交
773 774 775 776 777
        self._check_exception(exception_message)


class TestImperativePipelineOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
778 779 780
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
781 782 783
        optimizer = PipelineOptimizer(optimizer)
        return optimizer

784
    def test_pipline(self):
Z
zhongpu 已提交
785 786 787 788 789 790
        exception_message = "In dygraph, don't support PipelineOptimizer."
        self._check_exception(exception_message)


class TestImperativeLookaheadOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
791 792 793
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
794 795 796
        optimizer = LookaheadOptimizer(optimizer, alpha=0.5, k=5)
        return optimizer

797
    def test_lookahead(self):
Z
zhongpu 已提交
798 799 800 801 802 803
        exception_message = "In dygraph, don't support LookaheadOptimizer."
        self._check_exception(exception_message)


class TestImperativeRecomputeOptimizer(TestImperativeOptimizerBase):
    def get_optimizer_dygraph(self, parameter_list):
804 805 806
        optimizer = fluid.optimizer.SGD(
            learning_rate=0.5, parameter_list=parameter_list
        )
Z
zhongpu 已提交
807 808 809
        optimizer = RecomputeOptimizer(optimizer)
        return optimizer

810
    def test_recompute(self):
Z
zhongpu 已提交
811 812 813 814
        exception_message = "In dygraph, don't support RecomputeOptimizer."
        self._check_exception(exception_message)


H
hong 已提交
815
class TestImperativeOptimizerList(unittest.TestCase):
816
    def test_parameter_list(self):
H
hong 已提交
817
        with fluid.dygraph.guard():
818 819
            linear_1 = paddle.nn.Linear(10, 10)
            linear_2 = paddle.nn.Linear(10, 10)
H
hong 已提交
820

821 822 823 824 825 826
            sgd = SGDOptimizer(
                1.0,
                parameter_list=itertools.chain(
                    linear_1.parameters(), linear_2.parameters()
                ),
            )
H
hong 已提交
827 828 829 830 831 832

            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)
833
            loss = paddle.mean(y)
H
hong 已提交
834 835 836 837
            loss.backward()
            sgd.minimize(loss)

            self.assertTrue(
838 839 840
                len(sgd._parameter_list)
                == len(linear_1.parameters() + linear_2.parameters())
            )
H
hong 已提交
841 842


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