test_imperative_optimizer.py 10.5 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.

M
minqiyang 已提交
15 16
from __future__ import print_function

M
minqiyang 已提交
17 18 19
import contextlib
import unittest
import numpy as np
M
minqiyang 已提交
20
import six
M
minqiyang 已提交
21

M
minqiyang 已提交
22
import paddle
M
minqiyang 已提交
23 24
import paddle.fluid as fluid
from paddle.fluid import core
25
from paddle.fluid.optimizer import SGDOptimizer, Adam
26
from paddle.fluid.dygraph import Linear
L
lujun 已提交
27
from paddle.fluid.dygraph.base import to_variable
M
minqiyang 已提交
28
from test_imperative_base import new_program_scope
29 30


31
class MLP(fluid.Layer):
32 33
    def __init__(self, param_attr=None, bias_attr=None):
        super(MLP, self).__init__()
M
minqiyang 已提交
34

35 36
        self._fc1 = Linear(784, 10)
        self._fc2 = Linear(10, 10)
M
minqiyang 已提交
37

38 39 40 41
    def forward(self, inputs):
        y = self._fc1(inputs)
        y = self._fc2(y)
        return y
42

M
minqiyang 已提交
43

44 45
class TestImperativeOptimizerBase(unittest.TestCase):
    def setUp(self):
M
minqiyang 已提交
46
        self.batch_num = 20
M
minqiyang 已提交
47

48 49 50
    def get_optimizer_dygraph(self, parameter_list):
        raise NotImplementedError()

51
    def get_optimizer(self):
52
        raise NotImplementedError()
M
minqiyang 已提交
53

54 55 56
    def reader_decorator(self, reader):
        def _reader_imple():
            for item in reader():
57
                image = np.array(item[0]).reshape(1, 784)
58 59 60 61 62
                label = np.array(item[1]).astype('int64').reshape(1)
                yield image, label

        return _reader_imple

63
    def _check_mlp(self):
M
minqiyang 已提交
64
        seed = 90
65 66
        batch_size = 128

L
lujun 已提交
67
        with fluid.dygraph.guard():
M
minqiyang 已提交
68 69 70
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed

71 72 73
            mlp = MLP()
            optimizer = self.get_optimizer_dygraph(
                parameter_list=mlp.parameters())
74 75 76 77 78 79 80 81

            batch_py_reader = fluid.io.PyReader(capacity=1)
            batch_py_reader.decorate_sample_list_generator(
                paddle.batch(
                    self.reader_decorator(paddle.dataset.mnist.train()),
                    batch_size=batch_size,
                    drop_last=True),
                places=fluid.CPUPlace())
M
minqiyang 已提交
82

M
minqiyang 已提交
83
            dy_param_init_value = {}
84
            for batch_id, data in enumerate(batch_py_reader()):
85
                if batch_id >= self.batch_num:
M
minqiyang 已提交
86 87
                    break

88 89
                img = data[0]
                label = data[1]
90
                label.stop_gradient = True
91

92
                img = fluid.layers.reshape(img, shape=[batch_size, -1])
93 94
                cost = mlp(img)
                avg_loss = fluid.layers.reduce_mean(cost)
L
lujun 已提交
95
                dy_out = avg_loss.numpy()
M
minqiyang 已提交
96

M
minqiyang 已提交
97
                if batch_id == 0:
98
                    for param in mlp.parameters():
L
lujun 已提交
99
                        dy_param_init_value[param.name] = param.numpy()
M
minqiyang 已提交
100

L
lujun 已提交
101
                avg_loss.backward()
M
minqiyang 已提交
102
                optimizer.minimize(avg_loss)
103
                mlp.clear_gradients()
M
minqiyang 已提交
104
                dy_param_value = {}
105
                for param in mlp.parameters():
L
lujun 已提交
106
                    dy_param_value[param.name] = param.numpy()
M
minqiyang 已提交
107

M
minqiyang 已提交
108 109 110 111 112 113 114
        with new_program_scope():
            fluid.default_startup_program().random_seed = seed
            fluid.default_main_program().random_seed = seed

            exe = fluid.Executor(fluid.CPUPlace(
            ) if not core.is_compiled_with_cuda() else fluid.CUDAPlace(0))

115
            mlp = MLP()
M
minqiyang 已提交
116
            optimizer = self.get_optimizer()
M
minqiyang 已提交
117 118 119 120 121 122
            train_reader = paddle.batch(
                paddle.dataset.mnist.train(), batch_size=128, drop_last=True)

            img = fluid.layers.data(
                name='pixel', shape=[1, 28, 28], dtype='float32')
            label = fluid.layers.data(name='label', shape=[1], dtype='int64')
123
            img = fluid.layers.reshape(img, shape=[batch_size, -1])
124
            cost = mlp(img)
125
            avg_loss = fluid.layers.reduce_mean(cost)
M
minqiyang 已提交
126
            optimizer.minimize(avg_loss)
M
minqiyang 已提交
127 128 129 130

            # initialize params and fetch them
            static_param_init_value = {}
            static_param_name_list = []
131
            for param in mlp.parameters():
M
minqiyang 已提交
132 133 134 135 136 137 138 139
                static_param_name_list.append(param.name)

            out = exe.run(fluid.default_startup_program(),
                          fetch_list=static_param_name_list)

            for i in range(len(static_param_name_list)):
                static_param_init_value[static_param_name_list[i]] = out[i]

M
minqiyang 已提交
140
            for batch_id, data in enumerate(train_reader()):
141
                if batch_id >= self.batch_num:
M
minqiyang 已提交
142 143
                    break

M
minqiyang 已提交
144
                static_x_data = np.array(
M
minqiyang 已提交
145 146 147 148
                    [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 已提交
149
                fetch_list = [avg_loss.name]
M
minqiyang 已提交
150 151
                fetch_list.extend(static_param_name_list)
                out = exe.run(fluid.default_main_program(),
M
minqiyang 已提交
152
                              feed={"pixel": static_x_data,
M
minqiyang 已提交
153 154 155 156 157 158 159
                                    "label": y_data},
                              fetch_list=fetch_list)

                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 已提交
160 161 162 163 164 165 166

        for key, value in six.iteritems(static_param_init_value):
            self.assertTrue(np.allclose(value, dy_param_init_value[key]))

        self.assertTrue(np.allclose(static_out, dy_out))

        for key, value in six.iteritems(static_param_value):
M
minqiyang 已提交
167
            self.assertTrue(np.allclose(value, dy_param_value[key]))
M
minqiyang 已提交
168 169


170
class TestImperativeOptimizerPiecewiseDecay(TestImperativeOptimizerBase):
171 172 173 174 175 176 177 178 179
    def get_optimizer_dygraph(self, parameter_list):
        bd = [3, 6, 9]
        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)
        return optimizer

180 181 182 183 184 185 186 187 188 189 190
    def get_optimizer(self):
        bd = [3, 6, 9]
        optimizer = SGDOptimizer(learning_rate=fluid.layers.piecewise_decay(
            boundaries=bd, values=[0.1 * (0.1**i) for i in range(len(bd) + 1)]))
        return optimizer

    def test_sgd(self):
        self._check_mlp()


class TestImperativeOptimizerNaturalExpDecay(TestImperativeOptimizerBase):
191 192 193 194 195 196 197 198 199 200
    def get_optimizer_dygraph(self, parameter_list):
        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)
        return optimizer

201 202 203 204 205 206 207 208 209 210 211 212 213
    def get_optimizer(self):
        optimizer = SGDOptimizer(learning_rate=fluid.layers.natural_exp_decay(
            learning_rate=0.1,
            decay_steps=10000,
            decay_rate=0.5,
            staircase=True))
        return optimizer

    def test_sgd(self):
        self._check_mlp()


class TestImperativeOptimizerExponentialDecay(TestImperativeOptimizerBase):
214 215 216 217 218 219 220 221 222 223
    def get_optimizer_dygraph(self, parameter_list):
        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)
        return optimizer

224 225 226 227 228 229 230 231 232 233 234 235 236
    def get_optimizer(self):
        optimizer = SGDOptimizer(learning_rate=fluid.layers.exponential_decay(
            learning_rate=0.1,
            decay_steps=10000,
            decay_rate=0.5,
            staircase=True))
        return optimizer

    def test_sgd(self):
        self._check_mlp()


class TestImperativeOptimizerInverseTimeDecay(TestImperativeOptimizerBase):
237 238 239 240 241 242 243 244 245 246
    def get_optimizer_dygraph(self, parameter_list):
        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)
        return optimizer

247 248 249 250 251 252 253 254 255 256 257 258 259
    def get_optimizer(self):
        optimizer = Adam(learning_rate=fluid.layers.inverse_time_decay(
            learning_rate=0.1,
            decay_steps=10000,
            decay_rate=0.5,
            staircase=True))
        return optimizer

    def test_adam(self):
        self._check_mlp()


class TestImperativeOptimizerPolynomialDecay(TestImperativeOptimizerBase):
260 261 262 263 264 265 266
    def get_optimizer_dygraph(self, parameter_list):
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.polynomial_decay(
                learning_rate=0.1, decay_steps=5, cycle=self.cycle),
            parameter_list=parameter_list)
        return optimizer

267 268 269 270 271 272 273 274 275 276 277 278 279 280
    def get_optimizer(self):
        optimizer = SGDOptimizer(learning_rate=fluid.layers.polynomial_decay(
            learning_rate=0.1, decay_steps=5, cycle=self.cycle))
        return optimizer

    def test_sgd_cycle(self):
        self.cycle = True
        self._check_mlp()

    def test_sgd(self):
        self.cycle = False
        self._check_mlp()


M
minqiyang 已提交
281
class TestImperativeOptimizerCosineDecay(TestImperativeOptimizerBase):
282 283 284 285 286 287 288
    def get_optimizer_dygraph(self, parameter_list):
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.cosine_decay(
                learning_rate=0.1, step_each_epoch=10000, epochs=120),
            parameter_list=parameter_list)
        return optimizer

M
minqiyang 已提交
289 290 291 292 293 294 295 296 297 298
    def get_optimizer(self):
        optimizer = SGDOptimizer(learning_rate=fluid.layers.cosine_decay(
            learning_rate=0.1, step_each_epoch=10000, epochs=120))
        return optimizer

    def test_sgd(self):
        self._check_mlp()


class TestImperativeOptimizerNoamDecay(TestImperativeOptimizerBase):
299 300 301 302 303 304 305
    def get_optimizer_dygraph(self, parameter_list):
        optimizer = SGDOptimizer(
            learning_rate=fluid.layers.noam_decay(
                d_model=512, warmup_steps=8000),
            parameter_list=parameter_list)
        return optimizer

M
minqiyang 已提交
306 307 308 309 310 311 312
    def get_optimizer(self):
        optimizer = SGDOptimizer(learning_rate=fluid.layers.noam_decay(
            d_model=512, warmup_steps=8000))
        return optimizer

    def test_sgd(self):
        self._check_mlp()
M
minqiyang 已提交
313 314 315 316


if __name__ == '__main__':
    unittest.main()