test_imperative_auto_prune.py 18.5 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
import paddle.fluid as fluid
import numpy as np
18
from paddle.fluid.framework import _test_eager_guard
19 20 21


class AutoPruneLayer0(fluid.Layer):
22 23 24 25
    def __init__(self, input_size):
        super(AutoPruneLayer0, self).__init__()
        self.linear1 = fluid.dygraph.Linear(
            input_size,
26 27 28
            5,
            param_attr=fluid.initializer.ConstantInitializer(value=2),
            bias_attr=False)
29 30
        self.linear2 = fluid.dygraph.Linear(
            5,
31 32 33 34 35
            5,
            param_attr=fluid.initializer.ConstantInitializer(value=2),
            bias_attr=False)

    def forward(self, x, y):
36 37
        a = self.linear1(x)
        b = self.linear2(y)
38 39 40 41 42 43
        c = fluid.layers.mul(a, b)
        d = fluid.layers.reduce_mean(c)
        return d


class AutoPruneLayer1(fluid.Layer):
44 45 46 47
    def __init__(self, input_size):
        super(AutoPruneLayer1, self).__init__()
        self.linear1 = fluid.dygraph.Linear(
            input_size,
48 49 50
            5,
            param_attr=fluid.initializer.ConstantInitializer(value=2),
            bias_attr=False)
51 52
        self.linear2 = fluid.dygraph.Linear(
            5,
53 54 55 56 57
            5,
            param_attr=fluid.initializer.ConstantInitializer(value=2),
            bias_attr=False)

    def forward(self, x, y):
58 59
        a = self.linear1(x)
        b = self.linear2(y)
60 61 62 63 64 65 66
        b.stop_gradient = True
        c = fluid.layers.mul(a, b)
        d = fluid.layers.reduce_mean(c)
        return d


class AutoPruneLayer2(fluid.Layer):
67 68 69 70
    def __init__(self, input_size):
        super(AutoPruneLayer2, self).__init__()
        self.linear = fluid.dygraph.Linear(input_size, 10, act=None)
        self.linear2 = fluid.dygraph.Linear(1, 1, act=None)
71 72

    def forward(self, x, label):
73 74
        feature = self.linear(x)
        label = self.linear2(label)
75 76 77 78 79 80 81 82 83
        label = fluid.layers.cast(label, dtype="float32")
        label = fluid.layers.cast(label, dtype='int64')
        # Note that the label is not persistable in fluid.layers.cross_entropy.
        loss = fluid.layers.cross_entropy(input=feature, label=label)
        loss = fluid.layers.mean(loss)
        return loss


class AutoPruneLayer3(fluid.Layer):
84 85 86
    def __init__(self, input_size):
        super(AutoPruneLayer3, self).__init__()
        self.linear = fluid.dygraph.Linear(input_size, 20, act=None)
87 88

    def forward(self, x, label, test_num):
89
        feature = self.linear(x)
90 91 92 93 94 95 96 97 98 99 100 101
        part1, part2 = fluid.layers.split(
            feature, num_or_sections=[10, 10], dim=1)
        # Note that: part2 is not used.
        loss = fluid.layers.cross_entropy(input=part1, label=label)
        loss = fluid.layers.mean(loss)
        if test_num == 1:
            return loss, part2
        else:
            return loss, part1, part2


class MyLayer(fluid.Layer):
102 103
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
        super(MyLayer, self).__init__(dtype=dtype)
104 105
        self.embed0 = fluid.Embedding(size=(vocab_size, size))
        self.embed1 = fluid.Embedding(size=(vocab_size, size))
106 107
        self.linear_0 = fluid.Linear(input_size, size, dtype=dtype)
        self.linear_1 = fluid.Linear(input_size, size, dtype=dtype)
108 109

    def forward(self, x):
110 111
        # this method involves only the linear layers
        loss = fluid.layers.reduce_mean(self.linear_0(x) + self.linear_1(x))
112 113 114
        return loss

    def linear0(self, x):
115
        loss = fluid.layers.reduce_mean(self.linear_0(x))
116 117 118
        return loss

    def embed_linear0(self, x):
119
        loss = fluid.layers.reduce_mean(self.linear_0(self.embed0(x)))
120 121 122 123
        return loss


class MyLayer2(fluid.Layer):
124 125
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
        super(MyLayer2, self).__init__(dtype=dtype)
126 127
        self.embed0 = fluid.Embedding(size=(vocab_size, size))
        self.embed1 = fluid.Embedding(size=(vocab_size, size))
128 129
        self.linear_0 = fluid.Linear(input_size, size, dtype=dtype)
        self.linear_1 = fluid.Linear(input_size, size, dtype=dtype)
130 131 132 133 134

    def forward(self, indices):
        # mind the difference with MyLayer
        # In this example, the forward method involes all params
        loss = fluid.layers.reduce_mean(
135 136
            self.linear_0(self.embed0(indices)) + self.linear_1(
                self.embed1(indices)))
137 138 139
        return loss

    def linear0(self, x):
140
        loss = fluid.layers.reduce_mean(self.linear_0(x))
141 142 143
        return loss

    def embed_linear0(self, x):
144
        loss = fluid.layers.reduce_mean(self.linear_0(self.embed0(x)))
145 146 147 148
        return loss


class TestImperativeAutoPrune(unittest.TestCase):
149
    def func_auto_prune(self):
150
        with fluid.dygraph.guard():
151
            case1 = AutoPruneLayer0(input_size=5)
152 153 154 155 156 157
            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()
158 159
            self.assertTrue(case1.linear2.weight._grad_ivar() is not None)
            self.assertTrue(case1.linear1.weight._grad_ivar() is not None)
160

161 162 163 164 165 166
    def test_auto_prune(self):
        with _test_eager_guard():
            self.func_auto_prune()
        self.func_auto_prune()

    def func_auto_prune2(self):
167
        with fluid.dygraph.guard():
168
            case2 = AutoPruneLayer1(input_size=5)
169 170 171 172 173
            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 已提交
174

175
            loss.backward()
176 177
            self.assertTrue(case2.linear2.weight._grad_ivar() is None)
            self.assertTrue(case2.linear1.weight._grad_ivar() is not None)
178

179 180 181 182 183
    def test_auto_prune2(self):
        with _test_eager_guard():
            self.func_auto_prune2()
        self.func_auto_prune2()

184
    # TODO(jiabin): Support this when we support better split tensor
185
    def func_auto_prune3(self):
186
        with fluid.dygraph.guard():
187
            case3 = AutoPruneLayer3(input_size=784)
188 189 190 191 192 193
            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()
194
            self.assertTrue(case3.linear.weight._grad_ivar() is not None)
195 196
            self.assertTrue((part2.gradient() == 0).all())

197 198 199 200 201 202
    def test_auto_prune3(self):
        with _test_eager_guard():
            self.func_auto_prune3()
        self.func_auto_prune3()

    def func_auto_prune4(self):
203
        with fluid.dygraph.guard():
204
            case4 = AutoPruneLayer3(input_size=784)
205 206 207 208 209 210
            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()
211
            self.assertTrue(case4.linear.weight._grad_ivar() is not None)
212 213
            self.assertTrue((part2.gradient() == 1).all())

214 215 216 217 218 219
    def test_auto_prune4(self):
        with _test_eager_guard():
            self.func_auto_prune4()
        self.func_auto_prune4()

    def func_auto_prune5(self):
220
        with fluid.dygraph.guard():
221
            case4 = AutoPruneLayer3(input_size=784)
222 223 224 225 226 227
            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()
228
            self.assertTrue(case4.linear.weight._grad_ivar() is not None)
229 230
            self.assertTrue((part2.gradient() == 0).all())

231 232 233 234 235
    def test_auto_prune5(self):
        with _test_eager_guard():
            self.func_auto_prune5()
        self.func_auto_prune5()

236
    def func_auto_prune6(self):
237 238 239 240
        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")
241 242
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(3, 3, dtype="float32")
243 244 245
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
246 247
            out1 = linear(a)
            out2 = linear2(b)
248 249 250
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
            out.backward()
251
            self.assertTrue(linear.weight.gradient() is None)
252
            self.assertTrue(out1.gradient() is None)
253

254 255 256 257 258 259
    def test_auto_prune6(self):
        with _test_eager_guard():
            self.func_auto_prune6()
        self.func_auto_prune6()

    def func_auto_prune7(self):
260 261 262 263
        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")
264 265
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(3, 3, dtype="float32")
266 267 268
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
269 270
            out1 = linear(a)
            out2 = linear2(b)
271 272
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
273
            out.backward()
274
            self.assertTrue(linear.weight.gradient() is None)
275
            self.assertTrue(out1.gradient() is None)
276

277 278 279 280 281 282
    def test_auto_prune7(self):
        with _test_eager_guard():
            self.func_auto_prune7()
        self.func_auto_prune7()

    def func_auto_prune8(self):
283 284 285 286
        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")
287 288
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(5, 3, dtype="float32")
289 290 291
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
292 293 294 295 296
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
            linear2.weight.stop_gradient = True
297
            out2.backward()
298 299
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
300
                parameter_list=(linear.parameters() + linear2.parameters()))
301
            optimizer.minimize(out2)
302 303 304 305
            self.assertTrue(
                np.array_equal(linear2_origin, linear2.weight.numpy()))
            self.assertFalse(
                np.array_equal(linear_origin, linear.weight.numpy()))
306

307 308 309 310 311 312
    def test_auto_prune8(self):
        with _test_eager_guard():
            self.func_auto_prune8()
        self.func_auto_prune8()

    def func_auto_prune9(self):
313 314 315 316
        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")
317 318
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(5, 3, dtype="float32")
319 320 321
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
322 323 324 325
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
326 327
            out2.stop_gradient = True
            out2.backward()
328 329
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
330
                parameter_list=(linear.parameters() + linear2.parameters()))
331
            optimizer.minimize(out2)
332 333 334 335
            self.assertTrue(
                np.array_equal(linear2_origin, linear2.weight.numpy()))
            self.assertTrue(
                np.array_equal(linear_origin, linear.weight.numpy()))
336
            try:
337
                linear2.weight.gradient()
338 339 340
            except ValueError as e:
                assert type(e) == ValueError

341 342 343 344 345 346
    def test_auto_prune9(self):
        with _test_eager_guard():
            self.func_auto_prune9()
        self.func_auto_prune9()

    def func_auto_prune10(self):
347 348 349 350
        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")
351 352
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(3, 3, dtype="float32")
353 354 355
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
356 357
            out1 = linear(a)
            out2 = linear2(b)
358 359
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
360
            #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.
361 362
            fluid.set_flags({'FLAGS_sort_sum_gradient': True})
            out.backward()
363
            self.assertTrue(linear.weight.gradient() is None)
364
            self.assertTrue(out1.gradient() is None)
365

366 367 368 369 370 371
    def test_auto_prune10(self):
        with _test_eager_guard():
            self.func_auto_prune10()
        self.func_auto_prune10()

    def func_auto_prune_with_optimizer(self):
372 373 374 375 376 377 378 379 380 381
        vocab_size = 100
        size = 20
        batch_size = 16

        indices = np.random.randint(
            low=0, high=100, size=(batch_size, 1)).astype("int64")
        embed = np.random.randn(batch_size, size).astype("float32")

        place = fluid.CPUPlace()
        with fluid.dygraph.guard(place):
382
            model = MyLayer(size, vocab_size, size)
383
            grad_clip = fluid.clip.GradientClipByGlobalNorm(0.001)
384 385
            optimizer = fluid.optimizer.AdamOptimizer(
                0.001, parameter_list=model.parameters(), grad_clip=grad_clip)
386
            indices = fluid.dygraph.to_variable(indices)
387
            embed = fluid.dygraph.to_variable(embed)
388 389 390 391
            dummy_loss = model(embed)

            loss = model.embed_linear0(indices)
            loss.backward()
392
            _, params_grads = optimizer.minimize(loss)
393
            for items in params_grads:
394
                assert items[0].name is not model.embed1.weight.name
395
                assert items[0].name is not model.linear_1.weight.name
396
            assert model.embed1.weight._grad_ivar() is None
397
            assert model.linear_1.weight._grad_ivar() is None
398 399

        with fluid.dygraph.guard(place):
400
            model = MyLayer2(size, vocab_size, size)
401
            grad_clip = fluid.clip.GradientClipByGlobalNorm(0.001)
402 403
            optimizer = fluid.optimizer.AdamOptimizer(
                0.001, parameter_list=model.parameters(), grad_clip=grad_clip)
404 405 406 407 408 409 410

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

            loss = model.embed_linear0(indices)
            loss.backward()
411
            optimizer.minimize(loss)
412
            for items in params_grads:
413
                assert items[0].name is not model.embed1.weight.name
414
                assert items[0].name is not model.linear_1.weight.name
415
            assert model.embed1.weight._grad_ivar() is None
416
            assert model.linear_1.weight._grad_ivar() is None
417

418 419 420 421 422 423
    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):
424 425 426 427 428
        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")
429
            case3 = AutoPruneLayer2(input_size=784)
430 431
            loss = case3(v1, v2)
            loss.backward()
432 433
            self.assertTrue(case3.linear2.weight._grad_ivar() is None)
            self.assertTrue(case3.linear.weight._grad_ivar() is not None)
434

435 436 437 438 439 440
    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):
441 442
        with fluid.dygraph.guard():
            value1 = np.arange(1).reshape(1, 1)
443
            linear = fluid.dygraph.Linear(1, 1, act=None)
444
            label = fluid.dygraph.to_variable(value1).astype("float32")
445
            label = linear(label)
446 447 448 449 450
            label = fluid.layers.cast(label, dtype="float32")
            label = fluid.layers.cast(label, dtype='int64')
            out = fluid.layers.one_hot(input=label, depth=100)
            loss = fluid.layers.mean(out)
            loss.backward()
451
            self.assertTrue(linear.weight._grad_ivar() is None)
452

453 454 455 456 457 458
    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):
459 460 461 462
        with fluid.dygraph.guard():
            out = fluid.layers.gaussian_random(shape=[20, 30])
            loss = fluid.layers.mean(out)
            loss.backward()
463
            self.assertTrue(out._grad_ivar() is None)
464

465 466 467 468 469
    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()

470 471 472

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