test_adamax_op.py 6.6 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 16
import unittest
import numpy as np
17
from op_test import OpTest
18 19 20


class TestAdamaxOp1(OpTest):
21

22 23 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
    def setUp(self):
        '''Test Adamax Operator with supplied attributes
        '''
        self.op_type = "adamax"
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The infinity norm is positive
        inf_norm = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.002
        beta1 = 0.78
        beta2 = 0.899
        epsilon = 1e-5
        beta1_pow = beta1**10

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment': moment,
            'InfNorm': inf_norm,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32")
        }

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

49 50
        param_out, moment_out, inf_norm_out = adamax_step(
            self.inputs, self.attrs)
51 52 53 54

        self.outputs = {
            'ParamOut': param_out,
            'MomentOut': moment_out,
55
            'InfNormOut': inf_norm_out
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        }

    def test_check_output(self):
        self.check_output()


class TestAdamaxOp2(OpTest):
    '''Test Adamax Operator with default attributes
    '''

    def setUp(self):
        self.op_type = "adamax"
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The infinity norm is positive
        inf_norm = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.002
        beta1 = 0.9
        beta2 = 0.999
        epsilon = 1e-8
        beta1_pow = beta1**8

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment': moment,
            'InfNorm': inf_norm,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32")
        }

        attrs = {'beta1': beta1, 'beta2': beta2, 'epsilon': epsilon}
90
        param_out, moment_out, inf_norm_out = adamax_step(self.inputs, attrs)
91 92 93 94

        self.outputs = {
            'ParamOut': param_out,
            'MomentOut': moment_out,
95
            'InfNormOut': inf_norm_out
96 97 98 99 100 101 102
        }

    def test_check_output(self):
        self.check_output()


class TestAdamaxOpMultipleSteps(OpTest):
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    def setUp(self):
        '''Test Adamax Operator with supplied attributes
        '''
        self.op_type = "adamax"
        self.num_steps = 10

        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        # The infinity norm is positive
        inf_norm = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.002
        beta1 = 0.8
        beta2 = 0.99
        epsilon = 1e-5
        beta1_pow = 1

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment': moment,
            'InfNorm': inf_norm,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32")
        }

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

    def test_check_output(self):
        for _ in range(self.num_steps):
135 136
            param_out, moment_out, inf_norm_out = adamax_step(
                self.inputs, self.attrs)
137 138 139 140

            self.outputs = {
                'ParamOut': param_out,
                'MomentOut': moment_out,
141
                'InfNormOut': inf_norm_out
142 143 144 145 146 147 148 149 150
            }

            # Verify output for this step
            self.check_output()

            # Output of this step becomes input for next step
            self.inputs['Param'] = param_out
            self.inputs['Moment'] = moment_out
            self.inputs['InfNorm'] = inf_norm_out
151 152 153

            # Update Beta1 Power accumulator for next step
            self.inputs['Beta1Pow'] *= self.attrs['beta1']
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

            # Randomize gradient for next step
            self.inputs['Grad'] = np.random.uniform(
                -1, 1, (102, 105)).astype("float32")


def adamax_step(inputs, attributes):
    '''
    Simulate one step of the adamax optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment, inf_norm and
    beta1 power accumulator
    '''
    param = inputs['Param']
    grad = inputs['Grad']
    moment = inputs['Moment']
    inf_norm = inputs['InfNorm']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']

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

    moment_out = beta1 * moment + (1 - beta1) * grad
    inf_norm_out = np.maximum(beta2 * inf_norm + epsilon, np.abs(grad))
181
    lr_t = (lr / (1 - beta1_pow))
182 183
    param_out = param - lr_t * np.divide(moment_out, inf_norm_out)

184
    return param_out, moment_out, inf_norm_out
185 186


M
MRXLT 已提交
187
class TestAdamaxOpV2(unittest.TestCase):
188

M
MRXLT 已提交
189 190 191 192 193
    def test_adamax_op_invalid_input(self):
        import paddle
        paddle.disable_static()
        linear = paddle.nn.Linear(10, 10)
        with self.assertRaises(ValueError):
194 195 196
            adam = paddle.optimizer.Adamax(0.1,
                                           beta1=-1,
                                           parameters=linear.parameters())
M
MRXLT 已提交
197
        with self.assertRaises(ValueError):
198 199 200
            adam = paddle.optimizer.Adamax(0.1,
                                           beta2=-1,
                                           parameters=linear.parameters())
M
MRXLT 已提交
201
        with self.assertRaises(ValueError):
202 203 204
            adam = paddle.optimizer.Adamax(0.1,
                                           epsilon=-1,
                                           parameters=linear.parameters())
M
MRXLT 已提交
205 206


207 208
if __name__ == "__main__":
    unittest.main()