test_sgd_op.py 9.5 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
from __future__ import print_function

Q
Qiao Longfei 已提交
17
import unittest
Q
qijun 已提交
18
import numpy as np
19
import paddle.fluid as fluid
20 21
import paddle.fluid.core as core
from paddle.fluid.op import Operator
22
from op_test import OpTest
J
Jiawei Wang 已提交
23
import paddle
Q
Qiao Longfei 已提交
24 25


26
class TestSGDOp(OpTest):
Q
Qiao Longfei 已提交
27
    def setUp(self):
Q
qijun 已提交
28
        self.op_type = "sgd"
T
tensor-tang 已提交
29 30 31
        self.conf()
        w = np.random.random((self.h, self.w)).astype("float32")
        g = np.random.random((self.h, self.w)).astype("float32")
32
        lr = np.array([0.1]).astype("float32")
D
dangqingqing 已提交
33

34 35
        self.inputs = {'Param': w, 'Grad': g, 'LearningRate': lr}
        self.outputs = {'ParamOut': w - lr * g}
Q
Qiao Longfei 已提交
36

T
tensor-tang 已提交
37 38 39 40
    def conf(self):
        self.h = 102
        self.w = 105

Q
qijun 已提交
41 42 43
    def test_check_output(self):
        self.check_output()

Q
Qiao Longfei 已提交
44

T
tensor-tang 已提交
45 46 47 48 49 50
class TestSGDOpCase8X(TestSGDOp):
    def conf(self):
        self.h = 10
        self.w = 64


Q
qijun 已提交
51
class TestSparseSGDOp(unittest.TestCase):
Q
qijun 已提交
52
    def check_with_place(self, place):
Q
qijun 已提交
53 54 55 56 57
        scope = core.Scope()

        # create and initialize Grad Variable   
        height = 10
        rows = [0, 4, 7]
T
tensor-tang 已提交
58
        self.conf()
Q
qiaolongfei 已提交
59 60 61 62

        grad_selected_rows = scope.var('Grad').get_selected_rows()
        grad_selected_rows.set_height(height)
        grad_selected_rows.set_rows(rows)
T
tensor-tang 已提交
63
        np_array = np.ones((len(rows), self.row_numel)).astype("float32")
Q
qiaolongfei 已提交
64 65 66 67 68 69 70 71
        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()
T
tensor-tang 已提交
72
        param_array = np.full((height, self.row_numel), 5.0).astype("float32")
Q
qiaolongfei 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        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 run sgd operator
        sgd_op = Operator(
            "sgd",
            Param='Param',
            Grad='Grad',
            ParamOut='Param',
            LearningRate='LearningRate')
        sgd_op.run(scope, place)

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

        # rows[0] = 0, 5.0 - 2.0 * 2.0
        self.assertAlmostEqual(1.0, result_array[rows[0], 0])
        # rows[0] = 0, 5.0 - 2.0 * 1.0
        self.assertAlmostEqual(3.0, result_array[rows[0], 2])
        # 5.0 - 2.0 * 0.0
        self.assertAlmostEqual(5.0, result_array[1, 0])
        # rows[1] = 4, 5.0 - 2.0 * 1.0
        self.assertAlmostEqual(3.0, result_array[rows[1], 10])
        # 5.0 - 2.0 * 0.0
        self.assertAlmostEqual(5.0, result_array[5, 8])
        # rows[2] = 7, 5.0 - 2.0 * 1.0
        self.assertAlmostEqual(3.0, result_array[rows[2], 1])
        # rows[2] = 7, 5.0 - 2.0 * 4.0
        self.assertAlmostEqual(-3.0, result_array[rows[2], 8])

    def test_sparse_sgd(self):
        places = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))
        for place in places:
            self.check_with_place(place)

T
tensor-tang 已提交
114 115 116 117 118 119 120 121
    def conf(self):
        self.row_numel = 12


class TestSparseSGDOpCase8X(TestSparseSGDOp):
    def conf(self):
        self.row_numel = 16

Q
qiaolongfei 已提交
122 123 124 125 126

class TestSGDOpOptimizeSelectedRows(unittest.TestCase):
    def check_with_place(self, place):
        scope = core.Scope()

Q
qiaolongfei 已提交
127
        row_width = 12
Q
qiaolongfei 已提交
128
        # create and initialize Grad Variable
Q
qiaolongfei 已提交
129 130
        grad_height = 10
        grad_rows = [0, 4, 7]
Q
qijun 已提交
131 132

        grad_selected_rows = scope.var('Grad').get_selected_rows()
Q
qiaolongfei 已提交
133 134 135 136 137
        grad_selected_rows.set_height(grad_height)
        grad_selected_rows.set_rows(grad_rows)
        grad_array = np.ones((len(grad_rows), row_width)).astype("float32")
        grad_array[0, 0] = 2.0
        grad_array[2, 8] = 4.0
Q
qijun 已提交
138

Q
qijun 已提交
139
        grad_tensor = grad_selected_rows.get_tensor()
Q
qiaolongfei 已提交
140
        grad_tensor.set(grad_array, place)
Q
qijun 已提交
141 142

        # create and initialize Param Variable
Q
qiaolongfei 已提交
143 144 145 146 147 148 149
        # create and initialize W Variable
        param_rows = [0, 1, 2, 3, 4, 5, 6, 7]

        # init Param
        w_selected_rows = scope.var('Param').get_selected_rows()
        w_selected_rows.set_height(len(param_rows))
        w_selected_rows.set_rows(param_rows)
150
        w_selected_rows.sync_index()
Q
qiaolongfei 已提交
151 152 153 154 155 156 157
        w_array = np.ones((len(param_rows), row_width)).astype("float32")
        for i in range(len(param_rows)):
            w_array[i] *= i
        w_tensor = w_selected_rows.get_tensor()
        w_tensor.set(w_array, place)

        w_before_optimize = np.array(w_tensor)
Q
qijun 已提交
158 159

        # create and initialize LeraningRate Variable
Q
qiaolongfei 已提交
160
        lr_value = 0.1
Q
qijun 已提交
161
        lr = scope.var('LearningRate').get_tensor()
Q
qiaolongfei 已提交
162
        lr_array = np.full((1), lr_value).astype("float32")
Q
qijun 已提交
163 164
        lr.set(lr_array, place)

Q
qiaolongfei 已提交
165 166 167 168 169 170
        # optimize with Python
        w_after_optimize = np.copy(w_before_optimize)
        for index, id in enumerate(grad_rows):
            w_after_optimize[id] = w_before_optimize[
                id] - lr_value * grad_array[index]

Q
qijun 已提交
171 172 173 174 175 176 177
        # create and run sgd operator
        sgd_op = Operator(
            "sgd",
            Param='Param',
            Grad='Grad',
            ParamOut='Param',
            LearningRate='LearningRate')
D
dzhwinter 已提交
178
        sgd_op.run(scope, place)
Q
qijun 已提交
179 180

        # get and compare result
Q
qiaolongfei 已提交
181 182
        result_array = np.array(w_tensor)
        assert (result_array == w_after_optimize).all()
Q
qijun 已提交
183

184
    def test_sparse_parameter_sgd(self):
Q
qijun 已提交
185
        places = [core.CPUPlace()]
186
        # do not support GPU kernel currently
Q
qijun 已提交
187 188 189
        for place in places:
            self.check_with_place(place)

Q
qijun 已提交
190

191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
class TestSGDOpWithLargeInput(unittest.TestCase):
    def runTest(self):
        data = fluid.layers.fill_constant(shape=[1], value=128, dtype='int64')
        label = fluid.layers.fill_constant(
            shape=[1, 150], value=0.5, dtype='float32')
        emb = fluid.embedding(input=data, size=(10000000, 150), dtype='float32')
        out = fluid.layers.l2_normalize(x=emb, axis=-1)

        cost = fluid.layers.square_error_cost(input=out, label=label)
        avg_cost = fluid.layers.mean(cost)
        sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.001)
        sgd_optimizer.minimize(avg_cost)

        place = fluid.CPUPlace()
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())
        compiled_prog = fluid.compiler.CompiledProgram(
            fluid.default_main_program())
        result = exe.run(compiled_prog, fetch_list=[avg_cost])


J
Jiawei Wang 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
class TestSGDV2(unittest.TestCase):
    def test_sgd_dygraph(self):
        paddle.disable_static()
        value = np.arange(26).reshape(2, 13).astype("float32")
        a = paddle.to_tensor(value)
        linear = paddle.nn.Linear(13, 5)
        # This can be any optimizer supported by dygraph.
        adam = paddle.optimizer.SGD(learning_rate=0.01,
                                    parameters=linear.parameters(),
                                    weight_decay=0.01)
        out = linear(a)
        out.backward()
        adam.step()
        adam.clear_gradients()

    def test_sgd(self):
228
        paddle.enable_static()
J
Jiawei Wang 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        place = fluid.CPUPlace()
        main = fluid.Program()
        with fluid.program_guard(main):
            x = fluid.layers.data(name='x', shape=[13], dtype='float32')
            y = fluid.layers.data(name='y', shape=[1], dtype='float32')
            y_predict = fluid.layers.fc(input=x, size=1, act=None)
            cost = fluid.layers.square_error_cost(input=y_predict, label=y)
            avg_cost = fluid.layers.mean(cost)

            rms_optimizer = paddle.optimizer.SGD(learning_rate=0.1)
            rms_optimizer.minimize(avg_cost)

            fetch_list = [avg_cost]
            train_reader = paddle.batch(
                paddle.dataset.uci_housing.train(), batch_size=1)
            feeder = fluid.DataFeeder(place=place, feed_list=[x, y])
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
            for data in train_reader():
                exe.run(main, feed=feeder.feed(data), fetch_list=fetch_list)

    def test_raise_error(self):
        self.assertRaises(ValueError, paddle.optimizer.SGD, learning_rate=None)


254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
class TestSGDV2Group(TestSGDV2):
    def test_sgd_dygraph(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.
        adam = paddle.optimizer.SGD(learning_rate=0.01,
                                    parameters=[{
                                        'params': linear_1.parameters()
                                    }, {
                                        'params': linear_2.parameters(),
                                        'weight_decay': 0.001,
                                        'learning_rate': 0.1
                                    }],
                                    weight_decay=0.01)
        out = linear_1(a)
        out = linear_2(out)
        out.backward()
        adam.step()
        adam.clear_gradients()


Q
Qiao Longfei 已提交
278 279
if __name__ == "__main__":
    unittest.main()