test_gradient_clip.py 17.8 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
C
chengduo 已提交
2 3 4 5 6
#
# 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
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
C
chengduo 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21
#
# 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.

from __future__ import print_function

import unittest
import numpy as np
import paddle
import paddle.fluid.core as core
import paddle.fluid as fluid
22 23
import six
from fake_reader import fake_imdb_reader
C
chengduo 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52


def bow_net(data,
            label,
            dict_dim,
            emb_dim=128,
            hid_dim=128,
            hid_dim2=96,
            class_dim=2):
    """
    BOW net
    This model is from https://github.com/PaddlePaddle/models:
    fluid/PaddleNLP/text_classification/nets.py
    """
    emb = fluid.layers.embedding(
        input=data, is_sparse=True, size=[dict_dim, emb_dim])
    bow = fluid.layers.sequence_pool(input=emb, pool_type='sum')
    bow_tanh = fluid.layers.tanh(bow)
    fc_1 = fluid.layers.fc(input=bow_tanh, size=hid_dim, act="tanh")
    fc_2 = fluid.layers.fc(input=fc_1, size=hid_dim2, act="tanh")
    prediction = fluid.layers.fc(input=[fc_2], size=class_dim, act="softmax")
    cost = fluid.layers.cross_entropy(input=prediction, label=label)
    avg_cost = fluid.layers.mean(x=cost)

    return avg_cost


class TestGradientClip(unittest.TestCase):
    def setUp(self):
53
        self.word_dict_len = 5147
C
chengduo 已提交
54
        self.BATCH_SIZE = 2
55 56
        reader = fake_imdb_reader(self.word_dict_len, self.BATCH_SIZE * 100)
        self.train_data = paddle.batch(reader, batch_size=self.BATCH_SIZE)
57 58 59 60
        self.init()

    def init(self):
        pass
C
chengduo 已提交
61 62

    def get_places(self):
63
        places = [fluid.CPUPlace()]
C
chengduo 已提交
64
        if core.is_compiled_with_cuda():
65
            places.append(fluid.CUDAPlace(0))
C
chengduo 已提交
66 67
        return places

68 69
    def clip_gradient(self, params_grads):
        pass
70

71 72 73 74 75 76
    def check_clip_result(self, out, out_clip):
        pass

    def check_gradient_clip(self, place):
        prog = fluid.Program()
        startup_program = fluid.Program()
C
chengduo 已提交
77 78
        with fluid.program_guard(
                main_program=prog, startup_program=startup_program):
79 80 81 82
            image = fluid.data(name='x', shape=[-1, 784], dtype='float32')
            label = fluid.data(name='y', shape=[-1, 1], dtype='int64')
            hidden = fluid.layers.fc(input=image, size=32, act='relu')
            predict = fluid.layers.fc(input=hidden, size=10, act='softmax')
C
chengduo 已提交
83 84 85 86 87 88 89 90 91 92

            cost = fluid.layers.cross_entropy(input=predict, label=label)
            avg_cost = fluid.layers.mean(cost)

        prog_clip = prog.clone()
        avg_cost_clip = prog_clip.block(0).var(avg_cost.name)

        p_g = fluid.backward.append_backward(loss=avg_cost)
        p_g_clip = fluid.backward.append_backward(loss=avg_cost_clip)

93 94
        p_g = sorted(p_g, key=lambda x: x[0].name)
        p_g_clip = sorted(p_g_clip, key=lambda x: x[0].name)
95 96
        with fluid.program_guard(
                main_program=prog_clip, startup_program=startup_program):
97
            p_g_clip = self.clip_gradient(p_g_clip)
C
chengduo 已提交
98 99 100 101

        grad_list = [elem[1] for elem in p_g]
        grad_clip_list = [elem[1] for elem in p_g_clip]

102
        train_reader = paddle.batch(paddle.dataset.mnist.train(), batch_size=3)
C
chengduo 已提交
103 104 105 106
        exe = fluid.Executor(place)
        feeder = fluid.DataFeeder(feed_list=[image, label], place=place)
        exe.run(startup_program)

107 108 109 110 111 112
        data = next(train_reader())
        out = exe.run(prog, feed=feeder.feed(data), fetch_list=grad_list)
        out_clip = exe.run(prog_clip,
                           feed=feeder.feed(data),
                           fetch_list=grad_clip_list)
        self.check_clip_result(out, out_clip)
C
chengduo 已提交
113 114 115 116 117 118 119 120 121

    def check_sparse_gradient_clip(self, place):
        prog = fluid.framework.Program()
        startup_program = fluid.framework.Program()
        with fluid.program_guard(
                main_program=prog, startup_program=startup_program):
            data = fluid.layers.data(
                name="words", shape=[1], dtype="int64", lod_level=1)
            label = fluid.layers.data(name="label", shape=[1], dtype="int64")
122
            cost = bow_net(data, label, self.word_dict_len)
C
chengduo 已提交
123

124
            self.backward_and_optimize(cost)
C
chengduo 已提交
125 126 127 128 129 130 131 132 133 134 135

        exe = fluid.Executor(place)
        feeder = fluid.DataFeeder(feed_list=[data, label], place=place)
        exe.run(startup_program)

        data = next(self.train_data())
        val = exe.run(prog, feed=feeder.feed(data), fetch_list=[cost])[0]
        self.assertEqual((1, ), val.shape)
        print(val)
        self.assertFalse(np.isnan(val))

136 137 138 139 140 141 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
    def backward_and_optimize(cost):
        pass


class TestGradientClipByGlobalNorm(TestGradientClip):
    def init(self):
        self.clip_norm = 0.2

    def clip_gradient(self, params_grads):
        clip = fluid.clip.GradientClipByGlobalNorm(clip_norm=self.clip_norm)
        print(clip)
        return clip(params_grads)

    def check_clip_result(self, out, out_clip):
        global_norm = 0
        for v in out:
            global_norm += np.sum(np.power(v, 2))
        global_norm = np.sqrt(global_norm)
        scale = self.clip_norm / np.maximum(self.clip_norm, global_norm)
        res = []
        for i in range(len(out)):
            out[i] = scale * out[i]

        for u, v in zip(out, out_clip):
            self.assertTrue(
                np.allclose(
                    a=u, b=v, rtol=1e-5, atol=1e-8),
                "gradient clip by global norm has wrong results!")

    # test whether the ouput is right when use 'set_gradient_clip'
    def test_old_gradient_clip(self):
        def func(params_grads):
            clip = fluid.clip.GradientClipByGlobalNorm(clip_norm=self.clip_norm)
            fluid.clip.set_gradient_clip(clip)
            return fluid.clip.append_gradient_clip_ops(params_grads)

        self.clip_gradient = func
        self.check_gradient_clip(fluid.CPUPlace())

    # test whether the ouput is right when use 'minimize(grad_clip)'
    def test_new_gradient_clip(self):
        def func(params_grads):
            clip = fluid.clip.GradientClipByGlobalNorm(clip_norm=self.clip_norm)
            print(clip)
            return clip(params_grads)
C
chengduo 已提交
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        self.clip_gradient = func
        self.check_gradient_clip(fluid.CPUPlace())

    # invoke 'set_gradient_clip' in a wrong order
    def test_wrong_API_order(self):
        def backward_func(cost):
            # no clip gradient
            def fileter_func(param):
                return param.name == "fc.w_0"

            clip = fluid.clip.GradientClipByGlobalNorm(
                clip_norm=5.0, need_clip=fileter_func)
            fluid.clip.set_gradient_clip(clip)
            sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.01)
            # if 'set_gradient_clip' and 'minimize(grad_clip)' together, 'set_gradient_clip' will be ineffective
            sgd_optimizer.minimize(cost, grad_clip=clip)
            # 'set_gradient_clip' must before 'minimize', otherwise, 'set_gradient_clip' will be ineffective
            fluid.clip.set_gradient_clip(clip)

        self.backward_and_optimize = backward_func
C
chengduo 已提交
202 203 204
        for place in self.get_places():
            self.check_sparse_gradient_clip(place)

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
    # if grad is None or not need clip
    def test_none_grad(self):
        def fileter_func(param):
            return param.name == "x"

        clip = fluid.clip.GradientClipByGlobalNorm(
            self.clip_norm, need_clip=fileter_func)
        x = fluid.default_main_program().global_block().create_parameter(
            name="x", shape=[2, 3], dtype="float32")
        y = fluid.default_main_program().global_block().create_parameter(
            name="y", shape=[2, 3], dtype="float32")

        # (x, None) should not be returned
        params_grads = [(x, None), (x, y), (y, x)]
        params_grads = clip(params_grads)
        self.assertTrue(
            len(clip(params_grads)) == 2,
            "ClipByGlobalNorm: when grad is None, it shouldn't be returned by gradient clip!"
        )
        self.assertTrue(
            params_grads[0][1].name != 'y',
            "ClipByGlobalNorm: param_grad (x, y) should be clipped!")

    # raise typeError
    def test_tpyeError(self):
        # the type of need_clip must be an funciton
        with self.assertRaises(TypeError):
            clip = fluid.clip.GradientClipByGlobalNorm(
                clip_norm=self.clip_norm, need_clip="test")

        # the type of minimize(grad_clip=) must be an instance of GradientClipBase's derived class
        with self.assertRaises(TypeError):
            x = fluid.default_main_program().global_block().create_parameter(
                name="x", shape=[2, 3], dtype="float32")
            loss = fluid.layers.reduce_mean(x)
            sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.1)
            sgd_optimizer.minimize(loss, grad_clip="test")

        # the type of RecomputeOptimizer.minimize(grad_clip=) must be an instance of GradientClipBase's derived class
        with self.assertRaises(TypeError):
            x = fluid.default_main_program().global_block().create_parameter(
                name="x", shape=[2, 3], dtype="float32")
            loss = fluid.layers.reduce_mean(x)
            sgd_optimizer = fluid.optimizer.SGD(learning_rate=0.1)
            recompute_optimizer = fluid.optimizer.RecomputeOptimizer(
                sgd_optimizer)
            recompute_optimizer._set_checkpoints([x])
            recompute_optimizer.minimize(loss, grad_clip="test")


class TestGradientClipByNorm(TestGradientClip):
    def init(self):
        self.clip_norm = 0.2

    def clip_gradient(self, params_grads):
        clip = fluid.clip.GradientClipByNorm(clip_norm=self.clip_norm)
        print(clip)
        return clip(params_grads)

    def check_clip_result(self, out, out_clip):
        for u, v in zip(out, out_clip):
            norm = np.sqrt(np.sum(np.power(u, 2)))
            scale = self.clip_norm / np.maximum(self.clip_norm, norm)
            u = u * scale
            self.assertTrue(
                np.allclose(
                    a=u, b=v, rtol=1e-5, atol=1e-8),
                "gradient clip by norm has wrong results!")

    # test whether the ouput is right when use 'minimize(grad_clip)'
    def test_gradient_clip(self):
        self.check_gradient_clip(fluid.CPUPlace())

    # if grad is None or not need clip
    def test_none_grad(self):
        def fileter_func(param):
            return param.name == "z"

        clip = fluid.clip.GradientClipByNorm(
            self.clip_norm, need_clip=fileter_func)
        x = fluid.default_main_program().global_block().create_parameter(
            name="x", shape=[2, 3], dtype="float32")
        y = fluid.default_main_program().global_block().create_parameter(
            name="y", shape=[2, 3], dtype="float32")

        # (x, None) should not be returned
        params_grads = [(x, None), (x, y)]
        params_grads = clip(params_grads)
        self.assertTrue(
            len(clip(params_grads)) == 1,
            "ClipByNorm: when grad is None, it shouldn't be returned by gradient clip!"
        )
        self.assertTrue(
            params_grads[0][1].name == 'y',
            "ClipByNorm: grad should not be clipped when filtered out!")


class TestGradientClipByValue(TestGradientClip):
    def init(self):
        self.max = 0.2
        self.min = 0.1

    def clip_gradient(self, params_grads):
        clip = fluid.clip.GradientClipByValue(max=self.max, min=self.min)
        print(clip)
        return clip(params_grads)

    def check_clip_result(self, out, out_clip):
        for i, v in enumerate(out):
            out[i] = np.clip(v, self.min, self.max)
        for u, v in zip(out, out_clip):
            u = np.clip(u, self.min, self.max)
            self.assertTrue(
                np.allclose(
                    a=u, b=v, rtol=1e-6, atol=1e-8),
                "gradient clip by value has wrong results!")

    # test whether the ouput is right when use 'minimize(grad_clip)'
    def test_gradient_clip(self):
        self.check_gradient_clip(fluid.CPUPlace())

    # if grad is None or not need clip
    def test_none_grad(self):
        def fileter_func(param):
            return param.name == "z"

        clip = fluid.clip.GradientClipByValue(
            self.max, self.min, need_clip=fileter_func)
        x = fluid.default_main_program().global_block().create_parameter(
            name="x", shape=[2, 3], dtype="float32")
        y = fluid.default_main_program().global_block().create_parameter(
            name="y", shape=[2, 3], dtype="float32")

        # (x, None) should not be returned
        params_grads = [(x, None), (x, y)]
        params_grads = clip(params_grads)
        self.assertTrue(
            len(clip(params_grads)) == 1,
            "ClipByValue: when grad is None, it shouldn't be returned by gradient clip!"
        )
        self.assertTrue(
            params_grads[0][1].name == 'y',
            "ClipByValue: grad should not be clipped when filtered out!")


class TestDygraphGradientClip(unittest.TestCase):
    def test_gradient_clip(self):
        with fluid.dygraph.guard():
            linear = fluid.dygraph.Linear(5, 5)
            inputs = fluid.layers.uniform_random(
                [16, 5], min=-10, max=10).astype('float32')
            out = linear(fluid.dygraph.to_variable(inputs))
            loss = fluid.layers.reduce_mean(out)
            loss.backward()
            sgd_optimizer = fluid.optimizer.SGD(
                learning_rate=0.0, parameter_list=linear.parameters())
            self.check_clip_result(loss, sgd_optimizer)

    def check_clip_result(self, loss, optimizer):
        pass


class TestDygraphGradientClipByGlobalNorm(TestDygraphGradientClip):
    def setUp(self):
        # only clip gradient of x (ParamBase)
        def fileter_func(param):
            return param.name == "x"

        self.clip_norm = 0.8
        self.clip1 = fluid.clip.GradientClipByGlobalNorm(
            clip_norm=self.clip_norm, need_clip=fileter_func)
        self.clip2 = fluid.clip.GradientClipByGlobalNorm(
            clip_norm=self.clip_norm)

    def check_clip_result(self, loss, optimizer):
        # if grad is None
        x = fluid.dygraph.to_variable(
            np.array([2, 3]).astype("float32"), name="x")
        y = fluid.dygraph.to_variable(
            np.array([3, 4]).astype("float32"), name="y")
        assert len(self.clip1([(x, x), (x, y), (x, None)])) == 2
        # get params and grads from network
        opt, params_grads = optimizer.minimize(loss, grad_clip=self.clip2)
        _, grads = zip(*params_grads)
        params_grads = self.clip2(params_grads)
        _, grads_clip = zip(*params_grads)

        global_norm = 0
        for u in grads:
            u = u.numpy()
            global_norm += np.sum(np.power(u, 2))
        global_norm = np.sqrt(global_norm)

        global_norm_clip = 0
        for v in grads_clip:
            v = v.numpy()
            global_norm_clip += np.sum(np.power(v, 2))
        global_norm_clip = np.sqrt(global_norm_clip)

        a = np.minimum(global_norm, self.clip_norm)
        b = global_norm_clip
        self.assertTrue(
            np.isclose(
                a=a, b=b, rtol=1e-6, atol=1e-8),
            "gradient clip by global norm has wrong results, expetcd:%f, but recieved:%f"
            % (a, b))


class TestDygraphGradientClipByNorm(TestDygraphGradientClip):
    def setUp(self):
        # only clip gradient of linear_0.w_0 (ParamBase)
        def fileter_func(param):
            return param.name == "linear_0.w_0"

        self.clip_norm = 0.8
        self.clip = fluid.clip.GradientClipByNorm(
            clip_norm=self.clip_norm, need_clip=fileter_func)

    def check_clip_result(self, loss, optimizer):
        # if grad is None
        x = fluid.dygraph.to_variable(np.array([2, 3]).astype("float32"))
        assert len(self.clip([(x, None)])) == 0
        # get params and grads from network
        self.clip([(fluid.dygraph.to_variable(np.array([2, 3])), None)])
        params_grads = optimizer.backward(loss)
        _, grads = zip(*params_grads)
        params_grads = self.clip(params_grads)
        _, grads_clip = zip(*params_grads)

        for u, v in zip(grads, grads_clip):
            u = u.numpy()
            v = v.numpy()
            a = np.sqrt(np.sum(np.power(u, 2)))
            a = np.minimum(a, self.clip_norm)
            b = np.sqrt(np.sum(np.power(v, 2)))
            self.assertTrue(
                np.isclose(
                    a=a, b=b, rtol=1e-6, atol=1e-8),
                "gradient clip by norm has wrong results, expetcd:%f, but recieved:%f"
                % (a, b))


class TestDygraphGradientClipByValue(TestDygraphGradientClip):
    def setUp(self):
        # only clip gradient of linear_0.w_0 (ParamBase)
        def fileter_func(param):
            return param.name == "linear_0.w_0"

        self.max = 0.2
        self.min = 0.1
        self.clip = fluid.clip.GradientClipByValue(
            max=self.max, min=self.min, need_clip=fileter_func)

    def check_clip_result(self, loss, optimizer):
        # if grad is None
        x = fluid.dygraph.to_variable(np.array([2, 3]).astype("float32"))
        assert len(self.clip([(x, None)])) == 0
        # get params and grads from network
        params_grads = optimizer.backward(loss)
        _, grads = zip(*params_grads)
        params_grads = self.clip(params_grads)
        _, grads_clip = zip(*params_grads)
        for u, v in zip(grads, grads_clip):
            u = np.clip(u.numpy(), self.min, self.max)
            v = v.numpy()
            self.assertTrue(
                np.allclose(
                    a=u, b=v, rtol=1e-6, atol=1e-8),
                "gradient clip by value has wrong results!")

C
chengduo 已提交
475 476 477

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