test_imperative_auto_prune.py 18.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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
16 17 18

import numpy as np

19
import paddle
20
import paddle.fluid as fluid
21
from paddle.fluid.framework import _test_eager_guard
22
from paddle.tensor import random
23 24 25


class AutoPruneLayer0(fluid.Layer):
26
    def __init__(self, input_size):
27
        super().__init__()
28
        self.linear1 = paddle.nn.Linear(
29
            input_size,
30
            5,
31 32 33
            weight_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=2)
            ),
34 35
            bias_attr=False,
        )
36
        self.linear2 = paddle.nn.Linear(
37
            5,
38
            5,
39 40 41
            weight_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=2)
            ),
42 43
            bias_attr=False,
        )
44 45

    def forward(self, x, y):
46 47
        a = self.linear1(x)
        b = self.linear2(y)
48
        c = fluid.layers.mul(a, b)
49
        d = paddle.mean(c)
50 51 52 53
        return d


class AutoPruneLayer1(fluid.Layer):
54
    def __init__(self, input_size):
55
        super().__init__()
56
        self.linear1 = paddle.nn.Linear(
57
            input_size,
58
            5,
59 60 61
            weight_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=2)
            ),
62 63
            bias_attr=False,
        )
64
        self.linear2 = paddle.nn.Linear(
65
            5,
66
            5,
67 68 69
            weight_attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(value=2)
            ),
70 71
            bias_attr=False,
        )
72 73

    def forward(self, x, y):
74 75
        a = self.linear1(x)
        b = self.linear2(y)
76 77
        b.stop_gradient = True
        c = fluid.layers.mul(a, b)
78
        d = paddle.mean(c)
79 80 81 82
        return d


class AutoPruneLayer2(fluid.Layer):
83
    def __init__(self, input_size):
84
        super().__init__()
85 86
        self.linear = paddle.nn.Linear(input_size, 10)
        self.linear2 = paddle.nn.Linear(1, 1)
87 88

    def forward(self, x, label):
89 90
        feature = self.linear(x)
        label = self.linear2(label)
91 92
        label = fluid.layers.cast(label, dtype="float32")
        label = fluid.layers.cast(label, dtype='int64')
93 94 95 96
        # Note that the label is not persistable in paddle.nn.functional.cross_entropy.
        loss = paddle.nn.functional.cross_entropy(
            input=feature, label=label, reduction='none', use_softmax=False
        )
97
        loss = paddle.mean(loss)
98 99 100 101
        return loss


class AutoPruneLayer3(fluid.Layer):
102
    def __init__(self, input_size):
103
        super().__init__()
104
        self.linear = paddle.nn.Linear(input_size, 20)
105 106

    def forward(self, x, label, test_num):
107
        feature = self.linear(x)
108 109 110
        part1, part2 = fluid.layers.split(
            feature, num_or_sections=[10, 10], dim=1
        )
111
        # Note that: part2 is not used.
112 113 114
        loss = paddle.nn.functional.cross_entropy(
            input=part1, label=label, reduction='none', use_softmax=False
        )
115
        loss = paddle.mean(loss)
116 117 118 119 120 121 122
        if test_num == 1:
            return loss, part2
        else:
            return loss, part1, part2


class MyLayer(fluid.Layer):
123
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
124
        super().__init__(dtype=dtype)
125 126
        self.embed0 = fluid.Embedding(size=(vocab_size, size))
        self.embed1 = fluid.Embedding(size=(vocab_size, size))
127 128
        self.linear_0 = paddle.nn.Linear(input_size, size)
        self.linear_1 = paddle.nn.Linear(input_size, size)
129 130

    def forward(self, x):
131
        # this method involves only the linear layers
132
        loss = paddle.mean(self.linear_0(x) + self.linear_1(x))
133 134 135
        return loss

    def linear0(self, x):
136
        loss = paddle.mean(self.linear_0(x))
137 138 139
        return loss

    def embed_linear0(self, x):
140
        loss = paddle.mean(self.linear_0(self.embed0(x)))
141 142 143 144
        return loss


class MyLayer2(fluid.Layer):
145
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
146
        super().__init__(dtype=dtype)
147 148
        self.embed0 = fluid.Embedding(size=(vocab_size, size))
        self.embed1 = fluid.Embedding(size=(vocab_size, size))
149 150
        self.linear_0 = paddle.nn.Linear(input_size, size)
        self.linear_1 = paddle.nn.Linear(input_size, size)
151 152 153 154

    def forward(self, indices):
        # mind the difference with MyLayer
        # In this example, the forward method involes all params
155
        loss = paddle.mean(
156 157 158
            self.linear_0(self.embed0(indices))
            + self.linear_1(self.embed1(indices))
        )
159 160 161
        return loss

    def linear0(self, x):
162
        loss = paddle.mean(self.linear_0(x))
163 164 165
        return loss

    def embed_linear0(self, x):
166
        loss = paddle.mean(self.linear_0(self.embed0(x)))
167 168 169 170
        return loss


class TestImperativeAutoPrune(unittest.TestCase):
171
    def func_auto_prune(self):
172
        with fluid.dygraph.guard():
173
            case1 = AutoPruneLayer0(input_size=5)
174 175 176 177 178 179
            value1 = np.arange(25).reshape(5, 5).astype("float32")
            value2 = np.arange(25).reshape(5, 5).astype("float32")
            v1 = fluid.dygraph.to_variable(value1)
            v2 = fluid.dygraph.to_variable(value2)
            loss = case1(v1, v2)
            loss.backward()
180 181
            self.assertIsNotNone(case1.linear2.weight._grad_ivar())
            self.assertIsNotNone(case1.linear1.weight._grad_ivar())
182

183 184 185 186 187 188
    def test_auto_prune(self):
        with _test_eager_guard():
            self.func_auto_prune()
        self.func_auto_prune()

    def func_auto_prune2(self):
189
        with fluid.dygraph.guard():
190
            case2 = AutoPruneLayer1(input_size=5)
191 192 193 194 195
            value1 = np.arange(25).reshape(5, 5).astype("float32")
            value2 = np.arange(25).reshape(5, 5).astype("float32")
            v1 = fluid.dygraph.to_variable(value1)
            v2 = fluid.dygraph.to_variable(value2)
            loss = case2(v1, v2)
H
hong 已提交
196

197
            loss.backward()
198 199
            self.assertIsNone(case2.linear2.weight._grad_ivar())
            self.assertIsNotNone(case2.linear1.weight._grad_ivar())
200

201 202 203 204 205
    def test_auto_prune2(self):
        with _test_eager_guard():
            self.func_auto_prune2()
        self.func_auto_prune2()

206
    # TODO(jiabin): Support this when we support better split tensor
207
    def func_auto_prune3(self):
208
        with fluid.dygraph.guard():
209
            case3 = AutoPruneLayer3(input_size=784)
210 211 212 213 214 215
            value1 = np.arange(784).reshape(1, 784).astype("float32")
            value2 = np.arange(1).reshape(1, 1).astype("int64")
            v1 = fluid.dygraph.to_variable(value1)
            v2 = fluid.dygraph.to_variable(value2)
            loss, part2 = case3(v1, v2, 1)
            loss.backward()
216
            self.assertIsNotNone(case3.linear.weight._grad_ivar())
217 218
            self.assertTrue((part2.gradient() == 0).all())

219
    def test_auto_prune3(self):
220
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
221 222 223
        with _test_eager_guard():
            self.func_auto_prune3()
        self.func_auto_prune3()
224
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
225 226

    def func_auto_prune4(self):
227
        with fluid.dygraph.guard():
228
            case4 = AutoPruneLayer3(input_size=784)
229 230 231 232 233 234
            value1 = np.arange(784).reshape(1, 784).astype("float32")
            value2 = np.arange(1).reshape(1, 1).astype("int64")
            v1 = fluid.dygraph.to_variable(value1)
            v2 = fluid.dygraph.to_variable(value2)
            loss, part2 = case4(v1, v2, 1)
            part2.backward()
235
            self.assertIsNotNone(case4.linear.weight._grad_ivar())
236 237
            self.assertTrue((part2.gradient() == 1).all())

238
    def test_auto_prune4(self):
239
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
240 241 242
        with _test_eager_guard():
            self.func_auto_prune4()
        self.func_auto_prune4()
243
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
244 245

    def func_auto_prune5(self):
246
        with fluid.dygraph.guard():
247
            case4 = AutoPruneLayer3(input_size=784)
248 249 250 251 252 253
            value1 = np.arange(784).reshape(1, 784).astype("float32")
            value2 = np.arange(1).reshape(1, 1).astype("int64")
            v1 = fluid.dygraph.to_variable(value1)
            v2 = fluid.dygraph.to_variable(value2)
            loss, part1, part2 = case4(v1, v2, 2)
            part1.backward()
254
            self.assertIsNotNone(case4.linear.weight._grad_ivar())
255 256
            self.assertTrue((part2.gradient() == 0).all())

257
    def test_auto_prune5(self):
258
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
259 260 261
        with _test_eager_guard():
            self.func_auto_prune5()
        self.func_auto_prune5()
262
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
263

264
    def func_auto_prune6(self):
265 266 267 268
        with fluid.dygraph.guard():
            value0 = np.arange(26).reshape(2, 13).astype("float32")
            value1 = np.arange(6).reshape(2, 3).astype("float32")
            value2 = np.arange(10).reshape(2, 5).astype("float32")
269 270
            linear = paddle.nn.Linear(13, 5)
            linear2 = paddle.nn.Linear(3, 3)
271 272 273
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
274 275
            out1 = linear(a)
            out2 = linear2(b)
276 277 278
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
            out.backward()
279 280
            self.assertIsNone(linear.weight.gradient())
            self.assertIsNone(out1.gradient())
281

282 283 284 285 286 287
    def test_auto_prune6(self):
        with _test_eager_guard():
            self.func_auto_prune6()
        self.func_auto_prune6()

    def func_auto_prune7(self):
288 289 290 291
        with fluid.dygraph.guard():
            value0 = np.arange(26).reshape(2, 13).astype("float32")
            value1 = np.arange(6).reshape(2, 3).astype("float32")
            value2 = np.arange(10).reshape(2, 5).astype("float32")
292 293
            linear = paddle.nn.Linear(13, 5)
            linear2 = paddle.nn.Linear(3, 3)
294 295 296
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
297 298
            out1 = linear(a)
            out2 = linear2(b)
299 300
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
301
            out.backward()
302 303
            self.assertIsNone(linear.weight.gradient())
            self.assertIsNone(out1.gradient())
304

305 306 307 308 309 310
    def test_auto_prune7(self):
        with _test_eager_guard():
            self.func_auto_prune7()
        self.func_auto_prune7()

    def func_auto_prune8(self):
311 312 313 314
        with fluid.dygraph.guard():
            value0 = np.arange(26).reshape(2, 13).astype("float32")
            value1 = np.arange(6).reshape(2, 3).astype("float32")
            value2 = np.arange(10).reshape(2, 5).astype("float32")
315 316
            linear = paddle.nn.Linear(13, 5)
            linear2 = paddle.nn.Linear(5, 3)
317 318 319
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
320 321 322 323 324
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
            linear2.weight.stop_gradient = True
325
            out2.backward()
326 327
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
328 329
                parameter_list=(linear.parameters() + linear2.parameters()),
            )
330
            optimizer.minimize(out2)
331 332 333
            np.testing.assert_array_equal(
                linear2_origin, linear2.weight.numpy()
            )
334
            self.assertFalse(
335 336
                np.array_equal(linear_origin, linear.weight.numpy())
            )
337

338 339 340 341 342 343
    def test_auto_prune8(self):
        with _test_eager_guard():
            self.func_auto_prune8()
        self.func_auto_prune8()

    def func_auto_prune9(self):
344 345 346 347
        with fluid.dygraph.guard():
            value0 = np.arange(26).reshape(2, 13).astype("float32")
            value1 = np.arange(6).reshape(2, 3).astype("float32")
            value2 = np.arange(10).reshape(2, 5).astype("float32")
348 349
            linear = paddle.nn.Linear(13, 5)
            linear2 = paddle.nn.Linear(5, 3)
350 351 352
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
353 354 355 356
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
357 358
            out2.stop_gradient = True
            out2.backward()
359 360
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
361 362
                parameter_list=(linear.parameters() + linear2.parameters()),
            )
363
            optimizer.minimize(out2)
364 365 366
            np.testing.assert_array_equal(
                linear2_origin, linear2.weight.numpy()
            )
367
            np.testing.assert_array_equal(linear_origin, linear.weight.numpy())
368
            try:
369
                linear2.weight.gradient()
370 371 372
            except ValueError as e:
                assert type(e) == ValueError

373 374 375 376 377 378
    def test_auto_prune9(self):
        with _test_eager_guard():
            self.func_auto_prune9()
        self.func_auto_prune9()

    def func_auto_prune10(self):
379 380 381 382
        with fluid.dygraph.guard():
            value0 = np.arange(26).reshape(2, 13).astype("float32")
            value1 = np.arange(6).reshape(2, 3).astype("float32")
            value2 = np.arange(10).reshape(2, 5).astype("float32")
383 384
            linear = paddle.nn.Linear(13, 5)
            linear2 = paddle.nn.Linear(3, 3)
385 386 387
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
388 389
            out1 = linear(a)
            out2 = linear2(b)
390 391
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
392
            # TODO(jiabin): In Eager Mode we don't actually need sort_sum_gradient, this test should be removed when we don't support fluid anymore.
393 394
            fluid.set_flags({'FLAGS_sort_sum_gradient': True})
            out.backward()
395 396
            self.assertIsNone(linear.weight.gradient())
            self.assertIsNone(out1.gradient())
397

398 399 400 401 402 403
    def test_auto_prune10(self):
        with _test_eager_guard():
            self.func_auto_prune10()
        self.func_auto_prune10()

    def func_auto_prune_with_optimizer(self):
404 405 406 407
        vocab_size = 100
        size = 20
        batch_size = 16

408 409 410
        indices = np.random.randint(
            low=0, high=100, size=(batch_size, 1)
        ).astype("int64")
411 412 413 414
        embed = np.random.randn(batch_size, size).astype("float32")

        place = fluid.CPUPlace()
        with fluid.dygraph.guard(place):
415
            model = MyLayer(size, vocab_size, size)
416
            grad_clip = fluid.clip.GradientClipByGlobalNorm(0.001)
417
            optimizer = fluid.optimizer.AdamOptimizer(
418 419
                0.001, parameter_list=model.parameters(), grad_clip=grad_clip
            )
420
            indices = fluid.dygraph.to_variable(indices)
421
            embed = fluid.dygraph.to_variable(embed)
422 423 424 425
            dummy_loss = model(embed)

            loss = model.embed_linear0(indices)
            loss.backward()
426
            _, params_grads = optimizer.minimize(loss)
427
            for items in params_grads:
428
                assert items[0].name is not model.embed1.weight.name
429
                assert items[0].name is not model.linear_1.weight.name
430
            assert model.embed1.weight._grad_ivar() is None
431
            assert model.linear_1.weight._grad_ivar() is None
432 433

        with fluid.dygraph.guard(place):
434
            model = MyLayer2(size, vocab_size, size)
435
            grad_clip = fluid.clip.GradientClipByGlobalNorm(0.001)
436
            optimizer = fluid.optimizer.AdamOptimizer(
437 438
                0.001, parameter_list=model.parameters(), grad_clip=grad_clip
            )
439 440 441 442 443 444 445

            indices = fluid.dygraph.to_variable(indices)
            emebd = fluid.dygraph.to_variable(embed)
            dummy_loss = model(indices)

            loss = model.embed_linear0(indices)
            loss.backward()
446
            optimizer.minimize(loss)
447
            for items in params_grads:
448
                assert items[0].name is not model.embed1.weight.name
449
                assert items[0].name is not model.linear_1.weight.name
450
            assert model.embed1.weight._grad_ivar() is None
451
            assert model.linear_1.weight._grad_ivar() is None
452

453 454 455 456 457 458
    def test_auto_prune_with_optimizer(self):
        with _test_eager_guard():
            self.func_auto_prune_with_optimizer()
        self.func_auto_prune_with_optimizer()

    def func_case2_prune_no_grad_branch(self):
459 460 461 462 463
        with fluid.dygraph.guard():
            value1 = np.arange(784).reshape(1, 784)
            value2 = np.arange(1).reshape(1, 1)
            v1 = fluid.dygraph.to_variable(value1).astype("float32")
            v2 = fluid.dygraph.to_variable(value2).astype("float32")
464
            case3 = AutoPruneLayer2(input_size=784)
465 466
            loss = case3(v1, v2)
            loss.backward()
467 468
            self.assertIsNone(case3.linear2.weight._grad_ivar())
            self.assertIsNotNone(case3.linear.weight._grad_ivar())
469

470 471 472 473 474 475
    def test_case2_prune_no_grad_branch(self):
        with _test_eager_guard():
            self.func_case2_prune_no_grad_branch()
        self.func_case2_prune_no_grad_branch()

    def func_case3_prune_no_grad_branch2(self):
476 477
        with fluid.dygraph.guard():
            value1 = np.arange(1).reshape(1, 1)
478
            linear = paddle.nn.Linear(1, 1)
479
            label = fluid.dygraph.to_variable(value1).astype("float32")
480
            label = linear(label)
481 482 483
            label = fluid.layers.cast(label, dtype="float32")
            label = fluid.layers.cast(label, dtype='int64')
            out = fluid.layers.one_hot(input=label, depth=100)
484
            loss = paddle.mean(out)
485
            loss.backward()
486
            self.assertIsNone(linear.weight._grad_ivar())
487

488 489 490 491 492 493
    def test_case3_prune_no_grad_branch2(self):
        with _test_eager_guard():
            self.func_case3_prune_no_grad_branch2()
        self.func_case3_prune_no_grad_branch2()

    def func_case4_with_no_grad_op_maker(self):
494
        with fluid.dygraph.guard():
495
            out = random.gaussian(shape=[20, 30])
496
            loss = paddle.mean(out)
497
            loss.backward()
498
            self.assertIsNone(out._grad_ivar())
499

500 501 502 503 504
    def test_case4_with_no_grad_op_maker(self):
        with _test_eager_guard():
            self.func_case4_with_no_grad_op_maker()
        self.func_case4_with_no_grad_op_maker()

505 506 507

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