test_adam_op.py 45.1 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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 unittest
16

17
import numpy as np
姜永久 已提交
18
from eager_op_test import OpTest
19

M
MRXLT 已提交
20
import paddle
21 22 23
import paddle.fluid as fluid
from paddle.fluid import core
from paddle.fluid.op import Operator
24 25


姜永久 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
def adam_wrapper(
    param,
    grad,
    LearningRate,
    moment1,
    moment2,
    beta1_pow,
    beta2_pow,
    master_weight=None,
    find_inf=None,
    beta1=0.78,
    beta2=0.836,
    epsilon=1e-4,
    lazy_mode=False,
):
    _, _, _, _, _, _ = paddle._C_ops.adam_(
        param,
        grad,
        LearningRate,
        moment1,
        moment2,
        beta1_pow,
        beta2_pow,
        master_weight,
        find_inf,
        beta1,
        beta2,
        epsilon,
        lazy_mode,
        1000,
        False,
        False,
    )


61 62
class TestAdamOp1(OpTest):
    def setUp(self):
63
        '''Test Adam Op with supplied attributes'''
64
        self.op_type = "adam"
姜永久 已提交
65 66
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.004
        beta1 = 0.78
        beta2 = 0.836
        epsilon = 1e-4
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
87
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
88 89 90 91
        }

        self.attrs = {'epsilon': epsilon, 'beta1': beta1, 'beta2': beta2}

92
        param_out, moment1_out, moment2_out = adam_step(self.inputs, self.attrs)
93 94 95 96

        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
A
Aurelius84 已提交
97 98
            'ParamOut': param_out,
            'Beta1PowOut': np.array([beta1_pow]).astype("float32") * beta1,
99
            'Beta2PowOut': np.array([beta2_pow]).astype("float32") * beta2,
100 101 102 103 104 105 106
        }

    def test_check_output(self):
        self.check_output()


class TestAdamOp2(OpTest):
107 108 109
    def set_shape(self):
        self.shape = (102, 105)

110
    def setUp(self):
111
        '''Test Adam Op with supplied attributes'''
112
        self.op_type = "adam"
姜永久 已提交
113 114
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
115 116 117 118
        self.set_shape()
        param = np.random.uniform(-1, 1, self.shape).astype("float32")
        grad = np.random.uniform(-1, 1, self.shape).astype("float32")
        moment1 = np.random.uniform(-1, 1, self.shape).astype("float32")
119
        # The second moment is positive
120
        moment2 = np.random.random(self.shape).astype("float32")
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

        learning_rate = 0.001
        beta1 = 0.9
        beta2 = 0.999
        epsilon = 1e-8
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
136
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
137 138 139 140
        }

        attributes = {'epsilon': epsilon, 'beta1': beta1, 'beta2': beta2}

141
        param_out, moment1_out, moment2_out = adam_step(self.inputs, attributes)
142 143 144 145

        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
A
Aurelius84 已提交
146 147
            'ParamOut': param_out,
            'Beta1PowOut': np.array([beta1_pow]).astype("float32") * beta1,
148
            'Beta2PowOut': np.array([beta2_pow]).astype("float32") * beta2,
149 150 151 152 153 154
        }

    def test_check_output(self):
        self.check_output()


155 156
class TestAdamOnlyTailOp(TestAdamOp2):
    def set_shape(self):
157
        self.shape = 3
158 159


160 161
class TestAdamOpMultipleSteps(OpTest):
    def setUp(self):
162
        '''Test Adam Operator with supplied attributes'''
163
        self.op_type = "adam"
姜永久 已提交
164 165
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
166 167 168 169 170 171 172 173 174
        self.num_steps = 10

        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.001
A
Aurelius84 已提交
175 176
        self.beta1 = 0.9
        self.beta2 = 0.999
177
        epsilon = 1e-8
A
Aurelius84 已提交
178 179
        self.beta1_pow = self.beta1**10
        self.beta2_pow = self.beta2**10
180 181 182 183 184 185 186

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
A
Aurelius84 已提交
187
            'Beta1Pow': np.array([self.beta1_pow]).astype("float32"),
188
            'Beta2Pow': np.array([self.beta2_pow]).astype("float32"),
189 190
        }

A
Aurelius84 已提交
191 192 193
        self.attrs = {
            'epsilon': epsilon,
            'beta1': self.beta1,
194
            'beta2': self.beta2,
A
Aurelius84 已提交
195
        }
196 197 198

    def test_check_output(self):
        for _ in range(self.num_steps):
199 200 201
            param_out, moment1_out, moment2_out = adam_step(
                self.inputs, self.attrs
            )
202

A
Aurelius84 已提交
203 204
            beta1_pow_out = self.inputs['Beta1Pow'] * self.beta1
            beta2_pow_out = self.inputs['Beta2Pow'] * self.beta2
205 206 207
            self.outputs = {
                'Moment1Out': moment1_out,
                'Moment2Out': moment2_out,
A
Aurelius84 已提交
208 209
                'ParamOut': param_out,
                'Beta1PowOut': beta1_pow_out,
210
                'Beta2PowOut': beta2_pow_out,
211 212 213 214 215 216 217 218 219
            }

            # Verify output for this step
            self.check_output()

            # Output of this step becomes input for next step
            self.inputs['Param'] = param_out
            self.inputs['Moment1'] = moment1_out
            self.inputs['Moment2'] = moment2_out
220 221

            # Update powers of Beta1 and Beta2 for next time step
A
Aurelius84 已提交
222 223
            self.inputs['Beta1Pow'] = beta1_pow_out
            self.inputs['Beta2Pow'] = beta2_pow_out
224 225

            # Randomize gradient for next step
226 227 228
            self.inputs['Grad'] = np.random.uniform(-1, 1, (102, 105)).astype(
                "float32"
            )
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248


def adam_step(inputs, attributes):
    '''
    Simulate one step of the adam optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment1, moment2,
    beta1 power accumulator and beta2 power accumulator
    '''
    param = inputs['Param']
    grad = inputs['Grad']
    moment1 = inputs['Moment1']
    moment2 = inputs['Moment2']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']
    beta2_pow = inputs['Beta2Pow']

    epsilon = attributes['epsilon']

249 250 251 252 253 254 255 256 257
    if 'beta1' in attributes:
        beta1 = attributes['beta1']
    else:
        beta1 = inputs['Beta1Tensor'][0]
    if 'beta2' in attributes:
        beta2 = attributes['beta2']
    else:
        beta2 = inputs['Beta2Tensor'][0]

258 259
    moment1_out = beta1 * moment1 + (1 - beta1) * grad
    moment2_out = beta2 * moment2 + (1 - beta2) * np.square(grad)
260
    lr_t = lr * np.sqrt(1 - beta2_pow) / (1 - beta1_pow)
261
    param_out = param - lr_t * (moment1_out / (np.sqrt(moment2_out) + epsilon))
262
    return param_out, moment1_out, moment2_out
263 264


R
Roc 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
def adamw_step(inputs, attributes):
    '''
    Simulate one step of the adam optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment1, moment2,
    beta1 power accumulator and beta2 power accumulator
    '''
    param = inputs['Param']
    grad = inputs['Grad']
    moment1 = inputs['Moment1']
    moment2 = inputs['Moment2']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']
    beta2_pow = inputs['Beta2Pow']

    epsilon = attributes['epsilon']
    coeff = attributes["coeff"]
    if attributes.get("with_decay", False):
        decay = 1.0 - lr * coeff
        param2 = param * decay
        param = param2.copy()
    if 'beta1' in attributes:
        beta1 = attributes['beta1']
    else:
        beta1 = inputs['Beta1Tensor'][0]
    if 'beta2' in attributes:
        beta2 = attributes['beta2']
    else:
        beta2 = inputs['Beta2Tensor'][0]

    moment1_out = beta1 * moment1 + (1 - beta1) * grad
    moment2_out = beta2 * moment2 + (1 - beta2) * np.square(grad)
    lr_t = lr * np.sqrt(1 - beta2_pow) / (1 - beta1_pow)
    param_out = param - lr_t * (moment1_out / (np.sqrt(moment2_out) + epsilon))

    return param_out, moment1_out, moment2_out


304 305 306
def adam_step_sparse(
    inputs, attributes, height, rows, row_numel, np_grad, lazy_mode
):
T
wip  
typhoonzero 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    '''
    Simulate one step of the adam optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment1, moment2,
    beta1 power accumulator and beta2 power accumulator
    '''
    param = inputs['Param']
    # grad = inputs['Grad']
    moment1 = inputs['Moment1']
    moment2 = inputs['Moment2']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']
    beta2_pow = inputs['Beta2Pow']

    beta1 = attributes['beta1']
    beta2 = attributes['beta2']
    epsilon = attributes['epsilon']

T
typhoonzero 已提交
326 327 328
    moment1_out = np.zeros(shape=[height, row_numel])
    moment2_out = np.zeros(shape=[height, row_numel])
    param_out = np.zeros(shape=[height, row_numel])
T
wip  
typhoonzero 已提交
329

Q
Qiao Longfei 已提交
330
    def update_row(row_id, update_value):
331 332 333 334 335 336
        moment1_out[row_id] = (
            beta1 * moment1[row_id] + (1 - beta1) * update_value
        )
        moment2_out[row_id] = beta2 * moment2[row_id] + (1 - beta2) * np.square(
            update_value
        )
T
wip  
typhoonzero 已提交
337
        lr_t = lr * np.sqrt(1 - beta2_pow) / (1 - beta1_pow)
338
        param_out[row_id] = param[row_id] - lr_t * (
339 340
            moment1_out[row_id] / (np.sqrt(moment2_out[row_id]) + epsilon)
        )
Q
Qiao Longfei 已提交
341 342 343 344 345 346 347 348 349 350 351

    if lazy_mode:
        for idx, row_id in enumerate(rows):
            update_row(row_id, np_grad[idx])
    else:
        for row_id in range(param_out.shape[0]):
            update_value = np.zeros(np_grad[0].shape).astype("float32")
            if row_id in rows:
                update_value = np_grad[rows.index(row_id)]
            update_row(row_id, update_value)

T
wip  
typhoonzero 已提交
352 353 354 355
    return param_out, moment1_out, moment2_out


class TestSparseAdamOp(unittest.TestCase):
Q
Qiao Longfei 已提交
356
    def setup(self, scope, place, lazy_mode):
T
wip  
typhoonzero 已提交
357 358 359
        beta1 = 0.78
        beta2 = 0.836
        epsilon = 1e-4
A
Aurelius84 已提交
360 361
        beta1_pow = np.array([beta1**10]).astype("float32")
        beta2_pow = np.array([beta2**10]).astype("float32")
T
wip  
typhoonzero 已提交
362 363 364

        height = 10
        rows = [0, 4, 7]
T
typhoonzero 已提交
365
        self.rows = rows
T
wip  
typhoonzero 已提交
366
        row_numel = 12
T
typhoonzero 已提交
367
        self.row_numel = row_numel
T
wip  
typhoonzero 已提交
368
        self.dense_inputs = {
Q
Qiao Longfei 已提交
369 370 371
            "Param": np.full((height, row_numel), 5.0).astype("float32"),
            "Moment1": np.full((height, row_numel), 5.0).astype("float32"),
            "Moment2": np.full((height, row_numel), 5.0).astype("float32"),
A
Aurelius84 已提交
372 373
            'Beta1Pow': beta1_pow,
            'Beta2Pow': beta2_pow,
374
            "LearningRate": np.full((1), 2.0).astype("float32"),
T
wip  
typhoonzero 已提交
375
        }
Q
Qiao Longfei 已提交
376
        self.init_output = np.full((height, row_numel), 0.0).astype("float32")
377 378 379 380
        self.attrs = {
            'epsilon': epsilon,
            'beta1': beta1,
            'beta2': beta2,
381
            'min_row_size_to_use_multithread': 2,
382
        }
T
wip  
typhoonzero 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395

        grad_selected_rows = scope.var('Grad').get_selected_rows()
        grad_selected_rows.set_height(height)
        grad_selected_rows.set_rows(rows)
        np_array = np.ones((len(rows), row_numel)).astype("float32")
        np_array[0, 0] = 2.0
        np_array[2, 8] = 4.0

        grad_tensor = grad_selected_rows.get_tensor()
        grad_tensor.set(np_array, place)

        self.sparse_inputs = ["Grad"]

396 397 398 399 400 401 402 403 404
        param_out, mom1, mom2 = adam_step_sparse(
            self.dense_inputs,
            self.attrs,
            height,
            rows,
            row_numel,
            np_array,
            lazy_mode,
        )
T
wip  
typhoonzero 已提交
405
        self.outputs = {
T
typhoonzero 已提交
406
            "ParamOut": param_out,
T
wip  
typhoonzero 已提交
407
            "Moment1Out": mom1,
A
Aurelius84 已提交
408 409
            "Moment2Out": mom2,
            'Beta1PowOut': beta1_pow * beta1,
410
            'Beta2PowOut': beta2_pow * beta2,
T
wip  
typhoonzero 已提交
411 412
        }

Q
Qiao Longfei 已提交
413
    def check_with_place(self, place, lazy_mode):
T
wip  
typhoonzero 已提交
414
        scope = core.Scope()
Q
Qiao Longfei 已提交
415
        self.setup(scope, place, lazy_mode)
T
wip  
typhoonzero 已提交
416 417

        op_args = dict()
Q
Qiao Longfei 已提交
418
        op_args['lazy_mode'] = lazy_mode
419
        for key, np_array in self.dense_inputs.items():
T
wip  
typhoonzero 已提交
420 421 422 423 424
            var = scope.var(key).get_tensor()
            var.set(np_array, place)
            op_args[key] = key
        for s in self.sparse_inputs:
            op_args[s] = s
T
typhoonzero 已提交
425 426
        for s in self.outputs:
            var = scope.var(s).get_tensor()
Q
Qiao Longfei 已提交
427
            var.set(self.init_output, place)
T
typhoonzero 已提交
428
            op_args[s] = s
T
wip  
typhoonzero 已提交
429 430 431 432
        for k in self.attrs:
            op_args[k] = self.attrs[k]

        # create and run sgd operator
T
typhoonzero 已提交
433 434
        adam_op = Operator("adam", **op_args)
        adam_op.run(scope, place)
T
wip  
typhoonzero 已提交
435

436
        for key, np_array in self.outputs.items():
T
wip  
typhoonzero 已提交
437 438
            out_var = scope.var(key).get_tensor()
            actual = np.array(out_var)
T
typhoonzero 已提交
439 440
            actual = actual.reshape([actual.size])
            np_array = np_array.reshape([np_array.size])
Q
Qiao Longfei 已提交
441 442 443

            for i in range(np_array.size):
                self.assertLess((actual[i] - np_array[i]), 0.00001)
T
wip  
typhoonzero 已提交
444

Q
Qiao Longfei 已提交
445
    def test_sparse_adam(self):
T
wip  
typhoonzero 已提交
446
        places = [core.CPUPlace()]
447
        if core.is_compiled_with_cuda():
T
wip  
typhoonzero 已提交
448 449
            places.append(core.CUDAPlace(0))
        for place in places:
Q
Qiao Longfei 已提交
450 451
            for lazy_mode in (True, False):
                self.check_with_place(place, lazy_mode)
T
wip  
typhoonzero 已提交
452 453


454 455
class TestAdamOpBetaVariable(OpTest):
    def setUp(self):
456
        '''Test Adam Op with beta as Variable'''
457
        self.op_type = "adam"
姜永久 已提交
458 459
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")
        beta1 = 0.85
        beta2 = 0.95

        learning_rate = 0.001
        epsilon = 1e-8
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
            "Beta1Tensor": np.array([beta1]).astype("float32"),
            "Beta2Tensor": np.array([beta2]).astype("float32"),
        }

        attributes = {'epsilon': epsilon}

487
        param_out, moment1_out, moment2_out = adam_step(self.inputs, attributes)
488 489 490 491

        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
A
Aurelius84 已提交
492 493
            'ParamOut': param_out,
            'Beta1PowOut': np.array([beta1_pow]).astype("float32") * beta1,
494
            'Beta2PowOut': np.array([beta2_pow]).astype("float32") * beta2,
495 496 497 498 499 500
        }

    def test_check_output(self):
        self.check_output()


501 502
class TestAdamOpBetaEpsilonVariable(OpTest):
    def setUp(self):
503
        '''Test Adam Op with beta/epsilon as Variable'''
504
        self.op_type = "adam"
姜永久 已提交
505 506
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")
        beta1 = 0.85
        beta2 = 0.95

        learning_rate = 0.001
        epsilon = 1e-8
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
            "Beta1Tensor": np.array([beta1]).astype("float32"),
            "Beta2Tensor": np.array([beta2]).astype("float32"),
            "EpsilonTensor": np.array([epsilon]).astype("float32"),
        }

        attributes = {'epsilon': epsilon}

535
        param_out, moment1_out, moment2_out = adam_step(self.inputs, attributes)
536 537 538 539 540 541

        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
            'ParamOut': param_out,
            'Beta1PowOut': np.array([beta1_pow]).astype("float32") * beta1,
542
            'Beta2PowOut': np.array([beta2_pow]).astype("float32") * beta2,
543 544 545 546 547 548
        }

    def test_check_output(self):
        self.check_output()


549 550
class TestAdamOpWithGlobalBetaPow(OpTest):
    def setUp(self):
551
        '''Test Adam Op with global_beta_pow'''
552
        self.op_type = "adam"
姜永久 已提交
553 554
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")
        beta1 = 0.85
        beta2 = 0.95

        learning_rate = 0.001
        epsilon = 1e-8
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
            "Beta1Tensor": np.array([beta1]).astype("float32"),
            "Beta2Tensor": np.array([beta2]).astype("float32"),
            "EpsilonTensor": np.array([epsilon]).astype("float32"),
        }

        attributes = {'epsilon': epsilon}

583
        param_out, moment1_out, moment2_out = adam_step(self.inputs, attributes)
584 585 586 587 588 589 590 591 592

        self.attrs = {'use_global_beta_pow': True}

        # use_global_beta_pow=True, Beta1PowOut and Beta2PowOut are empty.
        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
            'ParamOut': param_out,
            'Beta1PowOut': np.array([]),
593
            'Beta2PowOut': np.array([]),
594 595 596 597 598 599
        }

    def test_check_output(self):
        self.check_output()


600 601
class TestAdamOpWithSkipUpdate(OpTest):
    def setUp(self):
602
        '''Test Adam Op with global_beta_pow'''
603
        self.op_type = "adam"
姜永久 已提交
604 605
        self.python_api = adam_wrapper
        self.python_out_sig = ['Out']
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The second moment is positive
        moment2 = np.random.random((102, 105)).astype("float32")
        beta1 = 0.85
        beta2 = 0.95

        learning_rate = 0.001
        epsilon = 1e-8
        beta1_pow = beta1**10
        beta2_pow = beta2**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
            'Beta2Pow': np.array([beta2_pow]).astype("float32"),
            "Beta1Tensor": np.array([beta1]).astype("float32"),
            "Beta2Tensor": np.array([beta2]).astype("float32"),
            "EpsilonTensor": np.array([epsilon]).astype("float32"),
            "SkipUpdate": np.array([True]).astype("bool"),
        }

        attributes = {'epsilon': epsilon}

        self.attrs = {'use_global_beta_pow': True}

        # use_global_beta_pow=True, Beta1PowOut and Beta2PowOut are empty.
        self.outputs = {
            'Moment1Out': moment1,
            'Moment2Out': moment2,
            'ParamOut': param,
            'Beta1PowOut': self.inputs['Beta1Pow'],
            'Beta2PowOut': self.inputs['Beta2Pow'],
        }

    def test_check_output(self):
        self.check_output()


M
MRXLT 已提交
650 651 652
class TestAdamOpV2(unittest.TestCase):
    def test_adam_op(self):
        place = fluid.CPUPlace()
653
        shape = [2, 3, 8, 8]
M
MRXLT 已提交
654 655 656 657 658 659
        exe = fluid.Executor(place)
        train_prog = fluid.Program()
        startup = fluid.Program()
        with fluid.program_guard(train_prog, startup):
            with fluid.unique_name.guard():
                data = fluid.data(name="data", shape=shape)
660
                conv = paddle.static.nn.conv2d(data, 8, 3)
661
                loss = paddle.mean(conv)
M
MRXLT 已提交
662

663
                beta1 = paddle.static.create_global_var(
664 665
                    shape=[1], value=0.85, dtype='float32', persistable=True
                )
666
                beta2 = paddle.static.create_global_var(
667 668
                    shape=[1], value=0.95, dtype='float32', persistable=True
                )
M
MRXLT 已提交
669
                betas = [beta1, beta2]
670 671 672 673 674 675 676
                opt = paddle.optimizer.Adam(
                    learning_rate=1e-5,
                    beta1=beta1,
                    beta2=beta2,
                    weight_decay=0.01,
                    epsilon=1e-8,
                )
M
MRXLT 已提交
677 678 679 680 681 682 683 684 685 686 687
                opt.minimize(loss)

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

    def test_adam_op_dygraph(self):
        paddle.disable_static()
        value = np.arange(26).reshape(2, 13).astype("float32")
        a = fluid.dygraph.to_variable(value)
688
        linear = paddle.nn.Linear(13, 5)
M
MRXLT 已提交
689

690 691 692
        adam = paddle.optimizer.Adam(
            learning_rate=0.01, parameters=linear.parameters()
        )
M
MRXLT 已提交
693 694 695 696
        out = linear(a)
        out.backward()
        adam.step()
        adam.clear_gradients()
697
        paddle.enable_static()
M
MRXLT 已提交
698 699 700 701

    def test_adam_op_with_state_dict(self):

        paddle.disable_static()
T
tangwei12 已提交
702
        emb = paddle.nn.Embedding(10, 10)
M
MRXLT 已提交
703 704 705 706 707

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

708
        # learning_rate is LRScheduler
709
        learning_rate = paddle.optimizer.lr.CosineAnnealingDecay(
710 711
            learning_rate=0.1, T_max=10
        )
M
MRXLT 已提交
712 713 714
        adam = paddle.optimizer.Adam(
            learning_rate=learning_rate,
            weight_decay=fluid.regularizer.L2Decay(0.001),
715 716
            parameters=emb.parameters(),
        )
M
MRXLT 已提交
717 718 719 720
        lr = adam.get_lr()
        state_dict = adam.state_dict()
        adam.set_state_dict(state_dict)

721
        # leanrning_rate is Tensor
M
MRXLT 已提交
722 723 724
        with self.assertRaises(TypeError):
            learning_rate = np.array([0.01]).astype("float32")
            learning_rate = paddle.to_tensor(learning_rate)
725 726 727
            adam = paddle.optimizer.Adam(
                learning_rate=learning_rate, parameters=emb.parameters()
            )
M
MRXLT 已提交
728 729

        params = adam.get_opti_var_name_list()
730
        assert params is not None
731
        paddle.enable_static()
M
MRXLT 已提交
732 733 734 735 736

    def test_adam_with_grad_clip(self):
        paddle.disable_static()
        value = np.arange(26).reshape(2, 13).astype("float32")
        a = fluid.dygraph.to_variable(value)
737
        linear = paddle.nn.Linear(13, 5)
738
        clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
739 740 741
        adam = paddle.optimizer.Adam(
            0.1, parameters=linear.parameters(), grad_clip=clip
        )
M
MRXLT 已提交
742 743 744 745
        out = linear(a)
        out.backward()
        adam.step()
        adam.clear_gradients()
746
        paddle.enable_static()
M
MRXLT 已提交
747 748 749 750 751 752 753 754 755

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

        lr = 0.01
        adam.set_lr(lr)
        cur_lr = adam.get_lr()
756
        assert lr == cur_lr
M
MRXLT 已提交
757
        with self.assertRaises(TypeError):
758
            lr_var = paddle.static.create_global_var(
759 760
                shape=[1], value=lr, dtype='float32'
            )
761
            adam.set_lr(lr_var)
762
        paddle.enable_static()
763

M
MRXLT 已提交
764 765 766 767
    def test_adam_op_invalid_input(self):
        paddle.disable_static()
        linear = paddle.nn.Linear(10, 10)
        with self.assertRaises(ValueError):
768 769 770
            adam = paddle.optimizer.Adam(
                0.1, beta1=-1, parameters=linear.parameters()
            )
M
MRXLT 已提交
771
        with self.assertRaises(ValueError):
772 773 774
            adam = paddle.optimizer.Adam(
                0.1, beta2=-1, parameters=linear.parameters()
            )
M
MRXLT 已提交
775
        with self.assertRaises(ValueError):
776 777 778
            adam = paddle.optimizer.Adam(
                0.1, epsilon=-1, parameters=linear.parameters()
            )
779
        paddle.enable_static()
M
MRXLT 已提交
780

781 782 783 784 785 786
    def test_adam_op_with_sparse_input_and_weight_decay(self):

        paddle.disable_static()
        x_data = np.arange(0, 10).reshape((10, 1)).astype(np.int64)
        x = paddle.to_tensor(x_data, stop_gradient=False)
        emb = paddle.nn.Embedding(10, 10, sparse=True)
787 788 789
        adam = paddle.optimizer.Adam(
            0.001, parameters=emb.parameters(), weight_decay=0.01
        )
790 791 792 793 794

        with self.assertRaises(RuntimeError):
            out = emb(x)
            out.backward()
            adam.step()
795
        paddle.enable_static()
796

797

798
class TestAdamOptimizer(unittest.TestCase):
799 800 801 802 803 804 805 806
    def _test(
        self,
        place,
        use_tensor=True,
        use_fluid_api=True,
        use_global_beta_pow=False,
        flatten_param_grads=False,
    ):
807 808 809 810 811 812 813
        paddle.enable_static()
        main_prog = paddle.static.Program()
        startup_prog = paddle.static.Program()
        SEED = 2021
        paddle.seed(SEED)
        np.random.seed(SEED)

814 815 816 817 818
        a_np = np.random.random(size=(2, 2)).astype('float32')
        b_np = np.random.random(size=(2, 2)).astype('float32')
        label_np = np.random.randint(2, size=(2, 1)).astype('int64')
        weight_attr1 = paddle.ParamAttr(
            name="weight1",
819
            initializer=paddle.nn.initializer.Constant(value=1.0),
820 821
            trainable=True,
        )
822 823
        weight_attr2 = paddle.ParamAttr(
            name="weight2",
824
            initializer=paddle.nn.initializer.Constant(value=2.0),
825 826
            trainable=True,
        )
827
        clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
828 829

        with paddle.static.program_guard(main_prog, startup_prog):
830 831 832
            with paddle.utils.unique_name.guard():
                a = paddle.static.data(name="a", shape=[2, 2], dtype='float32')
                b = paddle.static.data(name="b", shape=[2, 2], dtype='float32')
833 834 835
                label = paddle.static.data(
                    name="label", shape=[2, 1], dtype='int64'
                )
836 837 838 839

                sum = paddle.add(a, b)
                z = paddle.pow(sum, 2.0)

C
Charles-hit 已提交
840 841 842 843 844 845 846 847
                fc_1 = paddle.static.nn.fc(
                    x=z, size=2, weight_attr=weight_attr1
                )
                prediction = paddle.static.nn.fc(
                    x=fc_1,
                    size=2,
                    weight_attr=weight_attr2,
                    activation='softmax',
848
                )
849

850 851 852 853 854 855
                cost = paddle.nn.functional.cross_entropy(
                    input=prediction,
                    label=label,
                    reduction='none',
                    use_softmax=False,
                )
856
                loss = paddle.mean(cost)
857 858 859 860
                beta1_init = 0.9
                beta2_init = 0.999
                epsilon_init = 1e-8
                if use_tensor:
861
                    beta1 = paddle.static.create_global_var(
862 863 864 865
                        shape=[1],
                        value=float(beta1_init),
                        dtype='float32',
                        persistable=True,
866 867
                        name="beta1",
                    )
868
                    beta2 = paddle.static.create_global_var(
869 870 871 872
                        shape=[1],
                        value=float(beta2_init),
                        dtype='float32',
                        persistable=True,
873 874
                        name="beta2",
                    )
875
                    epsilon = paddle.static.create_global_var(
876 877 878 879
                        shape=[1],
                        value=float(epsilon_init),
                        dtype='float32',
                        persistable=True,
880 881
                        name="epsilon",
                    )
882 883 884 885 886 887 888 889 890
                    if use_fluid_api:
                        adam = fluid.optimizer.Adam(
                            learning_rate=0.01,
                            beta1=beta1,
                            beta2=beta2,
                            epsilon=epsilon,
                            use_global_beta_pow=use_global_beta_pow,
                            flatten_param_grads=flatten_param_grads,
                            align_size=256,
891 892
                            grad_clip=clip,
                        )
893
                    else:
894 895 896 897 898 899 900
                        adam = paddle.optimizer.Adam(
                            learning_rate=0.01,
                            beta1=beta1,
                            beta2=beta2,
                            epsilon=epsilon,
                            grad_clip=clip,
                        )
901
                else:
902 903 904 905 906 907 908 909 910
                    if use_fluid_api:
                        adam = fluid.optimizer.Adam(
                            learning_rate=0.01,
                            beta1=beta1_init,
                            beta2=beta2_init,
                            epsilon=epsilon_init,
                            use_global_beta_pow=use_global_beta_pow,
                            flatten_param_grads=flatten_param_grads,
                            align_size=256,
911 912
                            grad_clip=clip,
                        )
913
                    else:
914 915 916 917 918 919 920
                        adam = fluid.optimizer.Adam(
                            learning_rate=0.01,
                            beta1=beta1_init,
                            beta2=beta2_init,
                            epsilon=epsilon_init,
                            grad_clip=clip,
                        )
921 922 923 924 925 926 927 928 929 930

                adam.minimize(loss)

        scope = fluid.Scope()
        with fluid.scope_guard(scope):
            exe = paddle.static.Executor(place)
            exe.run(startup_prog)

            print("Start run on {}".format(place))
            for epoch in range(10):
931 932 933 934 935 936 937 938 939 940
                pred_res, loss_res = exe.run(
                    main_prog,
                    feed={"a": a_np, "b": b_np, "label": label_np},
                    fetch_list=[prediction, loss],
                )
                print(
                    "Epoch {} | Prediction[0]: {}, Loss: {}".format(
                        epoch, pred_res[0], loss_res
                    )
                )
941 942
            paddle.disable_static()
            return pred_res, loss_res
943 944 945 946 947 948 949

    def _test_with_place(self, place):
        preds = []
        losses = []

        for use_tensor in [True, False]:
            for use_fluid_api in [True, False]:
950
                for use_global_beta_pow in [True, False]:
951
                    for flatten_param_grads in [True, False]:
952 953 954 955 956 957 958
                        pred, loss = self._test(
                            place,
                            use_tensor,
                            use_fluid_api,
                            use_global_beta_pow,
                            flatten_param_grads,
                        )
959 960
                        preds.append(pred)
                        losses.append(loss)
961
        for pred in preds:
962
            np.testing.assert_allclose(pred, preds[0], rtol=1e-05)
963
        for loss in losses:
964
            np.testing.assert_allclose(loss, losses[0], rtol=1e-05)
965 966 967 968 969 970 971

    def test_adam_api(self):
        # NOTE(zhiqiu): cpu and gpu has different seed, so should compare separatly.
        self._test_with_place(paddle.CPUPlace())
        if core.is_compiled_with_cuda():
            self._test_with_place(paddle.CUDAPlace(0))

972 973 974 975 976 977
    def test_adam_flatten_param_grads_with_regularizer(self):
        # flatten_param_grads + regularizer is not supported yet.
        paddle.enable_static()
        main = fluid.Program()
        weight_attr = paddle.ParamAttr(
            name="weight1",
978
            initializer=paddle.nn.initializer.Constant(value=1.0),
979
            regularizer=fluid.regularizer.L1DecayRegularizer(
980 981 982 983
                regularization_coeff=0.1
            ),
            trainable=True,
        )
984 985 986
        with fluid.program_guard(main):
            x = fluid.data(name='x', shape=[None, 13], dtype='float32')
            y = fluid.data(name='y', shape=[None, 1], dtype='float32')
C
Charles-hit 已提交
987
            y_predict = paddle.static.nn.fc(x, size=1, weight_attr=weight_attr)
988 989 990
            cost = paddle.nn.functional.square_error_cost(
                input=y_predict, label=y
            )
991
            avg_cost = paddle.mean(cost)
992

993 994 995
            adam = fluid.optimizer.AdamOptimizer(
                0.01, flatten_param_grads=True, align_size=256
            )
996 997 998 999 1000
            adam.minimize(avg_cost)
            paddle.disable_static()

            self.assertEqual(adam._flatten_param_grads, False)

1001 1002 1003 1004 1005 1006 1007 1008 1009
    def test_adam_exception(self):
        paddle.enable_static()
        a = paddle.static.data(name="a", shape=[32, 32], dtype='float32')
        b = paddle.static.data(name="b", shape=[32, 32], dtype='float32')
        label = paddle.static.data(name="label", shape=[32, 1], dtype='int64')

        sum = paddle.add(a, b)
        z = paddle.pow(sum, 2.0)

C
Charles-hit 已提交
1010 1011
        fc_1 = paddle.static.nn.fc(x=z, size=128)
        prediction = paddle.static.nn.fc(x=fc_1, size=2, activation='softmax')
1012

1013 1014 1015
        cost = paddle.nn.functional.cross_entropy(
            input=prediction, label=label, reduction='none', use_softmax=False
        )
1016
        loss = paddle.mean(cost)
1017 1018 1019
        adam = fluid.optimizer.Adam(use_global_beta_pow=True)
        adam.minimize(loss)
        self.assertRaises(Exception, adam._get_global_accumulator, 'tmp')
1020 1021 1022
        adam._add_global_accumulator(
            'tmp', type=core.VarDesc.VarType.LOD_TENSOR
        )
1023
        adam._get_global_accumulator('tmp')
1024 1025 1026 1027 1028 1029
        self.assertRaises(
            Exception,
            adam._add_global_accumulator,
            adam._beta1_pow_acc_str,
            type=core.VarDesc.VarType.LOD_TENSOR,
        )
1030 1031 1032 1033 1034 1035 1036 1037
        paddle.disable_static()

    def test_adam_save_load(self):
        paddle.disable_static()
        a = paddle.rand([4, 10])
        linear = paddle.nn.Linear(10, 10)
        b = linear(a)
        state_dict = linear.state_dict()
1038
        paddle.save(state_dict, "paddle_dy.pdparams")
1039

1040 1041 1042 1043 1044 1045 1046 1047
        scheduler = paddle.optimizer.lr.NoamDecay(
            d_model=0.01, warmup_steps=100, verbose=True
        )
        adam = paddle.fluid.optimizer.Adam(
            learning_rate=scheduler,
            parameter_list=linear.parameters(),
            use_global_beta_pow=True,
        )
1048 1049
        adam.minimize(b)
        state_dict = adam.state_dict()
1050 1051 1052
        paddle.save(state_dict, "paddle_dy.pdopt")
        para_state_dict = paddle.load("paddle_dy.pdparams")
        opt_state_dict = paddle.load("paddle_dy.pdopt")
1053
        adam.set_state_dict(opt_state_dict)
1054 1055 1056

        paddle.enable_static()

1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    def test_adam_save_load_error(self):
        paddle.disable_static()

        def get_opt(dtype, shape):
            with paddle.utils.unique_name.guard():
                paddle.set_default_dtype(dtype)
                a = paddle.rand([4, 10])
                linear = paddle.nn.Linear(10, 10)
                b = linear(a)
                state_dict = linear.state_dict()
1067
                paddle.save(state_dict, "paddle_dy.pdparams")
1068

1069 1070 1071
                scheduler = paddle.optimizer.lr.NoamDecay(
                    d_model=0.01, warmup_steps=100, verbose=True
                )
1072 1073 1074
                adam = paddle.fluid.optimizer.Adam(
                    learning_rate=scheduler,
                    parameter_list=linear.parameters(),
1075 1076
                    use_global_beta_pow=True,
                )
1077 1078 1079 1080 1081 1082
                adam.minimize(b)
                return adam

        adam = get_opt('float32', [10, 10])

        state_dict = adam.state_dict()
1083 1084 1085
        paddle.save(state_dict, "paddle_dy.pdopt")
        para_state_dict = paddle.load("paddle_dy.pdparams")
        opt_state_dict = paddle.load("paddle_dy.pdopt")
1086 1087 1088 1089 1090 1091
        adam.set_state_dict(opt_state_dict)

        adam2 = get_opt('float64', [10, 10])  # dtype not match
        self.assertRaises(AssertionError, adam2.set_state_dict, opt_state_dict)

        adam3 = get_opt('float32', [10, 10])  # shape not match
1092 1093 1094
        opt_state_dict['beta1_pow_acc_0'] = np.array(
            [0.9, 0.9], dtype='float32'
        )
1095 1096 1097
        self.assertRaises(AssertionError, adam3.set_state_dict, opt_state_dict)
        paddle.enable_static()

1098

1099 1100 1101 1102 1103 1104 1105 1106
class TestAdamOpV2Group(TestAdamOpV2):
    def test_adam_op(self):
        paddle.disable_static()
        value = np.arange(26).reshape(2, 13).astype("float32")
        a = paddle.to_tensor(value)
        linear_1 = paddle.nn.Linear(13, 5)
        linear_2 = paddle.nn.Linear(5, 3)
        # This can be any optimizer supported by dygraph.
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
        adam = paddle.optimizer.Adam(
            learning_rate=0.01,
            parameters=[
                {'params': linear_1.parameters()},
                {
                    'params': linear_2.parameters(),
                    'weight_decay': 0.001,
                    'beta1': 0.1,
                    'beta2': 0.99,
                },
            ],
            weight_decay=0.1,
        )
1120 1121 1122 1123 1124 1125 1126
        out = linear_1(a)
        out = linear_2(out)
        out.backward()
        adam.step()
        adam.clear_gradients()


Z
zhangbo9674 已提交
1127
class TestMultiTensorAdam(unittest.TestCase):
1128 1129 1130 1131 1132 1133 1134 1135
    def _adam_optimize_dygraph(
        self,
        place,
        use_param_attr=False,
        use_param_group=False,
        use_amp=False,
        use_multi_tensor=False,
    ):
Z
zhangbo9674 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144
        paddle.disable_static()
        paddle.seed(10)
        paddle.set_device(place)

        input = paddle.randn((5, 5))

        weight_attr = paddle.ParamAttr(
            learning_rate=0.5,
            regularizer=paddle.regularizer.L2Decay(1.0),
1145 1146
            trainable=True,
        )
Z
zhangbo9674 已提交
1147
        if use_param_attr:
1148
            model = paddle.nn.Linear(5, 5, weight_attr=weight_attr)
Z
zhangbo9674 已提交
1149 1150 1151 1152
        else:
            model = paddle.nn.Linear(5, 5)

        if not use_param_group:
1153 1154 1155 1156 1157
            optimizer = paddle.optimizer.Adam(
                parameters=model.parameters(),
                use_multi_tensor=use_multi_tensor,
                multi_precision=use_amp,
            )
Z
zhangbo9674 已提交
1158
        else:
1159 1160
            parameters = list(model.parameters())
            param_num = len(parameters)
1161 1162 1163
            optimizer = paddle.optimizer.Adam(
                parameters=[
                    {
1164
                        'params': parameters[: int(param_num / 2)],
1165 1166 1167
                        'weight_decay': 0.001,
                        'beta1': 0.1,
                        'beta2': 0.99,
1168 1169 1170 1171 1172 1173 1174
                    },
                    {
                        'params': parameters[int(param_num / 2) :],
                        'weight_decay': 0.001,
                        'beta1': 0.1,
                        'beta2': 0.99,
                    },
1175 1176 1177 1178
                ],
                use_multi_tensor=use_multi_tensor,
                multi_precision=use_amp,
            )
Z
zhangbo9674 已提交
1179 1180

        for idx in range(2):
1181
            if place == 'gpu' and use_amp:
Z
zhangbo9674 已提交
1182 1183 1184
                model = paddle.amp.decorate(models=model, level='O2')
                scaler = paddle.amp.GradScaler(init_loss_scaling=1024)

1185
            if place == 'gpu' and use_amp:
Z
zhangbo9674 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
                with paddle.amp.auto_cast(level='O2'):
                    output = model(input)
                    loss = paddle.mean(output)
                scaled = scaler.scale(loss)
                scaled.backward()
                scaler.step(optimizer)
                optimizer.clear_grad()
            else:
                output = model(input)
                loss = paddle.mean(output)
                loss.backward()
                optimizer.step()
                optimizer.clear_grad()

        return output, model.parameters()

1202 1203 1204
    def _adam_optimize_static(
        self, place, use_amp=False, use_multi_tensor=False
    ):
Z
zhangbo9674 已提交
1205 1206 1207 1208 1209 1210 1211 1212
        paddle.enable_static()
        paddle.seed(10)
        np.random.seed(10)
        if place == 'cpu':
            use_amp = False
        exe = paddle.static.Executor(place=place)
        train_program = paddle.static.Program()
        startup_program = paddle.static.Program()
1213 1214 1215
        optimizer = paddle.optimizer.Adam(
            multi_precision=use_amp, use_multi_tensor=use_multi_tensor
        )
Z
zhangbo9674 已提交
1216 1217 1218 1219 1220 1221
        if use_amp:
            optimizer = paddle.static.amp.decorate(
                optimizer,
                init_loss_scaling=128.0,
                use_dynamic_loss_scaling=True,
                use_pure_fp16=True,
1222 1223
                use_fp16_guard=False,
            )
Z
zhangbo9674 已提交
1224 1225
        with paddle.static.program_guard(train_program, startup_program):
            if use_amp:
1226 1227 1228
                data = paddle.static.data(
                    shape=[2, 2], name='X', dtype='float16'
                )
Z
zhangbo9674 已提交
1229
            else:
1230 1231 1232
                data = paddle.static.data(
                    shape=[2, 2], name='X', dtype='float32'
                )
Z
zhangbo9674 已提交
1233
            hidden = paddle.static.nn.fc(x=data, size=10)
1234
            loss = paddle.mean(hidden)
Z
zhangbo9674 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243
            optimizer.minimize(loss)
        exe.run(startup_program)
        if use_amp:
            optimizer.amp_init(place=place, scope=paddle.static.global_scope())
            x = np.random.random(size=(2, 2)).astype('float16')
        else:
            x = np.random.random(size=(2, 2)).astype('float32')
        out = []
        for idx in range(5):
1244 1245 1246
            (loss_data,) = exe.run(
                train_program, feed={"X": x}, fetch_list=[loss.name]
            )
Z
zhangbo9674 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
            out.append(loss_data)
        return out

    def _get_places(self):
        places = ['cpu']
        if paddle.is_compiled_with_cuda():
            places.append('gpu')
        return places

    def _check_with_place_amp(self, place, use_amp):
        # test dygraph mode
        output_dygraph1, params_dygraph1 = self._adam_optimize_dygraph(
1259 1260
            place=place, use_amp=use_amp, use_multi_tensor=True
        )
Z
zhangbo9674 已提交
1261
        output_dygraph2, params_dygraph2 = self._adam_optimize_dygraph(
1262 1263
            place=place, use_amp=use_amp, use_multi_tensor=False
        )
1264
        np.testing.assert_allclose(output_dygraph1, output_dygraph2, rtol=1e-05)
Z
zhangbo9674 已提交
1265
        for idx in range(len(params_dygraph1)):
1266 1267 1268
            np.testing.assert_allclose(
                params_dygraph1[idx], params_dygraph2[idx], rtol=1e-05
            )
1269
        # test static graph mode
1270 1271 1272 1273 1274 1275
        output_static1 = self._adam_optimize_static(
            place=place, use_amp=use_amp, use_multi_tensor=True
        )
        output_static2 = self._adam_optimize_static(
            place=place, use_amp=use_amp, use_multi_tensor=False
        )
Z
zhangbo9674 已提交
1276
        for idx in range(len(output_static1)):
1277 1278 1279
            np.testing.assert_allclose(
                output_static1[idx], output_static2[idx], rtol=1e-05
            )
Z
zhangbo9674 已提交
1280 1281

    def _check_with_param_arrt(self, place, use_amp):
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
        output1, params1 = self._adam_optimize_dygraph(
            place=place,
            use_amp=use_amp,
            use_param_attr=True,
            use_multi_tensor=True,
        )
        output2, params2 = self._adam_optimize_dygraph(
            place=place,
            use_amp=use_amp,
            use_param_attr=True,
            use_multi_tensor=False,
        )
Z
zhangbo9674 已提交
1294

1295
        np.testing.assert_allclose(output1, output2, rtol=1e-05)
Z
zhangbo9674 已提交
1296
        for idx in range(len(params1)):
1297
            np.testing.assert_allclose(params1[idx], params2[idx], rtol=1e-05)
Z
zhangbo9674 已提交
1298 1299

    def _check_with_param_group(self, place, use_amp):
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
        output1, params1 = self._adam_optimize_dygraph(
            place=place,
            use_amp=use_amp,
            use_param_group=True,
            use_multi_tensor=True,
        )
        output2, params2 = self._adam_optimize_dygraph(
            place=place,
            use_amp=use_amp,
            use_param_group=True,
            use_multi_tensor=False,
        )
Z
zhangbo9674 已提交
1312

1313
        np.testing.assert_allclose(output1, output2, rtol=1e-05)
Z
zhangbo9674 已提交
1314
        for idx in range(len(params1)):
1315
            np.testing.assert_allclose(params1[idx], params2[idx], rtol=1e-05)
Z
zhangbo9674 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325

    def test_main(self):
        for place in self._get_places():
            use_amp_list = [True, False]
            for use_amp in use_amp_list:
                self._check_with_place_amp(place, use_amp)
                self._check_with_param_arrt(place, use_amp)
                self._check_with_param_group(place, use_amp)


1326
if __name__ == "__main__":
H
hong 已提交
1327
    paddle.enable_static()
1328
    unittest.main()