prune_config.py 12.1 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 numpy as np
import os.path as osp
import paddle.fluid as fluid
J
jiangjiajun 已提交
18
#import paddlehub as hub
J
jiangjiajun 已提交
19 20 21
import paddlex

sensitivities_data = {
S
sunyanfang01 已提交
22 23
    'AlexNet':
    'https://bj.bcebos.com/paddlex/slim_prune/alexnet_sensitivities.data',
J
jiangjiajun 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    'ResNet18':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet18.sensitivities',
    'ResNet34':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet34.sensitivities',
    'ResNet50':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet50.sensitivities',
    'ResNet101':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet101.sensitivities',
    'ResNet50_vd':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet50vd.sensitivities',
    'ResNet101_vd':
    'https://bj.bcebos.com/paddlex/slim_prune/resnet101vd.sensitivities',
    'DarkNet53':
    'https://bj.bcebos.com/paddlex/slim_prune/darknet53.sensitivities',
    'MobileNetV1':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv1.sensitivities',
    'MobileNetV2':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv2.sensitivities',
    'MobileNetV3_large':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_large.sensitivities',
    'MobileNetV3_small':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_small.sensitivities',
S
sunyanfang01 已提交
46 47 48 49
    'MobileNetV3_large_ssld':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_large_ssld_sensitivities.data',
    'MobileNetV3_small_ssld':
    'https://bj.bcebos.com/paddlex/slim_prune/mobilenetv3_small_ssld_sensitivities.data',
J
jiangjiajun 已提交
50 51 52 53 54 55 56 57 58 59
    'DenseNet121':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet121.sensitivities',
    'DenseNet161':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet161.sensitivities',
    'DenseNet201':
    'https://bj.bcebos.com/paddlex/slim_prune/densenet201.sensitivities',
    'Xception41':
    'https://bj.bcebos.com/paddlex/slim_prune/xception41.sensitivities',
    'Xception65':
    'https://bj.bcebos.com/paddlex/slim_prune/xception65.sensitivities',
S
sunyanfang01 已提交
60 61
    'ShuffleNetV2':
    'https://bj.bcebos.com/paddlex/slim_prune/shufflenetv2_sensitivities.data',
J
jiangjiajun 已提交
62 63 64 65 66 67 68 69
    'YOLOv3_MobileNetV1':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_mobilenetv1.sensitivities',
    'YOLOv3_MobileNetV3_large':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_mobilenetv3.sensitivities',
    'YOLOv3_DarkNet53':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_darknet53.sensitivities',
    'YOLOv3_ResNet34':
    'https://bj.bcebos.com/paddlex/slim_prune/yolov3_resnet34.sensitivities',
70
    'UNet': 'https://bj.bcebos.com/paddlex/slim_prune/unet.sensitivities',
J
jiangjiajun 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
    'DeepLabv3p_MobileNetV2_x0.25':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.25_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.5':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.5_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.0':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.0_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.5':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.5_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x2.0':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x2.0_no_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.25_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.25_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x0.5_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x0.5_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.0_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.0_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x1.5_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x1.5_with_aspp_decoder.sensitivities',
    'DeepLabv3p_MobileNetV2_x2.0_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_mobilenetv2_x2.0_with_aspp_decoder.sensitivities',
    'DeepLabv3p_Xception65_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_xception65_with_aspp_decoder.sensitivities',
    'DeepLabv3p_Xception41_aspp_decoder':
    'https://bj.bcebos.com/paddlex/slim_prune/deeplab_xception41_with_aspp_decoder.sensitivities'
}


def get_sensitivities(flag, model, save_dir):
    model_name = model.__class__.__name__
    model_type = model_name
    if hasattr(model, 'backbone'):
        model_type = model_name + '_' + model.backbone
    if model_type.startswith('DeepLabv3p_Xception'):
        model_type = model_type + '_' + 'aspp' + '_' + 'decoder'
105 106
    elif hasattr(model, 'encoder_with_aspp') or hasattr(model,
                                                        'enable_decoder'):
J
jiangjiajun 已提交
107 108 109 110 111 112 113 114
        model_type = model_type + '_' + 'aspp' + '_' + 'decoder'
    if osp.isfile(flag):
        return flag
    elif flag == 'DEFAULT':
        assert model_type in sensitivities_data, "There is not sensitivities data file for {}, you may need to calculate it by your self.".format(
            model_type)
        url = sensitivities_data[model_type]
        fname = osp.split(url)[-1]
J
jiangjiajun 已提交
115
        paddlex.utils.download(url, path=save_dir)
J
jiangjiajun 已提交
116
        return osp.join(save_dir, fname)
J
jiangjiajun 已提交
117 118 119 120 121 122 123 124 125 126

#        try:
#            hub.download(fname, save_path=save_dir)
#        except Exception as e:
#            if isinstance(e, hub.ResourceNotFoundError):
#                raise Exception(
#                    "Resource for model {}(key='{}') not found".format(
#                        model_type, fname))
#            elif isinstance(e, hub.ServerConnectionError):
#                raise Exception(
127
#                    "Cannot get reource for model {}(key='{}'), please check your internet connection"
J
jiangjiajun 已提交
128 129 130 131 132 133
#                    .format(model_type, fname))
#            else:
#                raise Exception(
#                    "Unexpected error, please make sure paddlehub >= 1.6.2 {}".
#                    format(str(e)))
#        return osp.join(save_dir, fname)
J
jiangjiajun 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    else:
        raise Exception(
            "sensitivities need to be defined as directory path or `DEFAULT`(download sensitivities automatically)."
        )


def get_prune_params(model):
    prune_names = []
    model_type = model.__class__.__name__
    if model_type == 'BaseClassifier':
        model_type = model.model_name
    if hasattr(model, 'backbone'):
        backbone = model.backbone
        model_type += ('_' + backbone)
    program = model.test_prog
    if model_type.startswith('ResNet') or \
            model_type.startswith('DenseNet') or \
S
sunyanfang01 已提交
151
            model_type.startswith('DarkNet') or \
S
sunyanfang01 已提交
152 153
            model_type.startswith('AlexNet') or \
            model_type.startswith('ShuffleNetV2'):
J
jiangjiajun 已提交
154 155 156 157 158 159
        for block in program.blocks:
            for param in block.all_parameters():
                pd_var = fluid.global_scope().find_var(param.name)
                pd_param = pd_var.get_tensor()
                if len(np.array(pd_param).shape) == 4:
                    prune_names.append(param.name)
S
sunyanfang01 已提交
160 161
        if model_type == 'AlexNet':
            prune_names.remove('conv5_weights')
S
sunyanfang01 已提交
162
        if model_type == 'ShuffleNetV2':
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
            not_prune_names = [
                'stage_2_1_conv5_weights',
                'stage_2_1_conv3_weights',
                'stage_2_2_conv3_weights',
                'stage_2_3_conv3_weights',
                'stage_2_4_conv3_weights',
                'stage_3_1_conv5_weights',
                'stage_3_1_conv3_weights',
                'stage_3_2_conv3_weights',
                'stage_3_3_conv3_weights',
                'stage_3_4_conv3_weights',
                'stage_3_5_conv3_weights',
                'stage_3_6_conv3_weights',
                'stage_3_7_conv3_weights',
                'stage_3_8_conv3_weights',
                'stage_4_1_conv5_weights',
                'stage_4_1_conv3_weights',
                'stage_4_2_conv3_weights',
                'stage_4_3_conv3_weights',
                'stage_4_4_conv3_weights',
            ]
S
sunyanfang01 已提交
184
            for name in not_prune_names:
185
                prune_names.remove(name)
J
jiangjiajun 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
    elif model_type == "MobileNetV1":
        prune_names.append("conv1_weights")
        for param in program.global_block().all_parameters():
            if "_sep_weights" in param.name:
                prune_names.append(param.name)
    elif model_type == "MobileNetV2":
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name \
                    or 'dwise' in param.name \
                    or 'fc' in param.name :
                continue
            prune_names.append(param.name)
    elif model_type.startswith("MobileNetV3"):
S
sunyanfang01 已提交
199
        if model_type.startswith('MobileNetV3_small'):
J
jiangjiajun 已提交
200 201 202 203 204 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
            expand_prune_id = [3, 4]
        else:
            expand_prune_id = [2, 3, 4, 8, 9, 11]
        for param in program.global_block().all_parameters():
            if ('expand_weights' in param.name and \
                    int(param.name.split('_')[0][4:]) in expand_prune_id)\
                    or 'linear_weights' in param.name \
                    or 'se_1_weights' in param.name:
                prune_names.append(param.name)
    elif model_type.startswith('Xception') or \
            model_type.startswith('DeepLabv3p_Xception'):
        params_not_prune = [
            'weights',
            'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'.
            format(model_type[-2:]), 'encoder/concat/weights',
            'decoder/concat/weights'
        ]
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name \
                    or 'dwise' in param.name \
                    or 'depthwise' in param.name \
                    or 'logit' in param.name:
                continue
            if param.name in params_not_prune:
                continue
            prune_names.append(param.name)
    elif model_type.startswith('YOLOv3'):
        for block in program.blocks:
            for param in block.all_parameters():
                if 'weights' in param.name and 'yolo_block' in param.name:
                    prune_names.append(param.name)
    elif model_type.startswith('UNet'):
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            if 'logit' in param.name:
                continue
            prune_names.append(param.name)
        params_not_prune = [
            'encode/block4/down/conv1/weights',
            'encode/block3/down/conv1/weights',
            'encode/block2/down/conv1/weights', 'encode/block1/conv1/weights'
        ]
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)

    elif model_type.startswith('DeepLabv3p'):
        for param in program.global_block().all_parameters():
            if 'weight' not in param.name:
                continue
            if 'dwise' in param.name or 'depthwise' in param.name or 'logit' in param.name:
                continue
            prune_names.append(param.name)
        params_not_prune = [
            'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'.
            format(model_type[-2:]), 'encoder/concat/weights',
            'decoder/concat/weights'
        ]
        if model.encoder_with_aspp == True:
            params_not_prune.append(
                'xception_{}/exit_flow/block2/separable_conv3/pointwise/weights'
                .format(model_type[-2:]))
            params_not_prune.append('conv8_1_linear_weights')
        for i in params_not_prune:
            if i in prune_names:
                prune_names.remove(i)
    else:
        raise Exception('The {} is not implement yet!'.format(model_type))
    return prune_names