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


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

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


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

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


class AutoPruneLayer2(fluid.Layer):
66 67 68 69
    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)
70 71

    def forward(self, x, label):
72 73
        feature = self.linear(x)
        label = self.linear2(label)
74 75 76 77 78 79 80 81 82
        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):
83 84 85
    def __init__(self, input_size):
        super(AutoPruneLayer3, self).__init__()
        self.linear = fluid.dygraph.Linear(input_size, 20, act=None)
86 87

    def forward(self, x, label, test_num):
88
        feature = self.linear(x)
89 90 91 92 93 94 95 96 97 98 99 100
        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):
101 102
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
        super(MyLayer, self).__init__(dtype=dtype)
103 104
        self.embed0 = fluid.Embedding(size=(vocab_size, size))
        self.embed1 = fluid.Embedding(size=(vocab_size, size))
105 106
        self.linear_0 = fluid.Linear(input_size, size, dtype=dtype)
        self.linear_1 = fluid.Linear(input_size, size, dtype=dtype)
107 108

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

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

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


class MyLayer2(fluid.Layer):
123 124
    def __init__(self, input_size, vocab_size, size, dtype="float32"):
        super(MyLayer2, self).__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 = fluid.Linear(input_size, size, dtype=dtype)
        self.linear_1 = fluid.Linear(input_size, size, dtype=dtype)
129 130 131 132 133

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

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

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


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

    def test_auto_prune2(self):
        with fluid.dygraph.guard():
162
            case2 = AutoPruneLayer1(input_size=5)
163 164 165 166 167
            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 已提交
168

169
            loss.backward()
170 171
            self.assertTrue(case2.linear2.weight._grad_ivar() is None)
            self.assertTrue(case2.linear1.weight._grad_ivar() is not None)
172 173 174

    def test_auto_prune3(self):
        with fluid.dygraph.guard():
175
            case3 = AutoPruneLayer3(input_size=784)
176 177 178 179 180 181
            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()
182
            self.assertTrue(case3.linear.weight._grad_ivar() is not None)
183 184 185 186
            self.assertTrue((part2.gradient() == 0).all())

    def test_auto_prune4(self):
        with fluid.dygraph.guard():
187
            case4 = 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 = case4(v1, v2, 1)
            part2.backward()
194
            self.assertTrue(case4.linear.weight._grad_ivar() is not None)
195 196 197 198
            self.assertTrue((part2.gradient() == 1).all())

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

    def test_auto_prune6(self):
        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")
214 215
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(3, 3, dtype="float32")
216 217 218
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
219 220
            out1 = linear(a)
            out2 = linear2(b)
221 222 223
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
            out.backward()
224
            self.assertTrue((linear.weight.gradient() == 0).all())
225 226 227 228 229 230 231
            self.assertTrue((out1.gradient() == 0).all())

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

    def test_auto_prune8(self):
        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")
251 252
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(5, 3, dtype="float32")
253 254 255
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
256 257 258 259 260
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
            linear2.weight.stop_gradient = True
261
            out2.backward()
262 263
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
264
                parameter_list=(linear.parameters() + linear2.parameters()))
265
            optimizer.minimize(out2)
266 267 268 269
            self.assertTrue(
                np.array_equal(linear2_origin, linear2.weight.numpy()))
            self.assertFalse(
                np.array_equal(linear_origin, linear.weight.numpy()))
270 271 272 273 274 275

    def test_auto_prune9(self):
        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")
276 277
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(5, 3, dtype="float32")
278 279 280
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
281 282 283 284
            out1 = linear(a)
            linear_origin = linear.weight.numpy()
            out2 = linear2(out1)
            linear2_origin = linear2.weight.numpy()
285 286
            out2.stop_gradient = True
            out2.backward()
287 288
            optimizer = fluid.optimizer.SGD(
                learning_rate=0.003,
289
                parameter_list=(linear.parameters() + linear2.parameters()))
290
            optimizer.minimize(out2)
291 292 293 294
            self.assertTrue(
                np.array_equal(linear2_origin, linear2.weight.numpy()))
            self.assertTrue(
                np.array_equal(linear_origin, linear.weight.numpy()))
295
            try:
296
                linear2.weight.gradient()
297 298 299 300 301 302 303 304
            except ValueError as e:
                assert type(e) == ValueError

    def test_auto_prune10(self):
        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")
305 306
            linear = fluid.Linear(13, 5, dtype="float32")
            linear2 = fluid.Linear(3, 3, dtype="float32")
307 308 309
            a = fluid.dygraph.to_variable(value0)
            b = fluid.dygraph.to_variable(value1)
            c = fluid.dygraph.to_variable(value2)
310 311
            out1 = linear(a)
            out2 = linear2(b)
312 313 314 315 316
            out1.stop_gradient = True
            out = fluid.layers.concat(input=[out1, out2, c], axis=1)
            backward_strategy = fluid.dygraph.BackwardStrategy()
            backward_strategy.sort_sum_gradient = True
            out.backward(backward_strategy)
317
            self.assertTrue((linear.weight.gradient() == 0).all())
318 319 320 321 322 323 324 325 326 327 328 329 330
            self.assertTrue((out1.gradient() == 0).all())

    def test_auto_prune_with_optimizer(self):
        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):
331
            model = MyLayer(size, vocab_size, size)
332 333
            optimizer = fluid.optimizer.AdamOptimizer(
                0.001, parameter_list=model.parameters())
334 335 336
            grad_clip = fluid.dygraph_grad_clip.GradClipByGlobalNorm(0.001)

            indices = fluid.dygraph.to_variable(indices)
337
            embed = fluid.dygraph.to_variable(embed)
338 339 340 341 342 343
            dummy_loss = model(embed)

            loss = model.embed_linear0(indices)
            loss.backward()
            _, params_grads = optimizer.minimize(loss, grad_clip=grad_clip)
            for items in params_grads:
344
                assert items[0].name is not model.embed1.weight.name
345
                assert items[0].name is not model.linear_1.weight.name
346
            assert model.embed1.weight._grad_ivar() is None
347
            assert model.linear_1.weight._grad_ivar() is None
348 349

        with fluid.dygraph.guard(place):
350
            model = MyLayer2(size, vocab_size, size)
351 352
            optimizer = fluid.optimizer.AdamOptimizer(
                0.001, parameter_list=model.parameters())
353 354 355 356 357 358 359 360 361 362
            grad_clip = fluid.dygraph_grad_clip.GradClipByGlobalNorm(0.001)

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

            loss = model.embed_linear0(indices)
            loss.backward()
            optimizer.minimize(loss, grad_clip=grad_clip)
            for items in params_grads:
363
                assert items[0].name is not model.embed1.weight.name
364
                assert items[0].name is not model.linear_1.weight.name
365
            assert model.embed1.weight._grad_ivar() is None
366
            assert model.linear_1.weight._grad_ivar() is None
367 368 369 370 371 372 373

    def test_case2_prune_no_grad_branch(self):
        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")
374
            case3 = AutoPruneLayer2(input_size=784)
375 376
            loss = case3(v1, v2)
            loss.backward()
377 378
            self.assertTrue(case3.linear2.weight._grad_ivar() is None)
            self.assertTrue(case3.linear.weight._grad_ivar() is not None)
379 380 381 382 383 384 385

    def test_case2_prune_no_grad_branch(self):
        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")
386
            case3 = AutoPruneLayer2(input_size=784)
387 388
            loss = case3(v1, v2)
            loss.backward()
389 390
            self.assertTrue(case3.linear2.weight._grad_ivar() is None)
            self.assertTrue(case3.linear.weight._grad_ivar() is not None)
391 392 393 394

    def test_case3_prune_no_grad_branch2(self):
        with fluid.dygraph.guard():
            value1 = np.arange(1).reshape(1, 1)
395
            linear = fluid.dygraph.Linear(1, 1, act=None)
396
            label = fluid.dygraph.to_variable(value1).astype("float32")
397
            label = linear(label)
398 399 400 401 402
            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()
403
            self.assertTrue(linear.weight._grad_ivar() is None)
404 405 406 407 408 409

    def test_case4_with_no_grad_op_maker(self):
        with fluid.dygraph.guard():
            out = fluid.layers.gaussian_random(shape=[20, 30])
            loss = fluid.layers.mean(out)
            loss.backward()
410
            self.assertTrue(out._grad_ivar() is None)
411 412 413 414


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