test_optimizer_grad.py 11.0 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
        """
        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)
        """
80
        param_x = paddle.create_parameter(
81 82
            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
        param_y = paddle.create_parameter(
88 89
            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
        param_z = paddle.create_parameter(
94 95
            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
        sum_xy = paddle.add(param_x, param_y, name='sum_xy')
        sub_yz = paddle.subtract(param_y, param_z, name='sub_yz')
102 103 104
        useless = fluid.layers.fc(param_x, size=1, name='fc_useless')

        def cond_true():
105
            cond_yz = paddle.add(param_y, param_z, name='sum_cond_yz')
106 107
            # param_y will not be updated
            param_y.stop_gradient = self.y_no_grad
108 109
            cond_res = paddle.add(cond_yz, param_z, name='sum_cond_true')
            cond_useless = paddle.multiply(param_x, param_y)
110 111 112
            return cond_res

        def cond_false():
113 114
            cond_res = paddle.add(param_y, param_z, name='sum_cond_false')
            cond_useless = paddle.multiply(param_z, param_z)
115 116 117
            return cond_res

        cond_i = fluid.layers.assign(np.array([cond_i], dtype='float32'))
118
        sum_cond = paddle.static.nn.cond(cond_i > 1.0, cond_true, cond_false)
119
        sum_all = paddle.add_n([sum_xy, sub_yz, sum_cond])
120
        mean_out = paddle.mean(sum_all)
A
arlesniak 已提交
121 122
        if use_bf16:
            import paddle.static.amp as amp
123

A
arlesniak 已提交
124 125 126
            self.optimizer = amp.bf16.decorate_bf16(
                self.optimizer,
                amp_lists=amp.bf16.AutoMixedPrecisionListsBF16(
127 128
                    custom_fp32_list={'elementwise_add'}
                ),
A
arlesniak 已提交
129
                use_bf16_guard=False,
130 131
                use_pure_bf16=True,
            )
A
arlesniak 已提交
132

133 134
        self.optimizer.minimize(mean_out)

135 136 137 138 139
        fetch_list = (
            ["param_x", "param_z"]
            if self.y_no_grad
            else ["param_x", "param_y", "param_z"]
        )
140
        fetch_list += [_append_grad_suffix_(param) for param in fetch_list]
A
arlesniak 已提交
141
        return fetch_list, self.optimizer
142 143 144 145 146 147 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


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 已提交
193
    def _check_grads(self, use_bf16=False):
194 195 196 197 198 199 200 201 202 203 204
        """
        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:
205 206 207
                        self.attr['lr'] = (
                            param_lr * self.optimizer._learning_rate
                        )
208 209 210 211 212 213 214
                        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(
215 216 217 218 219 220 221 222 223
                                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 已提交
224 225
                            if use_bf16:
                                self.optimizer = decorated_optimizer
226 227 228

                            exe = fluid.Executor(place)
                            exe.run(init_program)
A
arlesniak 已提交
229 230 231
                            if use_bf16:
                                self.optimizer.amp_init(exe.place)

232 233 234
                            # Train 2 steps to check validity
                            for batch_i in range(2):

235 236 237
                                res = exe.run(
                                    main_program, fetch_list=fetch_list
                                )
238
                                gt_grads = test_net._calc_gradient(cond_i)
239
                                gt_params = self._apply_optimize(
240 241
                                    test_net, gt_grads
                                )
242 243
                                param_grads = gt_params + gt_grads
                                for i in range(len(res)):
244
                                    np.testing.assert_allclose(
245 246
                                        res[i], param_grads[i]
                                    )
247 248


249 250 251
@unittest.skipIf(
    not fluid.core.supports_bfloat16(), "place does not support BF16 evaluation"
)
A
arlesniak 已提交
252 253
class TestSGDOptimizer(TestOptimizer):
    def test_optimizer_multiblock_except(self):
254 255 256
        with self.assertRaisesRegexp(
            ValueError, "var param_y not in this block"
        ):
A
arlesniak 已提交
257 258 259
            self._check_grads(use_bf16=True)


260 261 262 263 264 265 266 267 268 269
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
270 271 272
        self.optimizer = optimizer.AdamOptimizer(
            learning_rate=0.01, beta1=beta1, beta2=beta2, epsilon=epsilon
        )
273 274 275 276 277 278 279
        self.attr = {
            "beta1": beta1,
            "beta2": beta2,
            "beta1_pow": beta1,
            "beta2_pow": beta2,
            "moment1": np.zeros(SHAPE).astype("float32"),
            "moment2": np.zeros(SHAPE).astype("float32"),
280
            "epsilon": epsilon,
281 282 283 284 285 286 287 288 289 290 291 292
        }

    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']

293 294
        moment1_out = beta1 * moment1 + (1.0 - beta1) * grad
        moment2_out = beta2 * moment2 + (1.0 - beta2) * np.square(grad)
295

296
        lr = attr['lr'] * np.sqrt(1.0 - beta2_pow) / (1.0 - beta1_pow)
297
        param_out = param - lr * (
298 299 300
            moment1_out
            / (np.sqrt(moment2_out) + epsilon * np.sqrt(1 - beta2_pow))
        )
301 302 303 304 305 306 307 308 309 310 311 312

        # 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()