test_adagrad_op.py 6.3 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 math
16
import unittest
17

18
import numpy as np
19
from eager_op_test import OpTest
20

H
hong 已提交
21
import paddle
22 23
import paddle.fluid.core as core
from paddle.fluid.op import Operator
24 25


26 27 28 29
def adamgrad_wrapper(param, grad, moment, learning_rate, epsilon):
    paddle._C_ops.adagrad_(param, grad, moment, learning_rate, epsilon)


K
Kexin Zhao 已提交
30
class TestAdagradOp1(OpTest):
31
    '''Test Adagrad operator with explicit attributes'''
K
Kexin Zhao 已提交
32

33 34
    def setUp(self):
        self.op_type = "adagrad"
35 36
        self.python_api = adamgrad_wrapper
        self.python_out_sig = ['out']
37 38 39
        param = np.random.random((123, 321)).astype("float32")
        grad = np.random.random((123, 321)).astype("float32")
        moment = np.zeros((123, 321)).astype("float32")
K
Kexin Zhao 已提交
40 41 42 43 44 45 46
        lr = 0.01
        epsilon = 1e-8

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment': moment,
47
            'LearningRate': np.array([lr]).astype("float32"),
K
Kexin Zhao 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61
        }

        self.attrs = {'epsilon': epsilon}

        moment_out = moment + grad * grad
        param_out = param - lr * grad / (np.sqrt(moment_out) + epsilon)

        self.outputs = {'ParamOut': param_out, 'MomentOut': moment_out}

    def test_check_output(self):
        self.check_output()


class TestAdagradOp2(OpTest):
62
    '''Test Adagrad operator with default attributes'''
63

K
Kexin Zhao 已提交
64 65
    def setUp(self):
        self.op_type = "adagrad"
66 67
        self.python_api = adamgrad_wrapper
        self.python_out_sig = ['out']
K
Kexin Zhao 已提交
68 69 70 71 72

        param = np.random.random((123, 321)).astype("float32")
        grad = np.random.random((123, 321)).astype("float32")
        moment = np.zeros((123, 321)).astype("float32")
        lr = 0.01
73 74
        epsilon = 1e-6

K
Kexin Zhao 已提交
75 76 77 78
        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment': moment,
79
            'LearningRate': np.array([lr]).astype("float32"),
K
Kexin Zhao 已提交
80
        }
81

K
Kexin Zhao 已提交
82
        self.attrs = {'epsilon': epsilon}
83 84

        moment_out = moment + grad * grad
85
        param_out = param - lr * grad / (np.sqrt(moment_out) + epsilon)
86

K
Kexin Zhao 已提交
87
        self.outputs = {'ParamOut': param_out, 'MomentOut': moment_out}
88 89 90 91 92

    def test_check_output(self):
        self.check_output()


Q
QI JUN 已提交
93 94 95 96
class TestSparseAdagradOp(unittest.TestCase):
    def check_with_place(self, place):
        scope = core.Scope()

97
        # create and initialize Grad Variable
Q
QI JUN 已提交
98 99 100 101 102 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
        height = 10
        rows = [0, 4, 7, 4]
        row_numel = 12

        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)

        # create and initialize Param Variable
        param = scope.var('Param').get_tensor()
        param_array = np.full((height, row_numel), 5.0).astype("float32")
        param.set(param_array, place)

        # create and initialize LeraningRate Variable
        lr = scope.var('LearningRate').get_tensor()
        lr_array = np.full((1), 2.0).astype("float32")
        lr.set(lr_array, place)

        # create and initialize moment Variable
        moment = scope.var('Moment').get_tensor()
        moment_np_array = np.full((height, row_numel), 2.0).astype("float32")
        moment.set(moment_np_array, place)

        # create and run sgd operator
128 129 130 131 132 133 134 135 136 137
        adagrad_op = Operator(
            "adagrad",
            Param='Param',
            Grad='Grad',
            ParamOut='Param',
            Moment='Moment',
            MomentOut='Moment',
            LearningRate='LearningRate',
            epsilon=2.0,
        )
Q
QI JUN 已提交
138

D
dzhwinter 已提交
139
        adagrad_op.run(scope, place)
Q
QI JUN 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

        # get and compare moment result
        moment_result_array = np.array(moment)

        self.assertAlmostEqual(6.0, moment_result_array[rows[0], 0])
        self.assertAlmostEqual(3.0, moment_result_array[rows[0], 2])
        self.assertAlmostEqual(2.0, moment_result_array[1, 0])
        # 2.0 + (1.0 + 1.0)^2
        self.assertAlmostEqual(6.0, moment_result_array[rows[1], 10])
        self.assertAlmostEqual(6.0, moment_result_array[rows[3], 4])

        self.assertAlmostEqual(2.0, moment_result_array[5, 8])
        self.assertAlmostEqual(3.0, moment_result_array[rows[2], 1])
        self.assertAlmostEqual(18.0, moment_result_array[rows[2], 8])

        # get and compare param result
        result_array = np.array(param)

        def get_out(param, lr, grad, m, epsilon):
            return param - lr * grad / (math.sqrt(m) + epsilon)

161 162 163 164 165 166 167 168 169
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 2.0, 6.0, 2.0), result_array[rows[0], 0], places=5
        )
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 1.0, 3.0, 2.0), result_array[rows[0], 2], places=5
        )
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 0.0, 2.0, 2.0), result_array[1, 0], places=5
        )
Q
QI JUN 已提交
170 171 172

        # grad_merge = 1.0 + 1.0
        # m = 6.0
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 2.0, 6.0, 2.0),
            result_array[rows[1], 10],
            places=5,
        )

        self.assertAlmostEqual(
            get_out(5.0, 2.0, 0.0, 2.0, 2.0), result_array[5, 8], places=5
        )
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 1.0, 3.0, 2.0), result_array[rows[2], 1], places=5
        )
        self.assertAlmostEqual(
            get_out(5.0, 2.0, 4.0, 18.0, 2.0),
            result_array[rows[2], 8],
            places=5,
        )
Q
QI JUN 已提交
190 191 192

    def test_sparse_adagrad(self):
        places = [core.CPUPlace()]
193
        if core.is_compiled_with_cuda():
D
dzhwinter 已提交
194
            places.append(core.CUDAPlace(0))
Q
QI JUN 已提交
195 196 197 198
        for place in places:
            self.check_with_place(place)


199
if __name__ == "__main__":
H
hong 已提交
200
    paddle.enable_static()
201
    unittest.main()