test_asp_pruning_static.py 4.7 KB
Newer Older
1 2
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
# Copyright (c) 2022 NVIDIA Corporation.  All rights reserved.
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
#
8
#     http://www.apache.org/licenses/LICENSE-2.0
9
#
10 11 12 13 14 15 16
# 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
17 18 19

import numpy as np

20
import paddle
21 22
from paddle import fluid
from paddle.fluid import core
23
from paddle.incubate.asp import ASPHelper
24 25 26 27 28 29 30 31 32 33

paddle.enable_static()


class TestASPStaticPruningBase(unittest.TestCase):
    def setUp(self):
        self.main_program = fluid.Program()
        self.startup_program = fluid.Program()

        def build_model():
34
            img = paddle.static.data(
35 36
                name='img', shape=[None, 3, 24, 24], dtype='float32'
            )
37 38 39
            label = paddle.static.data(
                name='label', shape=[None, 1], dtype='int64'
            )
40
            hidden = paddle.static.nn.conv2d(
41 42
                input=img, num_filters=2, filter_size=3, padding=2, act="relu"
            )
C
Charles-hit 已提交
43 44 45 46 47 48 49
            hidden = paddle.static.nn.fc(
                x=hidden, size=32, activation='softmax'
            )
            hidden = paddle.static.nn.fc(x=hidden, size=3, activation='softmax')
            prediction = paddle.static.nn.fc(
                x=hidden, size=3, activation='softmax'
            )
50 51 52 53 54 55 56 57 58
            return img, label, prediction

        with fluid.program_guard(self.main_program, self.startup_program):
            self.img, self.label, self.predict = build_model()

        self.set_config()

    def set_config(self):
        self.mask_gen_func = 'mask_1d'
59
        self.mask_check_func = paddle.incubate.asp.CheckMethod.CHECK_1D
60 61 62 63 64 65 66 67 68 69 70

    def test_inference_pruning(self):
        place = paddle.CPUPlace()
        if core.is_compiled_with_cuda():
            place = paddle.CUDAPlace(0)
        exe = fluid.Executor(place)

        self.__pruning_and_checking(exe, place, False)

    def test_training_pruning(self):
        with fluid.program_guard(self.main_program, self.startup_program):
71
            loss = paddle.mean(
72 73 74 75 76 77
                paddle.nn.functional.cross_entropy(
                    input=self.predict,
                    label=self.label,
                    reduction='none',
                    use_softmax=False,
                )
78
            )
79
            optimizer = paddle.incubate.asp.decorate(
80 81
                fluid.optimizer.SGD(learning_rate=0.01)
            )
82 83 84 85 86 87 88 89 90 91 92
            optimizer.minimize(loss, self.startup_program)

        place = paddle.CPUPlace()
        if core.is_compiled_with_cuda():
            place = paddle.CUDAPlace(0)
        exe = fluid.Executor(place)

        self.__pruning_and_checking(exe, place, True)

    def __pruning_and_checking(self, exe, place, with_mask):
        exe.run(self.startup_program)
93 94 95
        paddle.incubate.asp.prune_model(
            self.main_program, mask_algo=self.mask_gen_func, with_mask=with_mask
        )
96 97
        for param in self.main_program.global_block().all_parameters():
            if ASPHelper._is_supported_layer(self.main_program, param.name):
98 99 100 101 102 103
                mat = np.array(
                    fluid.global_scope().find_var(param.name).get_tensor()
                )
                if (len(param.shape) == 4 and param.shape[1] < 4) or (
                    len(param.shape) == 2 and param.shape[0] < 4
                ):
M
minghaoBD 已提交
104
                    self.assertFalse(
105
                        paddle.incubate.asp.check_sparsity(mat.T, n=2, m=4)
106
                    )
M
minghaoBD 已提交
107 108
                else:
                    self.assertTrue(
109
                        paddle.incubate.asp.check_sparsity(
110 111 112
                            mat.T, func_name=self.mask_check_func, n=2, m=4
                        )
                    )
113 114 115 116 117


class TestASPStaticPruning1D(TestASPStaticPruningBase):
    def set_config(self):
        self.mask_gen_func = 'mask_1d'
118
        self.mask_check_func = paddle.incubate.asp.CheckMethod.CHECK_1D
119 120 121 122 123


class TestASPStaticPruning2DBest(TestASPStaticPruningBase):
    def set_config(self):
        self.mask_gen_func = 'mask_2d_best'
124
        self.mask_check_func = paddle.incubate.asp.CheckMethod.CHECK_2D
125 126 127 128 129


class TestASPStaticPruning2DGreedy(TestASPStaticPruningBase):
    def set_config(self):
        self.mask_gen_func = 'mask_2d_greedy'
130
        self.mask_check_func = paddle.incubate.asp.CheckMethod.CHECK_2D
131 132 133 134


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