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
M
minqiyang 已提交
22
import paddle.fluid as 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(fluid.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 505 506 507 508 509 510
            adam = fluid.optimizer.Adam(
                fluid.dygraph.NaturalExpDecay(
                    learning_rate=base_lr,
                    decay_steps=3,
                    decay_rate=0.5,
                    staircase=True,
                ),
                parameter_list=linear.parameters(),
            )
511

512 513 514
            np.testing.assert_allclose(
                adam.current_step_lr(), 1.0, rtol=1e-06, atol=0.0
            )
515 516 517 518 519 520

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

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

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

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

            a = fluid.dygraph.to_variable(a)

            b = linear(a)

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

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

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

            with self.assertRaises(RuntimeError):
553 554 555 556 557 558 559 560 561
                adam = fluid.optimizer.Adam(
                    fluid.dygraph.NaturalExpDecay(
                        learning_rate=0.1,
                        decay_steps=3,
                        decay_rate=0.5,
                        staircase=True,
                    ),
                    parameter_list=linear.parameters(),
                )
562 563
                adam.set_lr(0.01)

564

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

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

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

Z
zhongpu 已提交
579 580 581

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

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

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

Z
zhongpu 已提交
594 595 596

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

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

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

Z
zhongpu 已提交
609 610 611

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

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

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

Z
zhongpu 已提交
624 625 626

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

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

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

Z
zhongpu 已提交
647 648 649

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

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

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

Z
zhongpu 已提交
662 663 664

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

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

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

Z
zhongpu 已提交
682 683 684

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

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

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

Z
zhongpu 已提交
697 698 699

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

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

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

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

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


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

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

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


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

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


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

760
    def test_dgcmomentum(self):
Z
zhongpu 已提交
761 762 763 764 765 766 767 768 769
        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

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


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

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


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

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


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

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


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

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

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

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


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