test_optimizer_grad.py 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2019 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.

import unittest
from collections import defaultdict

18 19 20
import numpy as np

import paddle
21 22 23 24
import paddle.fluid as fluid
import paddle.fluid.optimizer as optimizer
from paddle.fluid.backward import _append_grad_suffix_

M
MRXLT 已提交
25 26
paddle.enable_static()

27 28 29 30 31
np.random.seed(10)

SHAPE = [16, 10]


32
class SimpleNetWithCond:
33 34 35 36 37 38 39 40 41 42 43 44 45
    """
    Build net with conditional Block and useless layers.
    """

    def __init__(self, test_optimizer, param_lr=1.0, y_no_grad=False):
        self.optimizer = test_optimizer
        self.param_lr = param_lr
        self.shape = SHAPE
        self.y_no_grad = y_no_grad
        self._init_param()

    def _init_param(self):
        self.x = np.ones(self.shape).astype('float32')
46 47
        self.y = np.ones(self.shape).astype('float32') * 2.0
        self.z = np.ones(self.shape).astype('float32') * 3.0
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

    def _calc_gradient(self, cond_i):
        """
        Calculate grads of params
        """
        grads = []
        d_out_val = np.ones_like(self.x).astype("float32") / np.prod(self.shape)
        grads.append(d_out_val)  # x_grad
        if cond_i > 1:
            y_grad_ratio, z_grad_ratio = 0 if self.y_no_grad else 3, 1
        else:
            y_grad_ratio, z_grad_ratio = 3, 0
        if not self.y_no_grad:
            grads.append(d_out_val * y_grad_ratio)  # y_grad
        grads.append(d_out_val * z_grad_ratio)  # z_grad

        return grads

A
arlesniak 已提交
66
    def build_net(self, cond_i, use_bf16=False):
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
        """
        pseudo code:
            sum_xy = x + y
            sub_yz = y - z
            if i > 1:
                internal = y + z
                sum_cond = internal + z
            else:
                sum_cond = y + z
            sum_all = sum_xy + sum_yz + sum_cond
            mean_out = mean(sum_all)
            optimizer.minimize(mean_out)
        """
        param_x = fluid.layers.create_parameter(
            dtype="float32",
            shape=self.shape,
83
            attr=fluid.ParamAttr(learning_rate=self.param_lr, name="param_x"),
84 85
            default_initializer=fluid.initializer.NumpyArrayInitializer(self.x),
        )
86 87 88 89

        param_y = fluid.layers.create_parameter(
            dtype="float32",
            shape=self.shape,
90
            attr=fluid.ParamAttr(learning_rate=self.param_lr, name="param_y"),
91 92
            default_initializer=fluid.initializer.NumpyArrayInitializer(self.y),
        )
93 94 95
        param_z = fluid.layers.create_parameter(
            dtype="float32",
            shape=self.shape,
96
            attr=fluid.ParamAttr(learning_rate=self.param_lr, name="param_z"),
97 98
            default_initializer=fluid.initializer.NumpyArrayInitializer(self.z),
        )
99 100 101 102 103 104

        sum_xy = fluid.layers.elementwise_add(param_x, param_y, name='sum_xy')
        sub_yz = fluid.layers.elementwise_sub(param_y, param_z, name='sub_yz')
        useless = fluid.layers.fc(param_x, size=1, name='fc_useless')

        def cond_true():
105 106 107
            cond_yz = fluid.layers.elementwise_add(
                param_y, param_z, name='sum_cond_yz'
            )
108 109
            # param_y will not be updated
            param_y.stop_gradient = self.y_no_grad
110 111 112
            cond_res = fluid.layers.elementwise_add(
                cond_yz, param_z, name='sum_cond_true'
            )
113 114 115 116
            cond_useless = fluid.layers.elementwise_mul(param_x, param_y)
            return cond_res

        def cond_false():
117 118 119
            cond_res = fluid.layers.elementwise_add(
                param_y, param_z, name='sum_cond_false'
            )
120 121 122 123 124
            cond_useless = fluid.layers.elementwise_mul(param_z, param_z)
            return cond_res

        cond_i = fluid.layers.assign(np.array([cond_i], dtype='float32'))
        sum_cond = fluid.layers.cond(cond_i > 1.0, cond_true, cond_false)
125
        sum_all = paddle.add_n([sum_xy, sub_yz, sum_cond])
126
        mean_out = paddle.mean(sum_all)
A
arlesniak 已提交
127 128
        if use_bf16:
            import paddle.static.amp as amp
129

A
arlesniak 已提交
130 131 132
            self.optimizer = amp.bf16.decorate_bf16(
                self.optimizer,
                amp_lists=amp.bf16.AutoMixedPrecisionListsBF16(
133 134
                    custom_fp32_list={'elementwise_add'}
                ),
A
arlesniak 已提交
135
                use_bf16_guard=False,
136 137
                use_pure_bf16=True,
            )
A
arlesniak 已提交
138

139 140
        self.optimizer.minimize(mean_out)

141 142 143 144 145
        fetch_list = (
            ["param_x", "param_z"]
            if self.y_no_grad
            else ["param_x", "param_y", "param_z"]
        )
146
        fetch_list += [_append_grad_suffix_(param) for param in fetch_list]
A
arlesniak 已提交
147
        return fetch_list, self.optimizer
148 149 150 151 152 153 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 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198


class TestOptimizer(unittest.TestCase):
    """
    TestOptimizer BaseClass to be inherited to test other Optimizer.
    And only need to implement two functions:
        setUp(): to set config info of optimizer, including Optimizer and its hyper-parameter.
        _apply_gradient(): to implement the way of updating grad.
    """

    def setUp(self):
        self._init_config()
        self.optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
        self.attr = {}

    def _init_config(self):
        self.NetClass = SimpleNetWithCond
        self.param_lr = [1.0, 2.0]
        self.cond_i = [0.1, 3]
        self.y_no_grad = [True, False]

    def test_optimizer(self):
        self._check_grads()

    def _apply_gradient(self, param, grad, name):
        """
        The way of updating grad in optimizer.(such as SGD)
        This method should be override.
        """
        return param - self.attr['lr'] * grad

    def _apply_optimize(self, net, grads):
        """
        apply to update all params in the net.
        """
        net.x = self._apply_gradient(net.x, grads[0], 'x')
        if len(grads) == 2:
            net.z = self._apply_gradient(net.z, grads[1], 'z')
            res = [net.x, net.z]
        else:
            net.y = self._apply_gradient(net.y, grads[1], 'y')
            net.z = self._apply_gradient(net.z, grads[2], 'z')
            res = [net.x, net.y, net.z]

        return res

    def _init_param_attr(self):
        self.param_attr = {}
        for key in ['x', 'y', 'z']:
            self.param_attr[key] = self.attr.copy()

A
arlesniak 已提交
199
    def _check_grads(self, use_bf16=False):
200 201 202 203 204 205 206 207 208 209 210
        """
        main logic code to check the validity of apply_optimize.
        """
        places = [fluid.CPUPlace()]
        if fluid.core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        # test on CPU and GPU
        for place in places:
            for param_lr in self.param_lr:
                for cond_i in self.cond_i:
                    for y_no_grad in self.y_no_grad:
211 212 213
                        self.attr['lr'] = (
                            param_lr * self.optimizer._learning_rate
                        )
214 215 216 217 218 219 220
                        self._init_param_attr()

                        main_program = fluid.Program()
                        init_program = fluid.Program()
                        with fluid.program_guard(main_program, init_program):
                            # reset optimizer._accumulators to avoid duplicate name in loop.
                            self.optimizer._accumulators = defaultdict(
221 222 223 224 225 226 227 228 229
                                lambda: dict()
                            )
                            test_net = self.NetClass(
                                self.optimizer, param_lr, y_no_grad
                            )
                            (
                                fetch_list,
                                decorated_optimizer,
                            ) = test_net.build_net(cond_i, use_bf16)
A
arlesniak 已提交
230 231
                            if use_bf16:
                                self.optimizer = decorated_optimizer
232 233 234

                            exe = fluid.Executor(place)
                            exe.run(init_program)
A
arlesniak 已提交
235 236 237
                            if use_bf16:
                                self.optimizer.amp_init(exe.place)

238 239 240
                            # Train 2 steps to check validity
                            for batch_i in range(2):

241 242 243
                                res = exe.run(
                                    main_program, fetch_list=fetch_list
                                )
244
                                gt_grads = test_net._calc_gradient(cond_i)
245
                                gt_params = self._apply_optimize(
246 247
                                    test_net, gt_grads
                                )
248 249
                                param_grads = gt_params + gt_grads
                                for i in range(len(res)):
250
                                    np.testing.assert_allclose(
251 252
                                        res[i], param_grads[i]
                                    )
253 254


255 256 257
@unittest.skipIf(
    not fluid.core.supports_bfloat16(), "place does not support BF16 evaluation"
)
A
arlesniak 已提交
258 259
class TestSGDOptimizer(TestOptimizer):
    def test_optimizer_multiblock_except(self):
260 261 262
        with self.assertRaisesRegexp(
            ValueError, "var param_y not in this block"
        ):
A
arlesniak 已提交
263 264 265
            self._check_grads(use_bf16=True)


266 267 268 269 270 271 272 273 274 275
class TestAdamOptimizer(TestOptimizer):
    """
    inherit TestOptimizer and shall override two functions as follows:
        setUp(): to set config info of optimizer, including Optimizer and its hyper-parameter.
        _apply_gradient(): to implement the way of updating grad.
    """

    def setUp(self):
        self._init_config()
        beta1, beta2, epsilon = 0.9, 0.999, 1e-8
276 277 278
        self.optimizer = optimizer.AdamOptimizer(
            learning_rate=0.01, beta1=beta1, beta2=beta2, epsilon=epsilon
        )
279 280 281 282 283 284 285
        self.attr = {
            "beta1": beta1,
            "beta2": beta2,
            "beta1_pow": beta1,
            "beta2_pow": beta2,
            "moment1": np.zeros(SHAPE).astype("float32"),
            "moment2": np.zeros(SHAPE).astype("float32"),
286
            "epsilon": epsilon,
287 288 289 290 291 292 293 294 295 296 297 298
        }

    def _apply_gradient(self, param, grad, name):
        """
        The way of updating grad in AdamOptimizer
        """
        attr = self.param_attr[name]
        beta1, beta2 = attr["beta1"], attr["beta2"]
        moment1, moment2 = attr['moment1'], attr['moment2']
        beta1_pow, beta2_pow = attr['beta1_pow'], attr['beta2_pow']
        epsilon = attr['epsilon']

299 300
        moment1_out = beta1 * moment1 + (1.0 - beta1) * grad
        moment2_out = beta2 * moment2 + (1.0 - beta2) * np.square(grad)
301

302
        lr = attr['lr'] * np.sqrt(1.0 - beta2_pow) / (1.0 - beta1_pow)
303
        param_out = param - lr * (
304 305 306
            moment1_out
            / (np.sqrt(moment2_out) + epsilon * np.sqrt(1 - beta2_pow))
        )
307 308 309 310 311 312 313 314 315 316 317 318

        # update hyper-parameter of optimizer
        self.param_attr[name]['beta1_pow'] = beta1_pow * beta1
        self.param_attr[name]['beta2_pow'] = beta2_pow * beta2
        self.param_attr[name]['moment1'] = moment1_out
        self.param_attr[name]['moment2'] = moment2_out

        return param_out


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